Engineering depth · Healthcare applications

ML Systems: From Weights to Work

Trace a neural network update, budget training and inference, compare post-training methods, and defend when adapters actually solve the problem.

8 lessons8 decision labsExportable workbook

Start with AI Fundamentals. Expect arithmetic, architectural tradeoffs and written decisions; no GPU or programming setup is required.

Your decisions save in this browser. Export a workbook to keep a portable copy.

All cases, budgets, latencies and results labeled as exercises are synthetic. Calculators show their assumptions; they do not size or certify a production system. Provider examples were checked October 24, 2026.

01

Data, objective and compute

Why machine learning changed

A timeline is useful only if it explains a change

The history of machine learning is not a sequence in which the newest model makes every earlier method obsolete. It is a sequence of changes in what we can represent, what evidence we can collect, and what computation we can afford. A modern healthcare team still uses rules, linear models, boosted trees, neural networks and human judgment. The engineering question is which combination solves a specified problem under its constraints.

Rosenblatt's 1958 perceptron work studied trainable pattern recognition. Samuel's 1959 checkers paper explored learning through experience in a game. These were different approaches to learning, not early versions of today's chat interface. They made explicit a powerful idea: useful behavior can emerge from adjusting a system with examples or experience instead of writing every decision by hand.

What made depth practical?

The 1986 Rumelhart, Hinton and Williams paper helped popularize training multilayer networks by propagating error derivatives backward. It did not invent all differentiation or every prior form of backpropagation. The important mechanism is credit assignment: when the final prediction is wrong, compute how each adjustable parameter contributed to that loss. Depth becomes trainable when that calculation is tractable and optimization actually works.

AlexNet's 2012 ImageNet result combined a deep convolutional architecture, substantial labeled image data and efficient GPU computation. Its lesson is not that a particular neuron count guarantees success. Architecture, data, optimization and hardware worked together. The 2017 Transformer replaced recurrence in its original translation architecture with attention-based processing, opening a different route to parallel training and contextual representations. Later scaling work made the allocation of compute between model size and training data an explicit optimization problem.

What did the objective buy you?

A model trained to predict the next token learns statistical structure useful for many tasks. That objective is different from accurately completing a credentialing workflow, maintaining a claim ledger or checking current permission. Post-training can shape behavior toward instructions or preferences, but a fluent answer is still not an external transaction. The surrounding application supplies tools, state and enforcement.

Consider a fictional denial-priority model. Its target could be whether a claim eventually receives payment, how much payment arrives, or whether a reviewer should act today. Those labels answer different questions. A paid claim is not automatically evidence that an intervention caused recovery. If the label depends on future events, the features must be reconstructed as they existed when the decision would have been made. Otherwise the model receives tomorrow's answer disguised as today's evidence.

Make the historical baseline difficult to beat

Build a chronological split and keep related claims or patients from leaking across partitions where that would overstate generalization. Compare the same decision-time features, review budget and action policy. Measure calibration and the value of the selected work queue, not just a ranking score. A small model with stable inputs may be easier to maintain and faster to serve than a language model that wins an irrelevant benchmark.

For your own system, write a one-sentence account of what a new architecture changes. Does it learn a more useful representation, handle longer sequences, improve sample efficiency, or merely move cost to another stage? If the answer is only that it is newer, the proposal is incomplete. History becomes practical when it helps you separate a mechanism from a fashion and choose the experiment that would prove the mechanism matters.

Decision lab 1: Why machine learning changed

A fictional team reports AUC 0.94 for a language-model claim classifier and 0.81 for a boosted-tree baseline. Both used a random row split. The language-model input includes the complete account notes, including notes written after appeal resolution; the tree used only fields available at submission. A reviewer can inspect 100 claims each day.

Which experiment should decide whether the language model adds value?

The choice has a reference answer. Your reasoning is saved for self-assessment; it is not automatically graded. At least 60 non-space characters are required only to discourage an empty explanation.

Change one fact

Now both models use valid decision-time inputs. The tree produces a better-calibrated score, but the language model identifies a useful exception category the tree misses. Propose a hybrid evaluation and a condition under which you would keep the simpler model.

