The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← AI 301 — Machine Learning, Neural Networks and Language

Weeks 12–14

Language models, attention and generated claims

Learning objectives

  • Explain and trace the mechanisms in language models, attention and generated claims.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

A language model estimates patterns over token sequences. Tokens are model-dependent pieces of text, not necessarily words. Predicting plausible continuations is different from verifying a claim about the world. Fluent explanations and formatted citations can be generated without corresponding evidence. Evaluate factual claims against reliable sources rather than treating style as a confidence measure.

Attention combines representations according to learned or computed compatibility scores. Queries, keys and values play different roles; softmax-normalized scores determine a weighted combination of value vectors. Positional information is needed to represent order. The mechanism supports contextual computation, but an attention weight is not automatically a faithful explanation of a final answer.

Separate pretraining, fine-tuning, prompting and retrieval. They change different parts of the system. Retrieval can supply current or private context without changing model weights, while still failing if retrieval misses the relevant passage or the model misuses it. Context windows are finite, and long inputs can obscure key evidence. Build evaluations that distinguish retrieval failures, unsupported generation, omissions and incorrect abstention. Avoid claiming that low-temperature output is guaranteed factual.

Worked reasoning The second score receives about 0.731 weight, the first about 0.269, producing a context near 17.31. Subtracting the maximum before exponentiation preserves softmax probabilities while reducing overflow risk. This scalar example illustrates normalized weighting, not a complete transformer, trained attention mechanism or explanation of a factual decision.

Extended teaching and laboratory

Attention forms a weighted combination of value representations using normalized scores. Softmax weights are positive and sum to one, but normalization is not a truth test. A high weight can reflect learned compatibility within the model rather than verified factual support. A generated sentence requires evidence beyond interpreting one internal weight.

Subtracting the maximum score before exponentiation preserves softmax ratios and helps numerical stability. This algebraic transformation changes neither the intended distribution nor the need to handle very large or invalid inputs carefully.

Worked problem Scores are [0, ln(3)] and values are [10,30]. Calculate the attention-weighted scalar, then explain what it does not establish.

Step-by-step reasoning 1. Exponentials are [1,3]; normalized weights are [.25,.75].

  1. The weighted value is .25×10+.75×30=25.
  1. Subtracting ln(3) gives exponentials [1/3,1], whose normalized weights remain [.25,.75].
  1. The result is a representation calculation. It does not establish that the second passage is true or supports a generated factual claim. That requires inspecting evidence and entailment.

Attention needs shapes, eligible context and a stable normalization

An attention calculation mixes supplied representations. A query asks for a combination; keys are compared with the query; values are combined using the resulting weights. Keep these roles separate even when all originate from the same sequence. A numerical weight does not label a sentence as true, authorized, endorsed or relevant to every question. Those are evidence and system-boundary questions outside the normalization itself.

For n queries with d features, Q has shape n×d. With m keys, K has shape m×d, so QKᵀ has shape n×m. Each query therefore receives m compatibility scores. Dividing by √d rescales those dot products before normalization. If V has shape m×p, multiplying the n×m weight matrix by V yields n×p outputs. A transposed array can contain all the expected numbers and still represent the wrong operation, so write the intended dimensions before implementing the loops.

For one query’s eligible scores si, softmax gives pi=exp(si)/Σexp(sj). The weights are nonnegative and sum to one. Subtracting the same finite constant M preserves the ratios because exp(si−M)=exp(si)exp(−M), and the shared factor cancels. Choosing the largest eligible score makes every exponent nonpositive and avoids overflow from directly exponentiating a large positive logit. This transformation cannot make invalid input, an overflowing dot product or every conceivable finite-precision operation safe; validate the numerical contract explicitly.

A mask excludes a key from this particular combination. Compute the maximum and denominator over eligible keys only. If a masked score of 10000 participates in the maximum while the only allowed score is 2, the allowed exponential can underflow and leave a zero denominator. Removing the masked key after normalization is also wrong: the remaining weights no longer sum to one unless they are normalized again. When no keys are eligible, the laboratory returns None as an explicit empty-result state. Returning a uniform average would invent a result from excluded items.

A causal mask is a model information-flow rule: a representation at one sequence position must not use future positions under the specified prediction setup. It differs from authorization. A permission boundary must exclude restricted material before it reaches model context; multiplying an already exposed representation by zero is not a complete access-control design. Keep a causal arithmetic mask and a document-authorization decision as separately testable properties.

Worked record: the same scores under different masks

Two queries each have pre-mask scores [0,ln(3)] over scalar values [10,30]. For query 1 allow only the first key; for query 2 allow both. The first query gives weight [1,0] and output 10. The second gives [1/4,3/4] and output 25. Replacing the second value with 100000 must leave query 1 unchanged under the mask, while query 2 changes. If no key is eligible, the output is None rather than 20 or zero. Zero is a valid numerical output in other records and should not silently mean that no information was available.

