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

College / LONGER LESSON 10

Probability and gradients: make loss visible

Compute stable softmax, derive cross-entropy gradients, and test confidence.

Preparation: Fractions and exponentials; derivatives for the college path.

Plan 20–35 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

Convert scores into shares

College path. Compute stable softmax, derive cross-entropy gradients, and test confidence.

Preparation: Fractions and exponentials; derivatives for the college path. Work through one section at a time. Predict the experiment result before changing its controls, then explain what the example leaves out.

Softmax maps unconstrained logits to a categorical distribution. Adding the same constant to every logit leaves its probabilities unchanged, because a common exponential factor cancels. This invariance explains both stable computation and the zero-sum structure of the logit gradient. We use natural exponentials, one-hot targets and natural-log cross-entropy in the derivation; batch weighting or alternate targets must be handled explicitly.

Worked step 1. Exponentiate [2,1,0] to approximately [7.389,2.718,1].

Worked step 2. Their sum is 11.107.

Worked step 3. Divide to obtain [0.6652,0.2447,0.0900].

pᵢ = exp(zᵢ) / Σⱼ exp(zⱼ)

Probability i is the exponential of score i divided by the sum of all exponential scores.

Try it yourself. Why not just divide the raw scores by their sum?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. That is a different mapping and can produce invalid negative probabilities for other scores. Exponentials provide positive weights.

Section 02 / 07

Shift large scores safely

Set m to the maximum logit and evaluate exp(z_i−m). Every exponent is nonpositive and at least one weight is one. Compute log probabilities as z_i−m minus the logarithm of the shifted exponential sum, avoiding a logarithm of an already-underflowed probability. Stable arithmetic protects the intended calculation; it does not calibrate the model or improve the correctness of the target labels.

Worked step 1. Shift [2,1,0] to [0,-1,-2].

Worked step 2. The positive weights become [1,0.3679,0.1353].

Worked step 3. Normalize by 1.5032 to recover the same probabilities.

log pᵢ = zᵢ − m − log Σⱼ exp(zⱼ − m)

Log probability is the shifted score minus the log of the shifted exponential sum.

Try it yourself. What should adding one hundred to every score do?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. Nothing to the exact probabilities. Small floating-point differences are possible, but a large change indicates a bug.

Section 03 / 07

Measure target surprise

One-hot cross-entropy is minus log p_target. For the logits [2,1,0], losses for the first and third targets are about 0.4076 and 2.4076. Framework functions that accept logits typically perform a stable log-softmax internally; passing probabilities as though they were logits changes the objective. Distinguish a single-example loss from batch means, class weights and ignored positions when checking gradients.

Worked step 1. First target: −log(0.6652) ≈ 0.4076.

Worked step 2. Third target: −log(0.0900) ≈ 2.4076.

Worked step 3. A lower target probability causes a larger loss.

L = −log p_target

The loss is minus the natural logarithm of the target probability.

Try it yourself. What is the loss when the correct target has probability one half?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. Approximately 0.6931 nats. A base-two logarithm would use bits instead; this lesson uses natural logarithms.

Section 04 / 07

Follow the chain rule

The softmax Jacobian has entries p_i(δ_ij−p_j). Composing it with the target-probability derivative −1/p_target gives dL/dz=p−y. This is a logit derivative, not a probability derivative. The components sum to zero, matching common-offset invariance. If softmax receives z/T, the derivative with respect to the unscaled z includes an additional factor 1/T. Keep that convention visible in an implementation.

Worked step 1. Subtract [1,0,0] from the probability vector.

Worked step 2. Obtain about [−0.3348,0.2447,0.0900].

Worked step 3. The three components sum to zero up to rounding.

∂L/∂zᵢ = (pᵢ − yᵢ)/T

For logits divided by temperature, subtract the target indicator from the probability and divide by temperature.

Try it yourself. Why is −1/p_target not the complete logit gradient?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. It differentiates the loss with respect to target probability. The normalization and its chain rule still connect that probability to every logit.

Section 05 / 07

Temperature is not truth

Positive temperature preserves logit ranking while changing entropy. As temperature grows, the distribution approaches uniformity; as it approaches zero, mass concentrates on maxima. Calibration requires held-out outcome measurements, not merely lower entropy. Keep inference sampling temperature distinct from a training objective that differentiates through temperature-scaled logits. Our experiment exposes both temperature and a common offset to separate a genuine distribution change from an invariant transformation.

Worked step 1. At temperature one, the leading probability is about 0.6652.

Worked step 2. At temperature two it is about 0.5065.

Worked step 3. The top-ranked class stays the same.

Try it yourself. Does sharpening the distribution establish that its top answer is correct?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. No. Confidence and correctness are different. Labels or evidence are required to assess correctness.

Section 06 / 07

Check the derivative two ways

A central difference computes [L(z+h e_i)−L(z−h e_i)]/(2h). Compare it with the analytic gradient, accounting for temperature and loss reduction. Test multiple step sizes rather than assuming the smallest is best. A finite-difference match is strong local diagnostic evidence, not a proof for every input. Separately test large common offsets, because normalized probabilities alone do not certify numerical stability or correct derivatives.

Worked step 1. Hold target and other scores fixed.

Worked step 2. Evaluate the loss at first score plus and minus 0.001.

Worked step 3. Divide the difference by 0.002 and compare with the analytic gradient.

gᵢ ≈ [L(z+h eᵢ) − L(z−h eᵢ)] / (2h)

Subtract the two perturbed losses and divide by twice the perturbation.

Try it yourself. What could cause a failed gradient check when probabilities still sum to one?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. Wrong target indexing, a missing temperature factor, batch averaging, or confusion between derivatives of logits and probabilities.

Section 07 / 07