Listen to this lesson

Marin · 7:04 recorded · AI narration

02

Forward pass → loss → gradient

Trace a neural network update

A network is a parameterized calculation

A neural network composes numerical transformations. For this lab, two inputs feed one hidden ReLU unit and then a linear output. The hidden preactivation is z equals w one times x one, plus w two times x two, plus b. The hidden activation h is the larger of zero and z. The prediction is v times h plus c. The five trainable parameters are w one, w two, b, v and c. This is deliberately small enough to inspect every dependency.

Use x one equal to one, x two equal to one-half, w one equal to 0.6, w two equal to minus 0.2, b equal to 0.1, v equal to 0.8 and c equal to 0.05. The forward pass gives z of 0.6, h of 0.6 and a prediction of 0.53. With a target of one and loss equal to one-half of squared error, the loss is 0.11045. These are exercise quantities, not probabilities of a clinical outcome.

Follow the derivative through the graph

The derivative of the loss with respect to the prediction is the prediction minus the target: minus 0.47. The derivative with respect to v is that error times h, or minus 0.282. Because the ReLU is active, the derivative with respect to w one is error times v times x one, or minus 0.376. Backpropagation applies this chain rule through the computation graph; it does not search randomly for an explanation of the mistake.

Gradient descent subtracts the learning rate times each gradient. All gradients in this one step must be evaluated at the same original parameter values. If you update v first and then use the new v to calculate another gradient, you have changed the algorithm. With a rate of 0.1, the simultaneous update yields a prediction of about 0.66399 and a loss of about 0.05645. A numerical finite-difference check can catch an incorrectly implemented derivative.

Why nonlinearity and scale matter

Without nonlinearities, stacked linear layers collapse to another linear transformation, even if the factorization changes optimization. A ReLU adds a piecewise boundary. If its input is negative, its incoming-weight gradient is zero for that example. In our lab, moving b to minus one turns the hidden unit off. The output bias c can still learn, so a lower loss does not prove the hidden representation is improving. At exactly zero, a framework chooses a subgradient convention; this lab uses zero.

Feature scaling, initialization, learning rate, normalization and optimizer choice affect whether gradients produce useful progress. Very large steps can raise loss or cross activation boundaries. A minibatch averages or sums losses over examples according to the implementation; changing batch size without understanding that reduction can change the update scale. Accumulating gradients across microbatches can reproduce a larger effective batch only when scaling and stateful behavior are handled consistently.

Training progress is not generalization

The network sees the target during training because the loss needs it. At inference, that target is absent. An optimizer can reduce training loss by fitting accidental patterns or memorizing examples. Evaluate on held-out data, inspect subgroup errors and calibration where relevant, and compare the loss you optimize with the decision the system will actually support.

For a fictional claim-priority predictor, a tiny loss reduction is not enough to recommend a release. The loss function might penalize every error equally while the workflow treats an unsupported high-priority recommendation as much more costly. Separate the differentiable training objective, the held-out metrics and the operating decision. Each answers a different question, and none substitutes for the others.

One simultaneous gradient update

Fixed exercise: x₁=1, x₂=0.5, w₁=0.6, w₂=−0.2, v=0.8, c=0.05, target=1. Loss=½(prediction−target)². ReLU derivative at zero is taken as zero.

Decision lab 2: Trace a neural network update

Use the supplied network and a learning rate of 0.1. An engineer reports dL/dw₁ = −0.376 and dL/dv = −0.282, then updates v before recomputing the gradient for w₁. A second engineer computes all five gradients from the original forward pass. Both show a smaller loss on this example.

Which result matches the defined single gradient-descent step?

The choice has a reference answer. Your reasoning is saved for self-assessment; it is not automatically graded. At least 60 non-space characters are required only to discourage an empty explanation.

Change one fact

Increase the learning rate until the one-step loss rises, then move the hidden bias below the ReLU boundary. Explain which parameters still receive gradients and why one example cannot establish the best learning rate.

