Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 21: Local AI Models

Week 21 / Lesson 2

Serving and benchmarking a local model

Operate a local endpoint and measure prompt processing, decoding, and concurrent load.

Section 2.1 1 of 7

Overview

Focus

Operate a local endpoint and measure prompt processing, decoding, and concurrent load.

Your route through the lesson

  • 2.2 Runtime setup and local serving
  • 2.3 Processor and accelerator inference and key-value caches
  • 2.4 Throughput, batching, and latency tradeoffs
  • 2.5 Put it into practice
  • 2.6 Guided comparison
  • 2.7 Batching that improves throughput and worsens latency

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 2.2 2 of 7

Runtime setup and local serving

Focus

Use a local serving interface and separate warm-up from measured requests.

A serving runtime loads model artifacts and accepts inference requests through a stable interface. For this lab, the loopback address 127.0.0.1 reaches the same computer, and port 11434 identifies the Ollama listener. A POST request carries generation parameters as JSON. Streaming returns successive JSON records rather than waiting for one complete answer.

The generation interface supplies final usage and duration fields. The lab's HTTP client reads each response line, records the first nonempty generated text, and retains the final completion record. Its visible first-token measurement includes local transport and client handling; it does not claim to observe an internal accelerator event.

Warm-up is a separate request that allows initial loading before steady-state measurements. Record cold-start behavior separately if startup matters to the application. Keep prompt text, context limit, output cap, temperature, runtime version, and artifact identity fixed across a comparison. If two models tokenize the same text differently, record their actual input token counts rather than claiming equal token lengths merely because the prompt characters match.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Why separate a warm-up request from steady-state measurements?
2. Two models receive identical text but different token counts. What should be reported?
3. The client records first nonempty streamed text. What is measured?

Section 2.3 3 of 7

Processor and accelerator inference and key-value caches

Focus

Explain processor and accelerator execution and the key-value cache.

The central processing unit runs general-purpose instructions. A graphics processing unit accelerates many parallel numeric operations when the runtime and hardware support them. Offloading weights can improve speed, but copying data and limited accelerator memory can change the tradeoff. Record which device actually ran the model rather than inferring it from the presence of a graphics card.

During prompt processing, attention produces keys and values for prior tokens. The key-value cache retains these tensors so later decoding can reuse them. Prompt processing, sometimes called prefill, handles the existing input; decoding adds output tokens step by step. Their rates need separate interpretation because the workloads differ.

Longer contexts increase cache demand. Multiple concurrent sequences usually require multiple active context states, even when weights are shared. Cache reuse between requests can also make repeated identical prompts appear faster than fresh inputs. Declare whether the benchmark tests repeated prompts, new prompts, cold cache, or warm cache. A runtime can batch work across requests, but better aggregate utilization does not guarantee shorter wait for every individual user.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. What does the key-value cache retain?
2. A machine has a graphics card. What confirms accelerator inference?
3. Repeated prompts become faster with cache reuse. What should a benchmark disclose?

Section 2.4 4 of 7

Throughput, batching, and latency tradeoffs

Focus

Calculate throughput while keeping queue delay and individual latency visible.

Throughput is completed work per unit time, such as generated tokens per second or completed requests per minute. Latency is one request's elapsed time. A system can improve throughput by batching several requests while increasing how long each waits before computation begins.

Suppose four requests generate forty tokens each. Processing them in a batch takes two seconds, giving eighty output tokens per second in aggregate. If each request waited one second for the batch to fill, a user experiences about three seconds, not two. Include admission delay, queue time, first visible token, and completion time when those matter to the workload.