The laboratory also constructs scores from two-feature vectors: query [1,0], keys [0,0] and [√2 ln(3),0]. Dividing the dot products by √2 produces exactly the specified score pair. This makes the relation between the scalar worked calculation and the matrix-shaped implementation inspectable. It is a single attention head over synthetic values; it does not instantiate a complete trained language model.

From logits to a loss gradient

A vocabulary prediction can use a separate softmax over output logits z. For target class y, cross-entropy is L=−ln(py). A stable equivalent is logΣexp(zj−M)−(zy−M). Differentiating gives dL/dzi=pi−1[i=y]. This gradient refers to output logits and a chosen training target. It must not be confused with attention weights over input keys, even though both calculations use softmax.

With logits [0,ln(3)] and target class 0, probabilities are [0.25,0.75], loss is ln4≈1.38629, and the logit gradient is [−0.75,+0.75]. A learning-rate-0.1 descent step gives logits [0.075,ln(3)−0.075], increasing the target probability and reducing this loss. Changing the target to class 1 changes the gradient even though the original probabilities are unchanged. A coherent probability distribution can still be poorly calibrated or factually wrong in a real task; arithmetic consistency is necessary for the computation, not sufficient evidence for the application.

Independent transfer

Repeat the masked calculation with scalar values [−10,50], leaving scores and masks fixed. Then add 1000 to both eligible scores and explain which outputs should change. Finally change the cross-entropy target to class 1 and calculate its loss and logit gradient. Write tests for an entirely masked query, incompatible Q/K dimensions, a mismatched key/value count and a nonfinite score. Explain why a successful causal-mask test does not certify document authorization.

Compare the reasoning

The first masked output is −10 and the second is (−10)/4+3×50/4=35. Adding the same score shift leaves their normalized weights and outputs unchanged within numerical tolerance. For target class 1 the loss is −ln(0.75)=ln(4/3)≈0.287682 and the gradient is [+0.25,−0.25]. The all-masked branch should return an explicit empty state; invalid dimensions and nonfinite numerical inputs should fail rather than silently truncate a zip operation or produce a plausible average. Authorization additionally needs tests of what material entered the model boundary and which identity and current permission justified it. These arithmetic tests deliberately do not claim to perform that larger system review.

From text to a conditional sequence model

A tokenizer maps text into a sequence of vocabulary identifiers. A word tokenizer, character tokenizer and learned subword tokenizer create different prediction units. Their vocabulary, normalization, treatment of spaces and unknown-input behavior belong to the model contract. A token ID is a lookup index, not a numerical measurement whose distance from another ID measures semantic similarity. An embedding table maps each identifier to a learned vector. Keep training-derived vocabulary construction within the evaluation boundary; do not let evaluation labels or prohibited documents enter fitting.

For a token sequence t₁,…,tₙ, the probability chain rule factors its joint probability as the product of P(tᵢ|t₁,…,tᵢ₋₁). A context-limited model approximates these conditionals using only the context its architecture and input contract permit. For a fictional two-token sequence with first-token probability .5 and second-token conditional probability .25, joint probability is .125. Natural-log negative likelihood is ln 8; mean loss per token is ln 8/2 and perplexity is √8. These quantities require the same tokenizer, sequence boundaries and weighting for comparisons. A lower token-level perplexity under a different tokenizer does not automatically mean a better model of identical events.

Teacher forcing supplies the observed prefix during training. Shift inputs and targets correctly: for [start,A,B,end], inputs [start,A,B] predict [A,B,end]. The representation predicting B may use start and A, but must not inspect B or later tokens through an unmasked attention path. During autoregressive generation, the model instead extends its own generated prefix. Errors can alter later context, so fitting conditional probabilities on observed prefixes and evaluating a free-running task answer different questions.

Architecture around the already explained attention head

The retained attention laboratory supplies Q/K/V dimensions, scaled scores, eligible-key normalization and complete changed-mask calculations. A multi-head layer first applies distinct learned projections for each head. Each head computes its own attention output; concatenate these outputs and project the result back to the intended model width. With sequence length 3, model width 4, two heads and head width 2, each head output has shape 3×2; concatenation is 3×4. A4×4 output projection retains 3×4. These are chosen teaching dimensions, not a requirement that every implementation use exactly this parameterization.

Token embeddings without any order-sensitive mechanism do not themselves distinguish all permutations. Position vectors added to embeddings, or another explicitly designed positional mechanism, supply order information. Self-attention can then combine representations across positions. An encoder block commonly combines self-attention with a positionwise feed-forward network. The same feed-forward weights transform each position separately; it does not perform an additional exchange between positions. Residual addition requires compatible widths. Layer normalization rescales a position's feature vector using its own feature statistics and learned affine parameters, differing from batch normalization across examples. Pre-normalization and post-normalization are different block conventions; name the one being traced.