Listen to this lesson

Cedar · 7:15 recorded · AI narration

03

Representations are not records

What attention actually computes

From an identifier to a contextual representation

An embedding maps a token identifier into a vector of learned numbers. A token is not necessarily a word, and its vector is not a row in a verified fact database. The same token can contribute differently in different contexts because later layers transform and combine its representation with other tokens. Position information also matters: a sequence should distinguish a reversal, a date correction and a quoted example even when they contain many of the same words.

Imagine a fictional account note: the clinician is approved for one location, but the second location is still pending. A useful representation must preserve the contrast, the entities and the relationship between approval and location. It is not enough to retrieve the word approved. The downstream application still needs authoritative records because a learned representation can encode an incorrect interpretation just as easily as a correct one.

Queries, keys and values

In scaled dot-product attention, the model projects representations into queries, keys and values. A query is compared with keys through dot products, scaled by the square root of the key dimension. A mask excludes positions that are not allowed, and a softmax turns the remaining scores into weights. The output is a weighted combination of value vectors. Different heads can learn different projections; the familiar formula is softmax of QK transpose divided by square root of d, plus a mask, multiplied by V.

The word attention can mislead. The weights are numerical routing coefficients inside a learned computation. They are not a statement that a source is trustworthy, that an entity is authorized, or that a sentence is a faithful explanation. A high weight on the wrong date can help produce a confident wrong answer. A permission check belongs in application code even when the relevant permission document is in context.

Causality and the two inference phases

A causal language model prevents a position from using future positions when predicting the sequence. During prompt processing, many prompt positions can be computed in parallel while respecting that causal structure. During ordinary autoregressive generation, the next token depends on the sequence generated so far. These different shapes of work help explain why prompt processing and token-by-token decoding have different performance characteristics.

A key-value cache stores earlier key and value representations so decoding does not recompute them from scratch for every new token. It spends memory to save work. Grouped-query attention shares key-value heads among multiple query heads, reducing cache requirements relative to using one key-value head per query head. The cache contains model activations for a session; it is not a durable patient record or an approval ledger.

Context design is an information-selection problem

Increasing the context window changes how much information can be supplied. It does not establish that the right evidence will be used correctly. A compact packet with record identifiers, source times and an explicit conflict can be easier to evaluate than an unstructured transcript containing repeated stale assertions. Compression has its own risk: a summary can omit a limitation that changes the decision.

For a healthcare worker, preserve the exact fields that determine the task: practice, clinician, payer, location, effective date and evidence status when applicable. Do not treat embedding similarity as an exact join. Retrieval can nominate candidate records; the application must verify that the returned record belongs to the right scope and matches the requested identifiers. Evaluate both retrieval recall and whether the model's final answer remains supported by the selected evidence.

ComponentStores or computesDoes not establish
Embedding indexSimilarity over representationsExact identity or permission
AttentionContext-dependent weighted representationsSource truth or authorization
KV cachePrior keys and values for inferenceDurable business state
Task ledgerRecorded operation state and receiptsThat every recorded assertion is verified

Decision lab 3: What attention actually computes

A fictional retrieval test returns the correct enrollment document in 98 of 100 cases. In 12 of those 98, the answer uses a similarly named clinician or an outdated location. An attention visualization highlights the word approved. The current system passes all retrieved snippets directly to the model without checking record identifiers.

Which change most directly targets the observed failure while preserving a useful test?

The choice has a reference answer. Your reasoning is saved for self-assessment; it is not automatically graded. At least 60 non-space characters are required only to discourage an empty explanation.

Change one fact

Now the correct record is missing from retrieval in 30 percent of cases, while entity checks are perfect on returned records. Explain why the highest-priority intervention changes, and what a valid unknown response should contain.

Listen to this lesson

Marin · 7:09 recorded · AI narration

04

Compute, memory and utilization

Budget training, not peak FLOPs

Start with an explicitly simplified model

