Macalinao StudioLearnAll enriched lessons ↗
College path · 7 sectionsSwitch to high school ↗

College / LONGER LESSON instruction

Instruction tuning: learn from demonstrations

Build a demonstration, follow masked token loss, distinguish training from prompting, and design a fair evaluation.

Preparation: fractions, probability and the idea of a predicted next token.

Plan 25–40 minutes with the activities; this is a study estimate, not a timed requirement. Both paths have complete narration. Your notes and progress are kept separately for each level.

Section 01 / 07

From continuation to an instructed task

College path. Build a demonstration, follow masked token loss, distinguish training from prompting, and design a fair evaluation. Preparation: fractions, probability and the idea of a predicted next token. Move between Signal Room, Workbench and Field Notes without losing your section. Pause before each worked solution.

A pretrained language model predicts continuations. An instruction-tuning dataset instead repeatedly shows a task request together with a desirable response. The learning rule can still be next-token prediction; what changes is the experience supplied to it. Imagine teaching a writing partner to turn a paragraph into two accurate bullet points. Good demonstrations show both the requested format and which facts deserve space. Merely adding the words “be helpful” at inference time changes the prompt, not the stored weights. Instruction tuning changes trainable parameters through many examples. It does not make every later answer correct.

Formally, supervised fine-tuning optimizes conditional response likelihood over a demonstration distribution. Instruction tuning is a use of supervised fine-tuning, not a separate Transformer architecture. Multitask instruction data can target generalization to new tasks, as in FLAN; a narrow domain dataset targets a different distribution. These goals require different held-out evaluations. Full-weight training and low-rank adaptation are alternative parameterizations of the update, not alternative definitions of the supervision.

Worked example. Write the prompt “Summarize this weather report in two bullets.” Pair it with two supported facts. During training the target response is supplied; during deployment the model must produce its own response. Rewriting the prompt alone supplies no weight update.

L = − average log pθ(response | instruction, context)

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Which changes weights: editing a user prompt, or running supervised optimization on demonstrations?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Supervised optimization changes the selected trainable weights. Editing the prompt changes the conditioning context for that request. Both can change behavior, but they are different interventions.

Section 02 / 07

Build the example before measuring its loss

A useful training record contains a clear instruction, any needed source material, and a checked answer. Conversation roles and separators tell the model which text came from the user and which text is the desired assistant response. A loss mask tells the trainer which token predictions to score. Masking a user token out of the loss does not remove that token from context. In our experiment the first two positions are prompt targets and the next two are response targets. The labels are deliberately tiny so you can inspect every contribution instead of trusting a single reported number.

The fixture uses four independent binary target-versus-other predictions. This makes every probability valid but does not model shared Transformer parameters or a real tokenizer. Actual causal-language-model labels are shifted relative to inputs; padding and excluded targets must not enter the denominator. Assistant-only or completion-only masking is a configuration and data-format choice, not a universal property of all SFT. Inspect the actual rendered chat template and labels.

Worked example. Our prompt target probabilities are 0.8 and 0.5. At response logit zero, both response target probabilities are 0.5. With prompt weight zero, only the two response predictions contribute to the mean. The prompt still provides context in the conceptual training example.

L = −Σ m_t log p_t / Σ m_t; context ≠ scored targets

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. If a prompt is masked out of the loss, should the model stop attending to it?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. The mask controls which targets are scored, not which context tokens can be attended to. Attention masking and loss masking solve different problems.

Section 03 / 07

Calculate surprise one token at a time

A correct target assigned low probability creates more loss than a correct target assigned high probability. Negative natural logarithm turns a product of probabilities into an additive score. At probability one half, the loss is about 0.693 natural-log units, called nats. At probability one quarter it is about 1.386 nats. Our Workbench exposes the numerator and denominator so that averaging cannot hide the accounting. A lower training loss means the supplied targets became easier to predict under that calculation. It does not independently verify that the targets were truthful or the model can solve new problems.

For a binary target probability sigmoid of logit u, the derivative of negative log probability with respect to u is p minus one. The fixture ties both response positions to the same u, while prompt predictions remain fixed. Its response-only loss therefore has the same derivative p minus one. When prompt terms enter the normalized mean, the derivative is multiplied by two divided by the total scored weight. Units and normalization matter when comparing gradients.

Worked example. At response logit zero, each response target has probability 0.5. Adding their two losses gives about 1.386; dividing by two gives 0.693. With learning rate one, the response-only gradient is minus 0.5, so the next logit is 0.5 and the target probability rises to about 0.622.

p = sigmoid(u); ∂L/∂u = p − 1 for response-only fixture

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Two scored tokens have probabilities one half and one quarter. What is their mean negative log loss?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Add approximately 0.693 and 1.386, then divide by two. The mean is about 1.040 nats. Do not average the probabilities first and take a logarithm afterward; that is a different calculation.

Section 04 / 07

A small denominator can change the story

Suppose a dashboard reports that loss fell after including easy prompt tokens. That number alone does not prove response prediction improved. The average may have changed because the collection of scored items changed. In the experiment, switch the prompt weight from zero to one without moving the response logit. The response probabilities stay identical while the reported mean changes. Intermediate prompt weights are an explicit teaching device for weighted loss. Real pipelines commonly use binary inclusion masks, and some use deliberate weights. Whatever the choice, record it beside the result.

At u equal to zero, the response loss sum is twice log two; the prompt sum is minus log 0.8 minus log 0.5. The denominator is two plus twice the prompt weight. Including fixed prompt terms reduces the tied response gradient magnitude in this fixture. A real model shares parameters across positions, so prompt loss may also update shared representations. The toy isolates normalization; it is not a prediction of real multitask gradient interference.