For Ollama's reported decode fields, convert nanoseconds to seconds before dividing output-token count by decode duration. Keep that server-side decode rate separate from end-to-end client throughput. A bounded concurrency test asks whether two simultaneous requests remain within useful latency and memory limits. It is not a production load test. Use a fixed small number of requests and stop on overload instead of launching an unbounded stress loop on a learner's machine.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A batch generates 160 tokens in 2 seconds. What is aggregate output throughput?
2. A request queues 1 second and computes 2 seconds. What is end-to-end latency?
3. Decode duration is reported in nanoseconds. What must happen before tokens-per-second calculation?

Section 2.5 5 of 7

Put it into practice

Focus

Run a bounded two-model benchmark with real streaming inference and explicit prerequisites.

After the small model smoke test, explicitly download a second model only if hardware permits: ollama pull qwen2.5:1.5b. Use the same existing runtime and save week21.py. Run python week21.py --lesson 2 --real --model qwen2.5:0.5b --second-model qwen2.5:1.5b. Without --real, it reports that inference did not run.

concurrent.futures is a standard-library interface for running independent calls in worker threads. ThreadPoolExecutor(max_workers=2) bounds this lab to two simultaneous requests. The script warms each model, measures three sequential requests and a two-request concurrent group, then unloads that model before selecting the next. Every generation caps context at 512 and output at 24 tokens.

Observe peak process and accelerator memory during each model's interval. Output includes actual answers, wall duration, first visible token, token counts, and runtime residency. Record whether each answer is healthy for the supplied synthetic successful-backup case. If a model does not fit, stop that comparison and report the limit; do not substitute a fixture score or silently compare different workloads.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. The benchmark uses max_workers=2. What does this bound?
2. One model cannot fit. What is the valid result?
3. Why unload the first model before the next?

Section 2.6 6 of 7

Guided comparison

Focus

Interpret benchmark records without conflating speed, quality, or peak memory.

Each model report contains three sequential measurements and two concurrent measurements. Compare wall duration and first visible token distributions, not just the single fastest request. Decode tokens per second describes the reported generation stage; client wall duration includes other work. Model loading was warmed separately, so the report should not be presented as cold-start latency.

Inspect actual generated text. A very fast response that labels a successful backup failed is not a useful win for this task. Conversely, one correct synthetic classification cannot establish general reliability. Preserve the model's raw answer, the exact check applied, and the narrow sample size.

The runtime residency snapshot helps explain fit but does not supply an automatically measured peak. Add the monitored peak and device observation manually to the same record. Differences between sequential and concurrent results can suggest queueing or resource contention, but detailed cause requires additional runtime evidence. The bounded experiment demonstrates real endpoint operation and basic measurement. It leaves broad task quality, sustained overload, and production availability outside its tested scope.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A candidate is fastest but gives the wrong classification. What should the report preserve?
2. Warm-up preceded every measurement. Which claim is unsupported?
3. Two concurrent requests are slower individually. What is a plausible next investigation?

Section 2.7 7 of 7

Batching that improves throughput and worsens latency

Focus

Explain a batching decision using both aggregate work and user wait.

An internal summarizer batches eight requests and completes them in four seconds, producing eight hundred tokens. Its aggregate decode throughput is two hundred tokens per second. The previous configuration completed one hundred tokens per second, so the throughput doubled. However, the first request now waits three seconds for the batch to form before computation begins.

For an overnight document job, that delay may be acceptable if total completion improves and memory stays bounded. For an interactive help desk, the extra wait may violate a first-response target. The same runtime optimization can therefore be beneficial for one workload and unacceptable for another.

The release decision needs workload-specific limits: maximum queue age, individual latency, aggregate completion, memory, and required output quality. A routing policy might reserve a low-latency lane for interactive requests and a separate bounded batch lane for background work. Keep authorization and data retention rules in both lanes. Batching does not grant permission to merge private contexts, expose one request's content to another, or omit per-request trace identifiers.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A batch produces 800 tokens in 4 seconds. What is throughput?
2. Batching doubles throughput but adds 3 seconds of queue wait. Is it always better?
3. Private requests share a batch. What must remain enforced?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Routing inference under explicit constraints →