A useful first estimate for dense Transformer pretraining is approximately six times the number of parameters times the number of training tokens, measured in floating-point operations. The factor summarizes forward and backward work under simplifying assumptions. It is not an exact formula for every architecture, sequence length or implementation. Attention work, embedding details, sparsity, recomputation and communication can make the approximation less representative.

Use decimal billions for parameters and tokens, and keep units visible. A seven-billion-parameter model trained on two hundred billion tokens gives roughly 8.4 times ten to the twenty-first operations. Eight accelerators sustaining one hundred and fifty trillion operations per second each provide 1.2 times ten to the fifteenth operations per second in aggregate. Dividing gives about seven million seconds, or eighty-one days. Those are synthetic assumptions, not a claim about a particular accelerator or a recommended training run.

Peak hardware capability is not sustained useful work

A vendor's peak throughput depends on precision and operation type. A real training job loses time to communication, input pipelines, uneven work, checkpoints, failed runs and evaluation. Model FLOPs utilization is one way to relate useful model computation to peak capability, but definitions and measurement methods matter. If you enter sustained throughput directly, do not multiply by utilization again; this lab instead asks for peak throughput and a separate utilization assumption.

More devices help only if the workload can use them. Data parallelism replicates a model and combines gradients across data shards. Tensor parallelism partitions operations within layers. Pipeline parallelism partitions layers and introduces scheduling considerations. Optimizer-state sharding distributes state that would otherwise be replicated. These strategies trade memory, communication, batch constraints and implementation complexity; their effects are not captured by multiplying a device count alone.

Training memory has several owners

The weights are only one memory consumer. Trainable parameters need gradients, and optimizers can keep multiple state tensors. A common mixed-precision Adam teaching budget is sixteen bytes per trainable parameter: low-precision weights and gradients, a higher-precision master copy and two higher-precision moment estimates. Implementations differ, and this estimate is not a universal requirement. Activations, temporary buffers, communication workspaces and fragmentation come on top.

At seven billion parameters, sixteen bytes per parameter is about 104.3 gibibytes before activations. Sharding changes per-device residency rather than erasing the underlying state. Gradient checkpointing reduces saved activations by recomputing some forward work during backward propagation. Gradient accumulation can reduce the microbatch footprint while increasing the number of passes before an optimizer step. Neither technique makes a compute budget disappear.

Allocate the budget to a decision

Scaling studies ask how to distribute a fixed compute budget across model size and training data under their assumptions. A larger model with too little training can lose to a smaller, better-trained one. Data quality, repetition, task coverage and contamination also matter. Counting tokens without inspecting their provenance and information content can produce an expensive but weak training plan.

Before proposing pretraining for a healthcare application, compare it with adapting an existing model, improving retrieval, using a smaller specialized predictor or changing a workflow rule. A new base model needs a reason that survives those alternatives. Record the expected capability gain, data rights, evaluation set, compute estimate, memory plan, failure allowance and operating cost after training. The training job ends once; serving and maintaining its result may continue for years.

Dense training budget

C≈6ND is a dense-model approximation. TFLOP/s is decimal; memory output uses binary GiB. The 16-byte state is one illustrative mixed-precision Adam configuration.

Decision lab 4: Budget training, not peak FLOPs

A synthetic plan uses 7 billion dense parameters, 200 billion tokens, 8 GPUs, 500 peak TFLOP/s per GPU and 30% sustained model utilization. An estimate promises completion in 24 days using only peak throughput. It budgets 14 GB for weights and treats that as the total training memory.

Which revision is closest to the stated assumptions?

The choice has a reference answer. Your reasoning is saved for self-assessment; it is not automatically graded. At least 60 non-space characters are required only to discourage an empty explanation.

Change one fact

Double the number of GPUs but assume utilization falls from 30% to 20% because communication dominates. Calculate the speedup. Then explain why halving the microbatch may help memory while making the training run slower.

Listen to this lesson

Cedar · 7:31 recorded · AI narration

05

Behavior, rewards and hidden cost

What post-training changes

Separate pretraining from adaptation