Worked example. With response probabilities fixed at 0.5, response-only loss is about 0.693. Including both prompt terms gives about 0.576. The lower number came from different scored tokens. Neither response prediction improved before an optimization step was taken.

D = 2 + 2w; ∂L/∂u = 2(p−1)/D

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Can you compare two training curves fairly if one scores prompts and responses and the other scores responses only?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Not from the scalar curves alone. Align the scoring rule, tokenization, data and denominator, or separately report a common held-out response loss. Preserve the raw accounting needed to interpret the comparison.

Section 05 / 07

Teacher forcing and the first wrong turn

During ordinary supervised training, a response token is predicted after the earlier target tokens from the dataset. This is teacher forcing. When the model generates freely, its earlier generated tokens become the context instead. A wrong early choice can send the rest of the answer down a different path. Reading a solution with each preceding step supplied is easier than writing the entire solution unaided. Test both token prediction and actual responses. An answer that begins in the expected style may still omit the main fact, ignore a constraint or confidently invent a detail.

The autoregressive factorization conditions each target on the prompt and previous target tokens. It permits parallel computation of training positions under causal masking. Free-running evaluation instead samples or decodes prefixes from the policy. The fixture has no generated prefix dependence, so it cannot simulate compounding errors; use it only for the scored-token arithmetic. Real evaluation should specify decoding settings and handle end-of-turn tokens and truncation consistently.

Worked example. The target answer is “Water freezes at zero degrees Celsius under ordinary pressure.” Teacher forcing scores later words after the supplied correct prefix. If free generation starts with “Water boils,” continuing fluently does not repair that factual change. Check the completed answer, not only a token-loss average.

p(y|x) = Π_t p(y_t | x, y_<t)

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Why can low teacher-forced loss coexist with an incorrect generated answer?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

The evaluation contexts differ. Training supplies target prefixes, while generation follows the model’s own choices. Dataset gaps and uncertain facts also remain. Low loss is useful evidence about prediction on those targets, not a certificate of correct free generation.

Section 06 / 07

Choose data that teaches the behavior you want

Demonstrations are a curriculum. If nearly every answer is long, the model may learn verbosity even when the instruction asks for one sentence. If examples contain confident mistakes, optimization rewards those mistakes. Include varied tasks, lengths, languages and realistic requests in proportions that match your goals. Check permissions and remove unnecessary personal information. Split related examples together so that a rewritten version of a training answer does not quietly become a test question. More records are useful only when they add appropriate learning signal rather than repeated errors.

Distinguish example-weighted and token-weighted objectives: long responses contribute more terms to a token average. Truncation may remove the desired response or its concluding constraint. Packing requires correct attention boundaries and label handling. Data overlap can occur through paraphrases, shared documents and synthetic generations, so a random row split may overstate generalization. Record source groups, deduplication rules and the sampling mixture before interpreting improvements.

Worked example. A collection contains 900 long summaries and 100 short extraction answers. The row ratio is nine to one; if summaries are ten times longer, their share of scored tokens is even larger. Inspect both counts before concluding that extraction received enough practice.

Token contribution ∝ example frequency × scored response length

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. You find five paraphrases of one source document. Where should they go when making a train/test split?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Keep the related group in one split. Otherwise the test may reward memorized source content. Then include independent documents and task variants to measure the intended kind of generalization.

Section 07 / 07

Evaluate the task, then connect the next signal

Finish by comparing the starting model and the tuned model on prompts held out before training. Use separate checks for factual accuracy, instruction compliance, appropriate uncertainty and unnecessary refusal. Ask reviewers to judge without knowing which system wrote each answer. Track regressions as carefully as gains. A model that follows the requested format but invents its contents has not completed the task. Instruction tuning teaches demonstrations; the next lessons ask what changes when people can more easily compare two answers than write an ideal answer themselves.

Keep the evaluation prompt distribution, decoding budget and rubric fixed across candidates. Report uncertainty from finite samples and inspect subgroup failures rather than compressing all behavior into one score. LoRA changes how many parameters are trained; RLHF and DPO change the learning signal or objective. These choices can be combined, but a pipeline must document the actual combination. Our one-step arithmetic experiment establishes neither generalization nor deployment readiness.

Worked example. For a two-bullet summarizer, score whether there are exactly two bullets, whether each claim is supported and whether the central fact is preserved. A perfect format score with poor factual support is a mixed result. Save one failure example and write a revised data-collection plan.

Evaluation = held-out tasks + fixed rubric + uncertainty + regression checks

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Design one test that could expose a weakness hidden by average training loss.

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Use unseen documents with misleading details and a strict two-bullet request. Judge support, coverage and format separately. Compare against the same base model under the same decoding settings and keep examples of both improvements and regressions.

Final checkpoint. At response logit zero with prompt weight one, what is the tied response gradient? Option 1: Minus 0.25. Option 2: Minus 0.5. Option 3: Zero.

Pause and choose an answer before continuing.

Reveal worked solution

Option 1 is correct. Two response terms contribute p minus one, divided by total weight four.

LONGER REASONING LESSONS

Reason, verify and learn from attempts

Worked examples, local narration and connected experiments at your level.

Continue the learning path

Sources and scope

Original worked examples and teaching text, grounded in these primary references. Numerical fixtures explain mechanisms; model quality and hardware performance require separate measurements. Both levels share key examples, with different explanations and checkpoints.

Reset this college path?

This removes only this path’s notes, progress and experiments from this browser.