Attention & Transformers

Raw Text to Packed Causal-LM Examples

How raw documents become token IDs, packed blocks, shifted labels, ignored positions, and a tiny masked causal-LM loss.

status: reviewimportance: criticaldifficulty 3/5math: undergraduateread: 12mlive demo

Concept Structure

Raw Text to Packed Causal-LM Examples

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
3next concepts
5related links

Learner Contract

What this page should let you do.

You are here becauseHow raw documents become token IDs, packed blocks, shifted labels, ignored positions, and a tiny masked causal-LM loss.

This Attention & Transformers concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Test the linkManipulate one control and predict the visible change.Then continue to Causal Self-Attention Mask (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources3 cited
Codeattached
Demolive
Reviewed2026-07-02
Updatedpage 2026-07-02

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptRaw Text to Packed Causal-LM ExamplesAttention & Transformers
3 sources attachedLocal snapshot ready
concept:attention-transformers/raw-text-to-packed-causal-lm-examples
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

A Transformer does not train on "text" in the loose everyday sense. It trains on a table.

For causal language modeling, each row says:

  • this is the token the model sees at position ii
  • this is the next token it should predict
  • this position either counts toward the loss or is ignored

That table is where many implementation bugs begin. If labels are copied instead of shifted, the task becomes wrong. If a document boundary is silently treated as a normal transition, the model is asked to predict the start of the next unrelated document. If padding contributes to loss, the loss is partly measuring bookkeeping.

This page uses a tiny corpus so the whole training object fits on screen. It is a local accounting probe, not a model-quality result.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let a packed block contain token IDs

z0,z1,,zT1.z_0, z_1, \dots, z_{T-1}.

The model input at position ii is

xi=zi.x_i = z_i.

The causal-LM target is the next token:

yi=zi+1.y_i = z_{i+1}.

But not every position should contribute to the loss. We attach a mask

mi{0,1}.m_i \in \{0, 1\}.

For this local accounting probe, mi=0m_i = 0 when the next-token transition crosses a document boundary or touches padding. Otherwise mi=1m_i = 1.

If the model predicts probabilities pθ(yixi)p_\theta(y_i \mid x_{\le i}), the masked mean negative log likelihood is

L=imi[logpθ(yixi)]imi.\mathcal L = \frac{\sum_i m_i\left[-\log p_\theta(y_i \mid x_{\le i})\right]}{\sum_i m_i}.

The important move is not the number. The important move is knowing exactly which rows counted.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import math

tok = {"<pad>": 0, "<bos>": 1, "<eos>": 2, "alpha": 3, "beta": 4, "gamma": 5}
ids = [tok[t] for t in ["<bos>", "alpha", "beta", "<eos>", "<bos>", "gamma", "<eos>", "<pad>"]]
ignore = -100
labels = [ids[i + 1] if i + 1 < len(ids) else ignore for i in range(len(ids))]

# Mask EOS-to-BOS document boundary and padding positions in this toy policy.
mask = [1, 1, 1, 0, 1, 1, 0, 0]
labels = [label if keep else ignore for label, keep in zip(labels, mask)]

# Tiny add-one bigram probabilities, just to make a visible loss.
counts = {
    tok["<bos>"]: {tok["alpha"]: 1, tok["gamma"]: 1},
    tok["alpha"]: {tok["beta"]: 1},
    tok["beta"]: {tok["<eos>"]: 1},
    tok["gamma"]: {tok["<eos>"]: 1},
}
vocab = [v for k, v in tok.items() if k != "<pad>"]
nll = []
for x, y, keep in zip(ids, labels, mask):
    if keep:
        row = counts.get(x, {})
        p = (row.get(y, 0) + 1) / (sum(row.values()) + len(vocab))
        nll.append(-math.log(p))

print("active positions:", [i for i, keep in enumerate(mask) if keep])
print("mean nll:", round(sum(nll) / len(nll), 3))
04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Before reveal, choose which packed-block positions should count toward the loss. The reveal shows the shifted labels, ignored positions, toy negative log likelihood bars, and the exact caveat: this is an input-to-loss accounting witness, not model-quality evidence.

Live Concept Demo

Explore Raw Text to Packed Causal-LM Examples

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Raw Text to Packed Causal-LM Examples should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

How raw documents become token IDs, packed blocks, shifted labels, ignored positions, and a tiny masked causal-LM loss.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Raw Text to Packed Causal-LM Examples should make visible.

Visual Inquiry

Make the image answer a mathematical question

How raw documents become token IDs, packed blocks, shifted labels, ignored positions, and a tiny masked causal-LM loss.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Raw Text to Packed Causal-LM Examples easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2026Stanford CS336: Language Modeling from ScratchStanford CS336 course staff

Course-level source for treating tokenizer, model, optimizer, and training system pieces as implementation objects in a language-model-from-scratch route.

Open source
documentation · 2026Hugging Face Transformers: Causal language modelingHugging Face

Documentation-level source for causal language-modeling preprocessing patterns such as grouping token sequences and using a language-modeling data collator. This page does not claim exact API behavior beyond the docs-linked scope.

Open source
reference · 2026Continuous Function LLM Input To Loss Level 2 witnesscodex

Local deterministic accounting probe for raw documents, fixed token IDs, packed block, shifted labels, loss mask, and small causal-LM loss.

Open source

Claim Review

How raw documents become token IDs, packed blocks, shifted labels, ignored positions, and a tiny masked causal-LM loss.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources3 references

cs336-language-modeling-from-scratch, hf-causal-language-modeling-docs, cf-llm-input-to-loss-witness

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedA causal-LM training example can be made explicit as input token IDs, next-token labels, a loss mask for ignored positions, and a masked mean cross-entropy loss; this local accounting probe is evidence about bookkeeping, not model quality.Claim metadata: source checked

CS336 supports the route-level need to implement language-model pieces from scratch. Hugging Face causal-LM docs support practical preprocessing around grouped token sequences and language-modeling collation. The local probe exactly supports this page's small token IDs, shifted labels, boundary/padding masks, and masked mean loss.

Sources: Stanford CS336: Language Modeling from Scratch, Hugging Face Transformers: Causal language modeling, Continuous Function LLM Input To Loss Level 2 witnessThis claim does not cover production tokenizers, exact Hugging Face API behavior, full LLM-from-scratch coverage, benchmark validity, contamination handling, data quality, or model-quality results.A bounded review summary is present; still check caveats and exact reference scope.

Checked the CS336 course anchor, Hugging Face causal-language-modeling docs, existing LLM_INPUT_TO_LOSS source spine, and the deterministic Level 2 witness. The learner-facing page is review-status pending GPT Pro publication critique.

Reviewer: codex-local-source-audit; reviewed 2026-07-02

Practice Loop

Try the idea before it explains itself

How raw documents become token IDs, packed blocks, shifted labels, ignored positions, and a tiny masked causal-LM loss.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Raw Text to Packed Causal-LM Examples.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptRaw Text to Packed Causal-LM ExamplesAttention & Transformers

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptAttention & Transformers

Raw Text to Packed Causal-LM Examples

Attached question

What is the smallest example that makes Raw Text to Packed Causal-LM Examples click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Raw Text to Packed Causal-LM Examples Selected item key: recorded for copy. Context: Attention & Transformers Page anchor: recorded for copy. Open question: What is the smallest example that makes Raw Text to Packed Causal-LM Examples click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/attention-transformers/raw-text-to-packed-causal-lm-examples concept:attention-transformers/raw-text-to-packed-causal-lm-examples