Pretraining usually learns broad statistical structure from a large corpus. Post-training is a family of procedures that further changes parameters after that stage. It can teach instruction following, output conventions, tool-use patterns or preferences. It is still training: there is an objective, data or sampled experience, optimization and a new model artifact. Writing a system prompt, loading a skill or appending memory does not by itself update model parameters.

Supervised fine-tuning uses examples of desired outputs. In a causal language model, an implementation may train only on response tokens while retaining the prompt as conditioning context; masks and data formatting determine the actual objective. A dataset full of confident but unsupported answers can teach exactly that behavior. More examples cannot repair a definition of success that rewards the wrong thing.

Preference optimization and reinforcement learning

Preference data compare candidate responses. Direct Preference Optimization uses a loss based on chosen and rejected responses relative to a reference policy, avoiding an explicit reward-model-plus-online-RL loop in its original formulation. This changes the optimization recipe; it does not make preferences objective truth. If reviewers consistently prefer reassurance to uncertainty, the resulting model can learn to sound confident when it should ask for evidence.

Reinforcement-learning approaches can generate trajectories, score outcomes or intermediate behavior, and update a policy. Depending on the method, compute may include rollout generation, policy training, reference-policy scoring, reward models or verifiers, and repeated evaluation. Long reasoning traces and many candidates can make sampling a substantial part of the budget. Calling the process post-training tells you when it occurs, not whether it is cheap.

The reward is a specification with failure modes

For a fictional scheduling worker, rewarding successful tool-call syntax is weaker than rewarding a valid requested appointment change. A model could call a syntactically valid tool with the wrong location. Rewarding a final confirmation string is weaker still: it can encourage the model to announce success without a committed write. A verifier should inspect the actual authorized state transition and its receipt under controlled test conditions.

Outcome labels can also hide selection bias. If a dataset includes only cases that reached a cooperative endpoint, the model sees little evidence about abstention, cancellation, ambiguous identity or unknown dispatch. Build explicit negative and recovery cases. Keep training data separate from a held-out evaluation, including template families or related workflow traces that might otherwise leak. A reference policy or a penalty on drift can constrain an update, but it does not prove preservation of every important capability.

Adaptation needs a release comparison

Distillation trains a student from a teacher's outputs or behavior. It can reduce serving cost, but teacher mistakes and missing cases can transfer too. Parameter-efficient adaptation changes a subset or additional low-dimensional parameters; it is a way to train, not a replacement for a valid objective. Full fine-tuning and adapters can both overfit or degrade behavior outside the training distribution.

Evaluate the exact candidate against a frozen baseline using the same tools, retrieval and test cases. Separate gains in style, task success, unsupported assertions, permission handling, recovery and cost. Review results by failure severity, not only the average. If improved warmth comes with more unsupported completion claims, a higher preference score is not sufficient. Keep the model, prompt, tool schema, skill version and evaluation set identifiable so you can explain what changed and roll back the actual source of a regression.

Decision lab 5: What post-training changes

A synthetic post-training run improves reviewer preference from 68% to 79%. On 400 held-out appointment-change traces, unsupported success announcements rise from 2 to 11. Tool-schema validity stays at 99%. The preference rubric rewards concise reassurance but does not require a commit receipt. No prompt or tool implementation changed.

Which release decision is supported by this packet?

The choice has a reference answer. Your reasoning is saved for self-assessment; it is not automatically graded. At least 60 non-space characters are required only to discourage an empty explanation.

Change one fact

Now unsupported claims fall to zero in the test, but the candidate escalates nearly every task and completion falls sharply. Define a release comparison that includes selective coverage, reviewer capacity and severity instead of optimizing a single safety metric.

Listen to this lesson

Marin · 7:28 recorded · AI narration

06

LoRA, quantization and versioning

Adapters without the mythology

What is being adapted?

An adapter is a parameter-efficient way to alter model behavior without necessarily updating every original parameter. The term includes several designs. Bottleneck adapters add small trainable modules within a network. LoRA represents a weight update with low-rank matrices. These mechanisms should not be confused with a connector that lets an application call an external service, even though software teams sometimes use the same word for both.