Mastery and transfer

Bring the pieces together. First answer the checkpoint without the worked solutions. Then explain the mechanism in your own words, using one numerical example from this lesson.

At temperature one, the logit gradient is… Option 1: p−y. Option 2: −1/p for all coordinates. Option 3: y−p.

Pause here and choose an answer before continuing. The checkpoint explanation follows.

Reveal worked solution

The correct choice is option 1: p−y. The softmax chain rule yields p minus y.

Transfer task. Change one assumption in the worked example. State your prediction, calculate or test it in Workbench, then explain whether the result supports your prediction.

Reveal worked solution

Self-check rubric. Name the changed assumption, keep the other inputs fixed, show at least one intermediate calculation, and distinguish what the toy example guarantees from what would require a trained model or a real measurement.

MODERN MODEL CASE STUDY

DeepSeek V4.1 Flash: where this idea goes next

See how CSA2 separates cache reuse from index reuse. Follow the worked examples, then evaluate the reported gains and their limits.

Open the college case study →

Added October 21, 2026. This optional extension has its own complete local narration.

LONGER INFERENCE LESSONS

Follow the mechanism in depth

Worked examples, local narration and connected learning modes at your level.

LONGER ATTENTION LESSONS

Follow the mechanism in depth

Worked examples, local narration and connected learning modes at your level.

LONGER POST-TRAINING LESSONS

Follow demonstrations, rewards and preferences

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

LONGER REASONING LESSONS

Reason, verify and learn from attempts

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

LONGER SEARCH AND VERIFICATION LESSONS

Compare answers, explore paths and check steps

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

LONGER RETRIEVAL, TOOL AND AGENT LESSONS

Find evidence, use tools and coordinate work

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

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.

EXTENDED FIELD NOTES

What a model learns: from numbers to a useful answer

Follow a sentence through learned weights, temporary activations, and the next-token decision.

Additional reading · original lesson audio remains unchanged.

Read the full explanation · 586 words + college extension
What changes when you ask a question?

The weights stay fixed during ordinary inference. Activations change with your input.

  1. Text → tokens
  2. Tokens → vectors
  3. Learned transformations
  4. Next-token scores

Text → tokens

A model is a computation with learned settings

A language model does not contain a little librarian choosing a finished answer from a shelf. It contains a structured computation whose numerical settings were learned during training. Those settings are called parameters. Many are weights arranged in matrices; other parameters can include offsets or normalization scales. The architecture determines which operations happen and how information travels. The weights determine the particular transformations performed by those operations. Two models can share an architecture and behave differently because they learned different parameter values.

Consider a tiny operation: y = 0.6x₁ − 0.2x₂ + 0.1. With inputs x₁ = 2 and x₂ = 3, the output is 0.7. Changing the first weight from 0.6 to 0.5 changes the output to 0.5. This is a teaching example, not a miniature intelligent system. Its purpose is to make one idea visible: numerical settings influence the result. In a language model, many such transformations act together across large vectors, nonlinear functions, and layers.

Follow the sentence

First, a tokenizer turns text into a sequence of token identifiers. A token may represent a word, part of a word, punctuation, or another unit. An embedding table supplies a learned vector for each identifier. These vectors are starting representations, not complete dictionary definitions. As they pass through the network, surrounding tokens influence how the current sequence is represented.

In attention, learned projections produce queries, keys, and values. The model compares queries with keys to calculate input-dependent attention scores, then combines value representations. This distinction matters: the projection weights normally remain fixed during a conversation, while the attention scores change with the input. Feed-forward transformations further process the representations, and residual connections carry information around sublayers. Finally, an output transformation supplies scores for possible next tokens. A selection procedure chooses a continuation, which becomes part of the next input step.

Training changes the settings; a conversation changes the state

During training, a loss measures how the predictions compare with the training objective. Gradients estimate how parameter changes would affect that loss. An optimizer uses those gradients to update trainable parameters. A single example does not usually teach an isolated fact to one identifiable weight. Useful patterns emerge through many updates, and knowledge and behavior are distributed across the computation.

During ordinary inference, the parameters stay fixed. Your prompt changes the activations: the temporary numbers produced while the model runs. A cache can retain intermediate information so the system need not repeat earlier work. That cache is not a new permanent education for the model. A product may separately save conversation history or conduct later training, but those are additional mechanisms. Saying that a chatbot remembers your previous sentence does not establish that its weights changed.

Why more parameters is not a complete explanation

A parameter count describes scale, not a guarantee of reliability. Data quality, architecture, training, numerical precision, and the way a model is evaluated all matter. A large model can produce a convincing error; a smaller specialized model can perform a narrow task well. To compare systems, ask what task was tested and under what conditions, rather than treating one number as a universal intelligence score.

Return to the animation and identify three different objects: a stored weight, an activation that changes with the sentence, and an output score. If the diagram uses moving dots, those dots represent information flow; they are not literal particles inside a model. Using the small equation above on paper, change an input while keeping a weight fixed, then change the weight while keeping the input fixed. Explain why these are different experiments. That distinction will help you understand fine-tuning, quantization, caches, and model releases throughout the course.

College extension · make the assumptions explicit

For a linear layer, write y = Wx + b. If W has shape m × n, x has n entries and y has m entries. During backpropagation, the chain rule relates a loss gradient at y to gradients at W and x. During inference, the same forward transformation can execute without constructing those training gradients. In attention, WQ, WK and WV are parameters; QKᵀ and its normalized scores are functions of the current activations. Keeping these categories separate prevents a common mistake: interpreting an attention heat map as a direct picture of stored model weights.

Sources and further investigation

Source review: October 28, 2026. Model-release claims are attributed to their publishers.

Open the focused reading page →

Reset this college path?

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