In an encoder–decoder model, the encoder represents the source sequence. Decoder self-attention obeys the causal output boundary, while cross-attention uses decoder queries and encoder keys and values. A decoder-only model omits that separate encoder/cross-attention arrangement. A vocabulary projection converts a position's representation into logits; its softmax concerns candidate output tokens, rather than the attention distribution over input positions. The preserved logit-gradient example demonstrates why those two distributions must not be conflated.

Suppose a two-feature representation is x=[1,−1] and a sublayer produces [2,0]. A residual sum is [3,−1]. Its feature mean is 1 and population variance 4. Ignoring learned affine scaling and using ε=0 for this nonzero-variance arithmetic illustration, normalization gives[1,−1]. Real implementations include positive ε and may normalize before the sublayer; they need not produce this exact value. Compatible shapes establish the arithmetic's form, not correct masking or useful representations.

Generated text and source evidence

Pretraining changes weights using a broad training objective. Fine-tuning changes them using further training; prompting supplies input context; retrieval selects context from a separate corpus. These mechanisms can be combined, but one does not substitute for verifying another's boundary. A retrieved passage can be irrelevant, outdated, a quotation of a rejected claim or an instruction that the application should treat as untrusted data. Evaluate retrieval coverage separately from source support and generation quality. Low-temperature decoding changes a sampling policy; it does not turn token probabilities into factual proof.

Optional changed sequence and shape reasoning

Change the second-token conditional probability from .25 to .5 while retaining the first .5. Joint probability becomes .25, total negative log-likelihood ln 4, mean loss ln 2 and perplexity 2. This is a probability calculation under a stipulated model, not evidence that a sentence is true. Change sequence length to 5 with the same two heads: head outputs 5×2, concatenation 5×4 and projected output 5×4. Changing the output projection to 4×6 would produce 5×6, which cannot be added directly to a 5×4 residual input. Restore the intended width or define an explicit skip projection. If a retrieved sentence says that an obsolete rule is no longer effective, citing the quoted old rule as current fails support even when attention gives that sentence high weight.

Optional criteria, one point each: trace tokens, shifted targets and conditionals; reconcile sequence likelihood and loss units; track multi-head/residual shapes and masking roles; distinguish generated likelihood from current source support. Explain all four for four points.

Apply the idea

Scores are [0, ln(3)] and values are [10,30]. Calculate the attention-weighted scalar, then explain what it does not establish.

A model places .95 attention weight on a sentence that quotes a false claim in order to refute it. Can that weight justify citing the claim as true?

Further computation — complete record

New complete record: scores [0,ln(3)] for each of two queries, values [10,30], first query mask [allowed,excluded], second mask [allowed,allowed]. The output-class logits are separately [0,ln(3)].

Repeat the masked calculation with scalar values [−10,50], leaving scores and masks fixed. Then add 1000 to both eligible scores and explain which outputs should change. Finally change the cross-entropy target to class 1 and calculate its loss and logit gradient. Write tests for an entirely masked query, incompatible Q/K dimensions, a mismatched key/value count and a nonfinite score. Explain why a successful causal-mask test does not certify document authorization.

Read the worked reasoning

No. Attention strength does not encode the cited sentence’s argumentative role or prove entailment. Read the surrounding passage and distinguish quotation, negation and endorsement. An answer should cite the evidence for the conclusion it actually states, not treat a numerical attention weight as an authority score.

Further computation reasoning

The first masked output is −10 and the second is (−10)/4+3×50/4=35. Adding the same score shift leaves their normalized weights and outputs unchanged within numerical tolerance. For target class 1 the loss is −ln(0.75)=ln(4/3)≈0.287682 and the gradient is [+0.25,−0.25]. The all-masked branch should return an explicit empty state; invalid dimensions and nonfinite numerical inputs should fail rather than silently truncate a zip operation or produce a plausible average. Authorization additionally needs tests of what material entered the model boundary and which identity and current permission justified it. These arithmetic tests deliberately do not claim to perform that larger system review.

Check understanding

Two queries have scores [0,ln(3)] over scalar values [10,30]. The first mask allows only the first key; the second allows both. What are the two attention outputs?

  1. 10 and 10
    Feedback

    The second query permits both keys and must normalize their two scores; ignoring the second key changes that requested operation.

  2. 25 and 25
    Feedback

    The first query cannot use the second key. Its eligible weight is [1,0], giving 10.

  3. 10 and 25
    Feedback

    The first query returns 10. With both keys eligible, weights [0.25,0.75] produce 25 for the second.

Further reading

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

Use the preserved original investigation and connected Academy preparation/application below. Compare your reasoning with its optional complete model. Historical source directions remain in immutable edition4.

My learning →