For a weight matrix W with d output rows and k input columns, LoRA learns matrices B and A whose product has the same shape as W. If B is d by r and A is r by k, the trainable update has r times d plus r times k parameters rather than d times k. A scaling factor is normally applied. The rank r limits the rank of the update, not the total rank or knowledge of the resulting model. Target modules and implementation choices matter as much as the rank number.

Calculate the savings in the right denominator

For one 4096 by 4096 matrix and rank sixteen, full tuning adjusts 16,777,216 parameters. The two LoRA matrices contain 131,072 parameters, or 0.78125% of that target matrix. For sixty-four such matrices, the adapters contain 8,388,608 trainable parameters. At two bytes per adapter weight, that is sixteen mebibytes of adapter weights. This is a calculation about the chosen matrices, not a statement that the entire training job uses sixteen mebibytes.

The frozen base model must still participate in the forward computation, and gradients must propagate through relevant operations to train the adapters. Activations and temporary workspaces still consume memory. Optimizer state for the trainable adapter parameters is smaller than for full tuning, but the training batch, sequence length and implementation can dominate the remaining footprint. A memory estimate that reports only the adapter file size is incomplete.

QLoRA combines different techniques

QLoRA showed a way to train low-rank adapters through a frozen, quantized base model using particular quantization and memory-management techniques. Quantization reduces the precision used to represent values; adapter training changes learned parameters. They are independent concepts that can be combined. A four-bit base is not the same as four-bit arithmetic everywhere, four-bit activations or a four-bit key-value cache.

Quantization metadata, dequantization, kernels, outliers and quality changes affect actual memory and speed. The nominal number of bits is a payload estimate, not a benchmark. Measure the exact quantized artifact and inference stack on the cases that matter. A model that fits memory can still have unacceptable tail latency, and a small adapter can still introduce a high-severity behavior regression.

Treat the adapter as a versioned model artifact

An adapter depends on the base architecture, the intended base checkpoint, target-module names, tokenizer assumptions and training configuration. A compatible tensor shape is not sufficient evidence of behavioral compatibility. Merging a LoRA update into base weights can avoid separate adapter computation at inference, but changes deployment and rollback choices. Hot-swapping adapters needs an explicit selection policy and tests for the serving implementation.

In a multi-practice system, an adapter is not a tenant-isolation boundary. A caller should not choose another practice's adapter merely by naming its identifier. Authorize selection on the server, bind it to the expected base and workflow version, and avoid training sensitive records into a model when the task only requires current retrieval. Removing an adapter does not retroactively erase data from logs, outputs, caches or other artifacts. Governance follows the whole training and serving path.

Count the trainable parameters

Square-matrix exercise: W∈R^(d×d), ΔW∝BA, A∈R^(r×d), B∈R^(d×r). Scaling does not change the parameter count. Memory excludes frozen base weights, activations and workspace.

Decision lab 6: Adapters without the mythology

A synthetic job targets 64 square matrices of dimension 4096 with LoRA rank 16. The engineer estimates 16 MiB of two-byte adapter weights and 128 MiB of illustrative sixteen-byte training state for those adapter parameters. The frozen base, activations and buffers are budgeted separately. Deployment proposes swapping the adapter onto a newer base with matching tensor shapes but no evaluation.

Which assessment is defensible?

The choice has a reference answer. Your reasoning is saved for self-assessment; it is not automatically graded. At least 60 non-space characters are required only to discourage an empty explanation.

Change one fact

Double rank while halving the number of target matrices. The trainable parameter count stays constant. Explain why the two adapters need not learn the same function or achieve the same quality.

Listen to this lesson

Cedar · 7:37 recorded · AI narration

07

Capacity is more than model weights

Why inference runs out of headroom

Prefill and decode stress different resources

A language-model request usually starts by processing the supplied prompt, often called prefill, then generates output tokens. Prefill can perform substantial parallel matrix computation across prompt positions. Autoregressive decoding produces successive tokens and repeatedly accesses model weights and cached state. Whether a particular request is compute-bound, bandwidth-bound or limited elsewhere depends on model shape, batch size, sequence length, kernels and hardware.

Time to first token, time between tokens, total completion time and aggregate tokens per second describe different experiences. A large batch can improve throughput while making an individual request wait longer. Continuous batching lets requests enter and leave a serving batch as they progress, but does not remove resource contention. For a voice agent, an attractive throughput figure is weak evidence if the long tail leaves callers waiting in silence.

Account for the key-value cache

A simplified key-value cache contains two tensors, keys and values, across layers, key-value heads, head dimensions, sequence positions and concurrent sequences. The byte count is two times layers times KV heads times head dimension times sequence length times batch times bytes per cached value. Use KV heads, not query heads, in a grouped-query architecture. The formula assumes a uniform full-length cache and omits implementation-specific allocation and paging overhead.

For thirty-two layers, eight KV heads, head dimension 128, sequence length 8192 and two-byte cache values, one sequence needs one gibibyte of KV payload. Sixteen such sequences need sixteen GiB. If the model instead had thirty-two KV heads, the payload would be four times larger. A wider context or higher concurrency can consume the remaining memory even when the quantized weights fit comfortably.

Nominal precision is not total memory

An eight-billion-parameter model at four bits per weight has a raw payload of four billion bytes, or about 3.73 GiB. Quantization scales and other metadata, runtime buffers, activations, graph capture, cache allocation and fragmentation add to that number. The lab includes an explicit reserve so you can see the difference between known payloads and an assumed allowance. That reserve is not a measured constant or an assurance that every runtime is covered.

Mixture-of-experts models require another distinction: parameters activated per token and parameters that must remain resident are not the same number. Routing can reduce computation relative to activating every expert while memory and communication remain substantial. Loading experts on demand introduces a different performance tradeoff. Do not size a model's memory from its active-parameter count without understanding the serving design.

Measure the workload you will actually serve

Build a load test with realistic prompt lengths, output lengths, concurrency, arrival bursts and tool delays. Separate cold start from warmed service. Record queue time, prefill, decoding, cancellations and failed requests. Report distributions, not just averages, and keep the quality evaluation tied to the exact quantized model, adapter, prompt and runtime version used in the performance test.

A healthcare workflow might allow an asynchronous RCM analysis to take several seconds but require a voice acknowledgment much sooner. Serving both through one unbounded queue can make the voice path unpredictable. Admission control, routing, reserved capacity and bounded output length may be more effective than buying a larger context window. When memory fits, the next question is whether the system meets its latency and quality requirements under the intended load; fitting is only the beginning of the capacity argument.

Weights plus KV cache

Raw weights=N×bits/8. KV=2×layers×KV heads×head dimension×tokens×sequences×bytes. The reserve is user-supplied, not measured. This single-device exercise does not model tensor parallelism, cache paging or throughput.

Decision lab 7: Why inference runs out of headroom

Use the lab defaults: 8B parameters at 4 bits, 32 layers, 8 KV heads, head dimension 128, context 8192, batch 16, two-byte KV values, 4 GiB explicit overhead and a 24 GiB device budget. A colleague proposes doubling context with no change to concurrency, arguing that the weights are still only 3.73 GiB.

Which capacity statement follows from the simplified calculation?

The choice has a reference answer. Your reasoning is saved for self-assessment; it is not automatically graded. At least 60 non-space characters are required only to discourage an empty explanation.

Change one fact

Keep the longer context but halve concurrency. The simplified total returns to its earlier value. Explain what this does and does not tell you about requests per second, queue delay and a voice service-level objective.

Listen to this lesson

Marin · 7:48 recorded · AI narration

08

Separate knowledge, behavior and authority

Choose the smallest effective intervention

Diagnose the failure before choosing the technique

An assistant can fail because information is missing, retrieval finds the wrong record, the model ignores a valid rule, a tool rejects the request, a transaction is uncertain, or the operating policy is undefined. Those failures call for different interventions. A larger model or a new adapter may help some of them and leave others untouched. Start from a reproducible trace with the expected outcome, observed outcome and the first point where evidence or control diverges.

A prompt supplies instructions for the current inference. Retrieval supplies selected external material. A tool exposes a capability through an application interface. A skill packages procedural guidance and sometimes supporting resources or scripts. Memory preserves selected information across a chosen scope and lifetime. An adapter or full fine-tune changes learned parameters. These components can work together, but naming all of them does not establish a coherent architecture.

Keep current facts outside irreversible learning loops

Suppose a payer's enrollment status changes today. That fact belongs in an authoritative source and a current lookup path, not in a training run that may finish next week. A model can learn how to interpret a status response, but it should not be trusted as the current record of participation. Likewise, a saved preference can help a conversation without authorizing a new action. Scope, provenance and freshness travel with the data rather than being inferred from friendly wording.

An adapter becomes more plausible when a stable, repeated behavior remains deficient after prompt, retrieval and tool design are sound, and you have legitimate training data plus a held-out test that can detect improvement and regression. For a narrow numerical decision, a rules engine or a specialized predictor may be the better baseline. The choice should follow the error distribution and operating constraints, not a desire to make every component agentic.

Run an ablation that can change your mind

An ablation removes or changes one component while holding the rest of the system fixed. Compare a baseline, improved evidence selection, improved instructions and a model adaptation separately before combining them. Use the same held-out case distribution and report confidence limits appropriate to the sample. Do not conclude that an adapter caused a gain if the adapter candidate also received a cleaner retrieval pipeline and a new prompt.

Include quality, coverage, reviewer effort, latency and cost per completed valid task. Cheap tokens can still produce expensive work if they trigger retries or manual correction. A model that abstains on every difficult case may avoid errors while exhausting the review queue. Count failures at the business boundary: an acknowledged request, a committed external action and a verified final outcome are different milestones.

Build an operating argument, not a shopping list

A useful architecture memo identifies the data owner, decision authority, source of truth, versioned artifacts, runtime constraints and failure recovery. It states what is simulated, what is tested and what remains unknown. In healthcare operations, credentialing approval, enrollment linkage, payer agreements and effective dates remain distinct facts where the workflow requires them. A model's explanation should preserve those distinctions rather than compress them into a single ready flag.

The capstone asks you to use the mechanisms from this course together. Reconstruct a gradient, calculate a compute budget, count adapter parameters and size an inference cache. Then decide which of those techniques is actually justified by the failure packet. Engineering depth is not using the most advanced technique available. It is being able to show why a particular change should work, what it costs, what it cannot fix and what evidence would make you reject it.

InterventionPrimary effectStill required
Prompt / skillChanges instructions available at inferenceVersioning, evaluation and tool enforcement
Retrieval / memorySupplies selected external or retained informationScope, freshness, provenance and deletion rules
Tool / workflowReads or changes application stateAuthorization, idempotency and receipts
Adapter / fine-tuneChanges learned model parametersValid training data, held-out evaluation and rollback

Decision lab 8: Choose the smallest effective intervention

In 200 synthetic credentialing tasks, 36 failures come from stale enrollment records, 12 from unresolved tool timeouts and 8 from incorrectly formatted summaries. The current model formats the summary correctly in 48 of 50 tests when given a validated record packet and a schema. A proposed adapter is trained on last quarter’s successful summaries and payer statuses.

Which first intervention best matches the dominant failures?

The choice has a reference answer. Your reasoning is saved for self-assessment; it is not automatically graded. At least 60 non-space characters are required only to discourage an empty explanation.

Change one fact

After those fixes, a stable specialty-specific interpretation still fails in 18% of cases despite good evidence and clear instructions. You have reviewed, legally usable examples. Specify the controlled adapter experiment, its baseline and the regression that would block adoption.

Listen to this lesson

Cedar · 7:22 recorded · AI narration

Defend an ML system decision

Use the final credentialing failure packet and your calculator results. Your memo must separate the data problem, learning problem and workflow problem. The workbook preserves your first and latest decisions so revision is visible.

Complete every decision lab and write at least 80 non-space characters per memo field before saving a complete workbook. This checks completeness, not correctness or operational readiness.