Coding tutorial · Build it from scratch

The Hugging Face Stack

We can already train a model in raw PyTorch. Here we rebuild each thing Hugging Face automates, run both versions, and check that the numbers agree.

Hugging FaceTraining loopsModel integration

A small package, hfstack, that writes out by hand what each Hugging Face library does: assistant-only labels, a collator, a training loop that matches Trainer to float precision, an Accelerate loop, generate() as a plain loop, a safetensors reader, and a custom model and VLM that plug into the Auto classes.

Time
About 3 hours, plus model downloads
Hardware
A CPU is enough. No step needs a GPU. Every CPU output here ran on an AMD EPYC 7R13 with 8 threads. Two runs were repeated once on a GPU for comparison.
You need
Python 3.10+, the raw loop from C1, and these libraries: transformers 5.x, datasets, accelerate, peft, trl
Package
hfstack
Final repo tree c02-hf-stack/
c02-hf-stack/
├── README.md
├── hfstack/
│   ├── utils.py            # device, tiny configs, parameter counts
│   ├── inspection.py       # print configs, outputs and caches
│   ├── chat.py             # messages to assistant-only labels
│   ├── data.py             # synthetic arithmetic dataset
│   ├── collators.py        # text and vision collators
│   ├── training.py         # raw loop and matching Trainer run
│   ├── custom_trainer.py   # compute_loss override with z-loss
│   ├── accelerate_loop.py  # the raw loop on N processes
│   ├── generation.py       # generate() written as a loop
│   ├── lora.py             # LoRA math checked against PEFT
│   ├── trl_runs.py         # TRL dataset formats and reward
│   ├── hub.py              # safetensors parsed by hand
│   ├── custom_model.py     # config, model, Auto registration
│   └── custom_vlm.py       # sub-configs, image token, scatter
├── scripts/                # 01 to 15 for the steps, plus checks
├── benchmarks/             # map, loop and generate timings
├── tests/                  # equivalence against the library
└── results/                # the real outputs quoted here

The plan

We know how to train a model in raw PyTorch. What does the Hugging Face stack do for us, and how do we check that it does it correctly?

The stack is easy to use and hard to see into. One call to Trainer(...).train() makes dozens of choices. If you cannot name those choices, you cannot debug them.

So every step below follows one rule. We write the thing the library does, run both versions, and compare the numbers. When they agree, we know what the library does. When they disagree, we have found a choice we did not know about.

Two small models carry the post. The first is SmolLM2-135M, a real 134.5 M parameter checkpoint, small enough to run on a CPU. The second is a tiny random Llama with 106,816 parameters, which trains in seconds. Both are LlamaForCausalLM, so they run the same code.

The task is synthetic arithmetic, for example "What is 49 - 97?". The right answer is always known, so labels and rewards never need a judge.

Figure 1The stack, following one training job. Each frame shows the library in charge, what crosses into it, and the step of this post that rebuilds it. PEFT and TRL sit beside the main path: PEFT wraps the model and TRL subclasses Trainer.

Clone the repo once. Every command below runs from its root.

$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"

Every output here came from an AMD EPYC 7R13 CPU limited to 8 threads, with no GPU. The Accelerate comparison in step 9 uses 1 thread per process. Steps 10 and 11 also show one GPU run each, on one NVIDIA H100 80GB HBM3 (torch 2.15.0, CUDA 13.2), always labelled and kept apart from the CPU numbers. Most outputs are shapes and equalities, which do not depend on hardware. Timings do. Each timing is a single run on a busy shared machine, with the load average above 70 and no variance estimate. Read them as rough guides only, and do not read a ranking into small gaps.

Step 01

Read the config, and let the Auto classes pick a model

GoalSee that a small JSON file decides every tensor shape, and follow how from_pretrained finds the right class.

A checkpoint has two parts: a description of the architecture and the weights. Transformers keeps them apart. The description is config.json, which is 905 bytes for SmolLM2. The weights are model.safetensors, which is 538 MB in float32.

That split pays off in three ways. You can read an architecture without downloading its weights. You can build the same architecture with new weights. You can catch a shape mismatch before any bytes move.

# 1. The config: a small JSON file that fully describes the architecture. No weights are downloaded.
config = AutoConfig.from_pretrained(BASE_LM)
print(f"type(config) = {type(config).__name__}")
for name, value in config_fields(config).items():
    print(f"  {name:<24} {value}")

# 2. Dispatch: config.model_type -> class name -> class.
print(f"\nmodel_type {config.model_type!r} -> {MODEL_FOR_CAUSAL_LM_MAPPING_NAMES[config.model_type]}")

# 3. The same config, three heads. Built from the config only, so weights are random.
tiny = tiny_llama_config(num_labels=3)
for auto_cls in (AutoModel, AutoModelForCausalLM, AutoModelForSequenceClassification):
    model = auto_cls.from_config(tiny)
    _, total = count_parameters(model)
    head = [n for n, _ in model.named_children()][-1]
    print(f"{auto_cls.__name__:<36} -> {type(model).__name__:<32} last child: {head:<8} params: {total:,}")
Listing 1Read the config, follow the dispatch, then build the same config with three different heads.

AutoConfig downloads only the JSON and returns a LlamaConfig. config_fields is a small helper that prints the fields we care about. The next line shows the dispatch: the string model_type indexes a table of class names.

$ .venv/bin/python c02-hf-stack/scripts/01_config_and_auto.py
type(config) = LlamaConfig
  model_type               llama
  architectures            ['LlamaForCausalLM']
  hidden_size              576
  num_hidden_layers        30
  num_attention_heads      9
  num_key_value_heads      3
  head_dim                 64
  intermediate_size        1536
  vocab_size               49152
  max_position_embeddings  8192
  rope_parameters          {'rope_theta': 100000, 'rope_type': 'default'}
  tie_word_embeddings      True
  dtype                    torch.bfloat16

model_type 'llama' -> LlamaForCausalLM
AutoModel                            -> LlamaModel                       last child: rotary_emb params: 106,816
AutoModelForCausalLM                 -> LlamaForCausalLM                 last child: lm_head  params: 106,816
AutoModelForSequenceClassification   -> LlamaForSequenceClassification   last child: score    params: 107,008

AutoModel                    last_hidden_state (2, 7, 64)
AutoModelForCausalLM         logits            (2, 7, 512)
AutoModelForSequenceClass.   logits            (2, 3)

LlamaForCausalLM: 134,515,008 parameters (134.5 M), dtype torch.float32
lm_head tied to embed_tokens: True

Dispatch has three stages. config.json holds "model_type": "llama". AutoConfig maps that string to LlamaConfig. Then each Auto model class holds its own table from config class to model class. That is why the same config gives a different class for each Auto class.

Same config and same input (B = 2, T = 7, vocabulary 512, D = 64, 3 labels)
Auto classTop fieldShapeMeaning
AutoModellast_hidden_state(2, 7, 64)One vector per token. No head.
AutoModelForCausalLMlogits(2, 7, 512)One score per vocabulary entry, per token.
AutoModelForSequenceClassificationlogits(2, 3)One score per class, per sequence.

The config fields are enough to compute the whole parameter count. Try it below. The two presets reproduce the real counts from the output above, which confirms the formula.

Parameters
float32 weights
q_proj, k_proj
Cached keys
Figure 2From config to parameter count. The formula is the one LlamaForCausalLM uses: bias-free projections, three MLP matrices per block, two norm vectors per block and one final norm. It gives 134,515,008 for SmolLM2 and 106,816 for the tiny config, equal to what the script printed. The sliders are illustrative settings, not checkpoints.

Checkpoint

  • You can read head_dim and the cached key shape straight from the config.
  • You can explain why AutoModelForCausalLM.from_config needs no download and has random weights.
Step 02

Turn text into tensors with a tokenizer

GoalInspect input_ids and attention_mask, and find each special-token default that can surprise you.

A tokenizer maps text to integer IDs and back. It also owns the rules for padding and truncation, and those rules decide what a batch looks like.

# 1. Encode and decode. Tokens are not words: the leading space belongs to the token.
text = "The backward pass computes gradients."
ids = tok(text)["input_ids"]
print("input_ids :", ids)
print("tokens    :", tok.convert_ids_to_tokens(ids))
print("decoded   :", repr(tok.decode(ids)))
Listing 2Encode and decode. Tokens are pieces of text, not words.
$ .venv/bin/python c02-hf-stack/scripts/02_tokenizer.py
input_ids : [504, 17301, 1301, 35864, 26085, 30]
tokens    : ['The', 'Ġbackward', 'Ġpass', 'Ġcomputes', 'Ġgradients', '.']
decoded   : 'The backward pass computes gradients.'

          bos             eos             pad             pad side  
M2-135M   <|endoftext|>   <|endoftext|>   None            right     
nstruct   <|im_start|>    <|im_end|>      <|im_end|>      right     
BOS added automatically: False

right padding
 input_ids      [[19556, 905, 0, 0, 0, 0], [504, 17301, 1301, 35864, 26085, 30]]
 attention_mask [[1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1]]
left padding
 input_ids      [[0, 0, 0, 0, 19556, 905], [504, 17301, 1301, 35864, 26085, 30]]
 attention_mask [[0, 0, 0, 0, 1, 1], [1, 1, 1, 1, 1, 1]]
truncation, max_length=3: [504, 17301, 1301]

The Ġ in Ġbackward stands for a leading space. The space belongs to the token, so "backward" at the start of a sentence would be a different ID from " backward" in the middle.

The table in the output holds three things worth checking on any new checkpoint.

A batch of two texts with padding (B = 2, N = 6)
TensorShapeMeaning
input_ids(B, N)Token IDs. N is the longest row in the batch.
attention_mask(B, N)1 on real tokens and 0 on padding.

Added tokens are the last trap. Adding a token grows the tokenizer at once, but it does nothing to the model. The embedding table still has the old number of rows.

# 4. Added tokens: the vocabulary grows, so the embedding matrix must grow with it.
print("\nlen(tokenizer) before:", len(tok))
added = tok.add_special_tokens({"additional_special_tokens": ["<tool_call>", "</tool_call>"]})
print("added:", added, "| len(tokenizer) after:", len(tok))
print("new token ids:", tok("<tool_call>x</tool_call>")["input_ids"])

model = AutoModelForCausalLM.from_config(tiny_llama_config(vocab_size=49152))
print("embedding before resize:", tuple(model.get_input_embeddings().weight.shape))
try:
    import torch

    model(input_ids=torch.tensor([[len(tok) - 1]]))
except IndexError as err:
    print("forward with a new token, before resize -> IndexError:", err)
model.resize_token_embeddings(len(tok))
print("embedding after resize :", tuple(model.get_input_embeddings().weight.shape))
print("lm_head after resize   :", tuple(model.get_output_embeddings().weight.shape))
print("config.vocab_size      :", model.config.vocab_size)
print("lm_head still tied     :", model.lm_head.weight is model.model.embed_tokens.weight)
Listing 3Grow the vocabulary, watch the model fail, then resize it.

Checkpoint

  • You know the BOS, EOS and PAD tokens of your checkpoint, and whether BOS is added for you.
  • test_encode_decode_round_trip and test_smollm2_tokenizer_adds_no_bos pass.
Step 03

Turn a conversation into token IDs and labels

GoalFollow a list of messages down to the exact tokens the model sees, then keep labels only on what the assistant wrote.

A chat model does not read messages. It reads one long token sequence. A chat template is a small Jinja program, stored with the tokenizer, that turns the message list into that sequence. The reason for training this way is in the theory post.

Theory inTeaching a language model to follow instructions
--- the template renders plain text ---
'<|im_start|>system\nYou are concise.<|im_end|>\n<|im_start|>user\nWhat is 2+2?<|im_end|>\n<|im_start|>assistant\n4<|im_end|>\n'

--- add_generation_prompt stops right where the model should start writing ---
'<|im_start|>system\nYou are concise.<|im_end|>\n<|im_start|>user\nWhat is 2+2?<|im_end|>\n<|im_start|>assistant\n'

--- tokenize=True returns a BatchEncoding in transformers 5 ---
BatchEncoding ['input_ids', 'attention_mask']

The template renders plain text first. add_generation_prompt=True stops right after the assistant header, where the model should begin writing. In transformers 5, tokenize=True returns a BatchEncoding and not a list, so our helper asks for a dict and takes input_ids.

Now the labels. In supervised fine-tuning, the model should learn to write the reply. It should not learn to predict the system prompt. So we set every other label to -100, the value cross_entropy skips. The hard part is finding which tokens are the reply.

def assistant_labels_by_prefix(tokenizer: PreTrainedTokenizerBase, messages: list[Message]) -> dict[str, list[int]]:
    """Tokenize a conversation and keep labels only on assistant tokens.

    Returns `input_ids`, `attention_mask` and `labels`, each of length N (one conversation, no padding).
    Labels are -100 everywhere except assistant content and its end-of-turn token.
    """
    input_ids = chat_ids(tokenizer, messages)
    labels = [IGNORE_INDEX] * len(input_ids)
    end_of_turn = tokenizer.eos_token_id

    for i, message in enumerate(messages):
        if message["role"] != "assistant":
            continue
        # Tokens before this reply: everything up to and including the "<|im_start|>assistant\n" header.
        prefix = chat_ids(tokenizer, messages[:i], add_generation_prompt=True)
        through = chat_ids(tokenizer, messages[: i + 1])
        if input_ids[: len(through)] != through or through[: len(prefix)] != prefix:
            raise ValueError("chat template is not prefix-preserving; use a template with {% generation %} tags")
        start, stop = len(prefix), len(through)
        # Train on the reply and its end-of-turn token, not on the newline the template adds after it.
        while stop > start and through[stop - 1] != end_of_turn:
            stop -= 1
        labels[start:stop] = input_ids[start:stop]

    return {"input_ids": input_ids, "attention_mask": [1] * len(input_ids), "labels": labels}
Listing 4Prefix diffing. Render the conversation up to the reply, render it again through the reply, and label the difference.

Read the loop slowly. prefix renders everything before this reply, including the assistant header. through renders everything up to and including the reply. The reply is the tokens between those two lengths.

The while loop trims the newline the template adds after <|im_end|>. The end-of-turn token stays labelled, because the model must learn to stop. The newline is not labelled, because the model never writes it.

The check on the two prefixes matters. Some templates change earlier text when a new message arrives. Prefix diffing would label the wrong tokens there, so the function raises an error and does not guess.

Tokens in view
Labelled
End-of-turn labelled

Figure 3The real 28 tokens from the script, in order. The number under each token is its ID. A blue cell is a training target. A grey cell has label -100. Choose a policy to see what the model would be trained on, and select a token to read its details.
$ .venv/bin/python c02-hf-stack/scripts/03_chat_template.py

There is a second way to find the reply. A training template can wrap assistant text in {% generation %} markers, and then return_assistant_tokens_mask=True returns the mask directly. Our assistant_labels_by_template does that. The script confirms that both methods give the same labels.

prefix diffing == generation tags: True

--- a template adds what you did not ask for: no system message given ---
'<|im_start|>system\nYou are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>\n<|im_start|>user\nWhat is 2+2?<|im_end|>\n<|im_start|>assistant\n4<|im_end|>\n'

Checkpoint

  • Only two positions carry labels: the reply token and the end-of-turn token.
  • test_two_assistant_mask_methods_agree and test_only_assistant_text_and_end_of_turn_are_labelled pass.
Step 04

Add images with a processor

GoalSee that a VLM processor is a tokenizer plus an image processor, and that the image decides how long the text is.

AutoProcessor bundles a tokenizer with an image processor, and with a video processor when the model has one. Its job is more than two calls side by side. The prompt holds one <image> placeholder. The processor must expand it into exactly as many tokens as the vision encoder will produce.

processor = AutoProcessor.from_pretrained(SMALL_VLM)
config = AutoConfig.from_pretrained(SMALL_VLM)
print(type(processor).__name__, "=", type(processor.tokenizer).__name__, "+", type(processor.image_processor).__name__)

image = card(640, 480, "red square")
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What does it say?"}]}]
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
print("\nprompt text:", repr(prompt))

print("\n--- 640x480 image, default settings ---")
batch = processor(text=[prompt], images=[[image]], return_tensors="pt")
show(batch)
ids = batch["input_ids"][0]
image_tokens = (ids == config.image_token_id).sum().item()
tiles = batch["pixel_values"].shape[1]
print(f"  image tokens in input_ids: {image_tokens} = {tiles} tiles x {image_tokens // tiles} tokens per tile")
print("  first 8 tokens:", processor.tokenizer.convert_ids_to_tokens(ids[:8].tolist()))
Listing 5Load the processor, render a prompt, and count the image tokens it inserts.
$ .venv/bin/python c02-hf-stack/scripts/04_processor.py
Idefics3Processor = GPT2Tokenizer + Idefics3ImageProcessorPil

prompt text: '<|im_start|>User:<image>What does it say?<end_of_utterance>\nAssistant:'

--- 640x480 image, default settings ---
  input_ids              (1, 875)                   int64
  attention_mask         (1, 875)                   int64
  pixel_values           (1, 13, 3, 512, 512)       float32
  pixel_attention_mask   (1, 13, 512, 512)          int64
  image tokens in input_ids: 832 = 13 tiles x 64 tokens per tile
  first 8 tokens: ['<|im_start|>', 'User', ':', '<fake_token_around_image>', '<row_1_col_1>', '<image>', '<image>', '<image>']
  tokens per tile from config: (512/16)^2 / 4^2 = 64

--- same image, do_image_splitting=False ---
  input_ids              (1, 80)                    int64
  attention_mask         (1, 80)                    int64
  pixel_values           (1, 1, 3, 512, 512)        float32
  pixel_attention_mask   (1, 1, 512, 512)           int64
  image tokens: 64

--- batch of two different images: pixel_values pad on the tile axis ---
  input_ids              (2, 1140)                  int64
  attention_mask         (2, 1140)                  int64
  pixel_values           (2, 17, 3, 512, 512)       float32
  pixel_attention_mask   (2, 17, 512, 512)          int64
  real tiles per image: [13, 17]

Figure 4One 640 × 480 image going through the SmolVLM processor. The grid of 4 columns and 3 rows, and the extra global tile, were read from the row and column tokens by scripts/16_side_checks.py. All other counts are in the output above.
One image, one prompt (B = 1, 13 tiles, N = 875)
TensorShapeMeaning
input_ids(B, N)43 text and layout tokens plus 832 image tokens.
attention_mask(B, N)Padding mask over the text.
pixel_values(B, tiles, 3, 512, 512)Every tile of every image, normalised.
pixel_attention_mask(B, tiles, 512, 512)Which pixels of each tile are real.

The processor is where one model family differs from another. The batch keys are not universal. Qwen2-VL returns a flat patch tensor with a grid tensor beside it. Only its image processor ran here. Its full AutoProcessor also loads a video processor, which needs torchvision, and torchvision is not installed. So the video side is not covered.

--- a different VLM family has different keys: Qwen2-VL's image processor ---
  pixel_values           (1564, 1176)               float32
  image_grid_thw         (1, 3)                     int64
  image_grid_thw: [1, 34, 46] -> 1564 patches; merge_size 2
  image_pad tokens the text needs: 1564 / 2^2 = 391
Two families, one image of 640 × 480
AspectSmolVLM (Idefics3)Qwen2-VL
Pixel tensor(1, 13, 3, 512, 512)(1564, 1176)
LayoutTiles, one row per imageFlat patches, grid in image_grid_thw
Image tokens13 × 64 = 8321564 / 2² = 391

Checkpoint

  • Tiles times tokens per tile equals the number of image tokens in input_ids.
  • test_processor_token_count_matches_vision_config passes.
Step 05

Store and transform examples with Datasets

GoalUnderstand why a Dataset is not a list[dict], how the cache decides to skip work, and when to stream.

We start with the data itself. Each row is a sum with a known answer. Synthetic data keeps every later label exact.

def make_arithmetic_rows(n: int, seed: int = 0, max_operand: int = 99) -> list[dict]:
    """Return `n` rows like {"id": 3, "a": 17, "b": 25, "op": "+", "answer": 42}."""
    rng = random.Random(seed)
    rows = []
    for i in range(n):
        a, b = rng.randint(0, max_operand), rng.randint(0, max_operand)
        op = rng.choice("+-")
        answer = a + b if op == "+" else a - b
        rows.append({"id": i, "a": a, "b": b, "op": op, "answer": answer})
    return rows
Listing 6A row is a plain dict. The seed makes the whole dataset reproducible.

Now load it the way any dataset is loaded. load_dataset reads local files too, so the Hub is one source among several.

# 1. load_dataset works on local files too; the Hub is one source among several.
path = write_jsonl(make_arithmetic_rows(2_000), tmp / "arithmetic.jsonl")
data = load_dataset("json", data_files={"train": str(path)}, cache_dir=str(tmp / "cache"))
print(type(data).__name__, "->", data)
train = data["train"]
print("features:", train.features)

# 2. Arrow: columns on disk, memory-mapped. Indexing reads and decodes one row.
print("\nrow 0        :", train[0])
print("cache files  :", [Path(f["filename"]).name for f in train.cache_files])
print("arrow table  :", type(train.data).__name__, "| nbytes:", train.data.nbytes)
python_list = train.to_list()
print("python list  :", sys.getsizeof(python_list) + sum(sys.getsizeof(r) for r in python_list), "bytes (shallow, no int objects)")

# 3. Transformations return new datasets. The fingerprint names each state.
print("\nfingerprint            :", train._fingerprint)
positive = train.filter(lambda row: row["answer"] >= 0)
print("filter(answer >= 0)    :", positive._fingerprint, len(positive), "rows")
shuffled = train.shuffle(seed=0)
print("shuffle(seed=0)        :", shuffled._fingerprint, "| indices mapping:", shuffled._indices is not None)
print("select(range(4))       :", train.select(range(4))._fingerprint, "| ids", train.select(range(4))["id"][:4])
print("first ids after shuffle:", shuffled["id"][:6])
Listing 7Load, look inside Arrow, then apply three transforms. Each one returns a new dataset with a new fingerprint.
$ .venv/bin/python c02-hf-stack/scripts/05_datasets.py
DatasetDict -> DatasetDict({
    train: Dataset({
        features: ['id', 'a', 'b', 'op', 'answer'],
        num_rows: 2000
    })
})
features: {'id': Value('int64'), 'a': Value('int64'), 'b': Value('int64'), 'op': Value('string'), 'answer': Value('int64')}

row 0        : {'id': 0, 'a': 49, 'b': 97, 'op': '-', 'answer': -48}
cache files  : ['json-train.arrow']
arrow table  : MemoryMappedTable | nbytes: 74000
python list  : 384184 bytes (shallow, no int objects)

fingerprint            : d9ca2f9e1eafa422
filter(answer >= 0)    : 5c6e7c57485d18b0 1486 rows
shuffle(seed=0)        : fc182f7b9d5de5db | indices mapping: True
select(range(4))       : bc419f7ef77d8972 | ids [0, 1, 2, 3]
first ids after shuffle: [1946, 1236, 1380, 1949, 1633, 474]

Your fingerprints will not match the ones printed here. Two runs of this script on the same machine gave different values. Within one run they behave as described below, so compare fingerprints inside one run and not against this page.

Arrow stores data by column, as flat typed arrays. Here that is 74,000 bytes for 2,000 rows, or 37 bytes per row: four 8-byte integers, one character and a 4-byte string offset. The Python list costs 384,184 bytes before counting any integer object.

The table is also memory-mapped. MemoryMappedTable means the bytes stay in a file and the operating system pages them in when needed. Several worker processes can share them, and a dataset can be larger than RAM.

Look at what shuffle did: indices mapping: True. It moved no rows. It wrote a separate list of row numbers and left the table alone.

Figure 5Each transform makes a new state with a new fingerprint. The values shown are the real fingerprints and timings from the output. The cache key for a map combines the input fingerprint with a hash of the function.

Next comes tokenizing with map. We use the labels from step 3, drop the old columns, and run it twice.

def tokenize(row: dict) -> dict:
    return assistant_labels_by_prefix(tok, to_messages(row)["messages"])


for attempt in ("first ", "second"):
    start = time.perf_counter()
    tokenized = train.map(tokenize, remove_columns=train.column_names)
    print(f"\n{attempt} map: {time.perf_counter() - start:6.2f} s | fingerprint {tokenized._fingerprint}")
print("columns after remove_columns:", tokenized.column_names)
print("row 0 lengths:", {k: len(v) for k, v in tokenized[0].items()})
Listing 8The same map, twice. The second call finds the first call's result on disk.
first  map:   1.47 s | fingerprint 6406fcdaa9bb7760

second map:   0.55 s | fingerprint 6406fcdaa9bb7760
columns after remove_columns: ['input_ids', 'attention_mask', 'labels']
row 0 lengths: {'input_ids': 41, 'attention_mask': 41, 'labels': 41}

batched map, 4 rows in -> 8 rows out: {'id': [0, 0, 1, 1], 'copy': [0, 1, 0, 1]}

scripts/16_side_checks.py times that hash alone, 9 times in each of 3 runs.

--- Hasher.hash, 9 repeats in one process, seconds ---
object                         first     min  median     max  distinct hashes
function reaching nothing      0.001   0.000   0.000   0.001  1
tokenizer alone                0.733   0.444   0.460   0.733  1
function reaching tokenizer    0.469   0.450   0.460   0.469  1

The median was 0.46 to 0.52 s across the 3 runs. That suggests the hash is most of the 0.55 s.

The benchmark compares ways of running the same tokenization.

$ .venv/bin/python c02-hf-stack/benchmarks/bench_map.py
20,000 rows, AMD EPYC 7R13, 8 threads, TOKENIZERS_PARALLELISM=false
per row                               3.44 s        5,813 rows/s
batched, batch_size=1000              1.07 s       18,626 rows/s
batched, batch_size=1000, 2 procs     1.08 s       18,596 rows/s

In this run, batching was about 3 times faster. A likely reason is that a fast tokenizer handles a whole batch in one call into Rust, but we did not test that. A second process gained nothing here: 18,596 rows/s against 18,626. This is one run on a busy machine, so a rerun may differ. Starting workers and moving results back has its own cost, and this is a small job, so measure before you raise num_proc. A batched function receives a dict of lists and may also return a different number of rows, as the explode function in the script does.

Streaming

A Dataset needs the whole corpus on disk. Pretraining corpora are often too big for that, so they are read as a stream, a point the theory post covers in How LLMs are pretrained. With streaming=True you get an IterableDataset: it has an order but no length and no random access.

# 6. Streaming: an IterableDataset has no length and no random access, only an order.
stream = load_dataset("json", data_files=str(path), split="train", streaming=True)
print("\n", type(stream).__name__, "| has __len__:", hasattr(stream, "__len__"))
print("first row      :", next(iter(stream)))
transformed = stream.filter(lambda r: r["answer"] >= 0).map(lambda r: {"text": f"{r['a']}{r['op']}{r['b']}"})
print("lazy transforms:", next(iter(transformed)))
buffered = stream.shuffle(seed=0, buffer_size=100)
print("buffer shuffle, first ids:", [row["id"] for row, _ in zip(buffered, range(6))])
print("take(2)        :", [row["id"] for row in stream.take(2)])
print("skip(1998) ids :", [row["id"] for row in stream.skip(1998)])
Listing 9The same file as a stream. Transforms are lazy and run while you iterate.
 IterableDataset | has __len__: False
first row      : {'id': 0, 'a': 49, 'b': 97, 'op': '-', 'answer': -48}
lazy transforms: {'id': 2, 'a': 51, 'b': 38, 'op': '-', 'answer': 13, 'text': '51-38'}
buffer shuffle, first ids: [82, 36, 20, 5, 93, 16]
take(2)        : [0, 1]
skip(1998) ids : [1998, 1999]

FineWeb-Edu on the Hub: 3,038 files, 5.84 TB
wikitext from the Hub, first 3 rows in 5.6 s, no full download: {'text': ' = Valkyria Chronicles III = \n'}

The last two lines show why streaming matters. FineWeb-Edu on the Hub is 3,038 files and 5.84 TB, far more than this tutorial wants on disk. The script reads the first rows of a Hub dataset without a full download.

Two kinds of dataset
AspectDatasetIterableDataset
ModelRandom-access tableStream of examples
len() and ds[i]YesNo
Disk needed firstWhole corpusNone
ShuffleGlobal, through an index listApproximate, inside a buffer
mapEager, cached by fingerprintLazy, runs on each pass
Use it whenThe data fits on disk and you want exact resamplingThe corpus is too big, or still growing

The buffer in the shuffle explains the output. With buffer_size=100, the first IDs are all below about 100. A small buffer on sorted data barely mixes it, so check that your corpus is already shuffled on disk.

Checkpoint

  • The two map calls print the same fingerprint.
  • test_fingerprint_changes_with_each_transform_and_repeats_with_same_input, test_shuffle_uses_an_indices_mapping_not_a_copy and test_streaming_matches_table_order pass.
Step 06

Build a batch with a data collator

GoalWrite the function that turns a list of examples into one batch of tensors, and find a bug in the library default.

A dataset yields one example at a time, with its own length. A model needs a rectangle. The collator is the step between them. It has three jobs: pad to a common length, build the attention mask, and set every label that should not be trained on to -100.

    pad_token_id: int
    pad_to_multiple_of: int | None = None

    def __call__(self, features: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
        longest = max(len(f["input_ids"]) for f in features)
        if self.pad_to_multiple_of:
            m = self.pad_to_multiple_of
            longest = (longest + m - 1) // m * m

        batch = len(features)
        input_ids = torch.full((batch, longest), self.pad_token_id, dtype=torch.long)
        attention_mask = torch.zeros((batch, longest), dtype=torch.long)
        labels = torch.full((batch, longest), IGNORE_INDEX, dtype=torch.long)

        for i, f in enumerate(features):
            ids = torch.as_tensor(f["input_ids"], dtype=torch.long)
            n = ids.numel()
            input_ids[i, :n] = ids
            attention_mask[i, :n] = 1
            labels[i, :n] = torch.as_tensor(f["labels"], dtype=torch.long) if "labels" in f else ids

        return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels}
Listing 10The whole collator. Each tensor starts full of its padding value, and real values are written over the start of each row.

The three torch.full and zeros lines make rectangles of shape (B, N). The loop writes each example over the first n positions. Anything not written keeps its fill value, so padding is decided by position. Keep that in mind for the Break it below.

What a collator returns (B examples, longest length N)
TensorShapeFill valueMeaning
input_ids(B, N)pad_token_idTokens the model reads.
attention_mask(B, N)01 on real positions.
labels(B, N)-100Targets. The model shifts them by one inside the loss.
Batch shape
Padding cells
Real EOS trained on
Figure 6A padded batch, drawn from the same rules as CausalLMCollator. The token IDs are illustrative. Each row ends in EOS (ID 2). The first quarter of each row is a prompt, so its labels are -100. Turn on masking by value to see a real end-of-turn token lose its label.
$ .venv/bin/python c02-hf-stack/scripts/06_collator.py
pad token: '<|im_end|>' 2 | eos token: '<|im_end|>' 2
example lengths: [39, 40, 41]
input_ids       (3, 41)
attention_mask  (3, 41)
labels          (3, 41)

tail of each row (last 8 positions)
 row 0 input_ids [9531, 198, 33, 40, 2, 198, 2, 2]
 row 0 attention [1, 1, 1, 1, 1, 1, 0, 0]
 row 0 labels    [-100, -100, 33, 40, 2, -100, -100, -100]
 row 1 input_ids [520, 9531, 198, 34, 37, 2, 198, 2]
 row 1 attention [1, 1, 1, 1, 1, 1, 1, 0]
 row 1 labels    [-100, -100, -100, 34, 37, 2, -100, -100]
 row 2 input_ids [520, 9531, 198, 33, 32, 41, 2, 198]
 row 2 attention [1, 1, 1, 1, 1, 1, 1, 1]
 row 2 labels    [-100, -100, -100, 33, 32, 41, 2, -100]

The vision collator has the same three jobs, plus one. The processor already pads, so we only build labels. Labels are -100 on padding, on image tokens and on the prompt. Because prompt length depends on the image, we run the processor on the prompts alone and read their real lengths.

        tok = self.processor.tokenizer
        tok.padding_side = "right"  # training pads on the right; generation pads on the left
        images = [[f["image"]] for f in features]
        full_text = [self.processor.apply_chat_template(f["messages"]) for f in features]
        prompt_text = [
            self.processor.apply_chat_template(f["messages"][:-1], add_generation_prompt=True) for f in features
        ]

        batch = self.processor(text=full_text, images=images, padding=True, return_tensors="pt")
        prompts = self.processor(text=prompt_text, images=images, padding=True, return_tensors="pt")

        labels = batch["input_ids"].clone()
        labels[batch["attention_mask"] == 0] = IGNORE_INDEX
        image_token_id = tok.convert_tokens_to_ids("<image>")
        labels[batch["input_ids"] == image_token_id] = IGNORE_INDEX
        for i, prompt_len in enumerate(prompts["attention_mask"].sum(dim=1).tolist()):
            labels[i, :prompt_len] = IGNORE_INDEX
        batch["labels"] = labels
        return batch
Listing 11The vision collator. Padding comes from the processor; the labels are ours.
--- the collator for training: labels only on the assistant reply ---
  input_ids              (2, 1146)                  int64
  attention_mask         (2, 1146)                  int64
  pixel_values           (2, 17, 3, 512, 512)       float32
  pixel_attention_mask   (2, 17, 512, 512)          int64
  labels                 (2, 1146)                  int64
  row 0: 1146 positions, 6 labelled -> ' It says seven.<end_of_utterance>\n'
  row 1: 1146 positions, 4 labelled -> ' Two.<end_of_utterance>\n'

Checkpoint

  • All 9 real end-of-turn tokens keep their labels with our collator, and 0 keep them with the library's.
  • test_pad_equal_to_eos_keeps_real_eos_labels and test_library_collator_drops_real_eos_when_pad_is_eos pass.
Step 07

Match a raw loop to Trainer, number by number

GoalWrite a plain PyTorch loop whose loss and gradient norm equal Trainer's at every step, so that every hidden choice has to appear as a line of code.

This is the centre of the post. Trainer is a training loop that someone else wrote. To learn what it does, we write the same loop and require equal numbers. Any choice we miss shows up as a difference.

Theory inInside a training step

Start with the loss. Language models predict the next token, so logits and labels are offset by one. The loss is a sum over tokens, not a mean over a batch. The reason appears in a moment.

def summed_token_loss(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
    """Sum of next-token cross-entropy over every label that is not -100.

    logits: (B, N, V). labels: (B, N), aligned with input_ids; position t is predicted from tokens < t.
    """
    shift_logits = logits[:, :-1, :].float()  # (B, N-1, V): predictions for positions 1..N-1
    shift_labels = labels[:, 1:]  # (B, N-1)
    return F.cross_entropy(
        shift_logits.reshape(-1, shift_logits.size(-1)),
        shift_labels.reshape(-1),
        ignore_index=IGNORE_INDEX,
        reduction="sum",
    )


def count_label_tokens(labels: torch.Tensor) -> int:
    """Number of positions that contribute to the loss (after the one-token shift)."""
    return int((labels[:, 1:] != IGNORE_INDEX).sum())
Listing 12The loss. Position t is predicted from the tokens before it.

Then the optimizer. Trainer puts weight decay on matrices but not on biases or norm weights. If we decayed everything, the runs would drift apart.

def no_decay(name: str) -> bool:
    """Trainer's rule: biases and normalisation weights get no weight decay."""
    name = name.lower()
    return "bias" in name or "norm" in name


def make_optimizer(model: nn.Module, cfg: LoopConfig) -> torch.optim.Optimizer:
    params = [(n, p) for n, p in model.named_parameters() if p.requires_grad]
    groups = [
        {"params": [p for n, p in params if not no_decay(n)], "weight_decay": cfg.weight_decay},
        {"params": [p for n, p in params if no_decay(n)], "weight_decay": 0.0},
    ]
    return torch.optim.AdamW(groups, lr=cfg.learning_rate, betas=(0.9, 0.999), eps=1e-8)
Listing 13Two parameter groups. The theory is in the optimizer post.

Now the loop.

    for step in range(cfg.max_steps):
        micro_batches = []
        for _ in range(cfg.grad_accum):
            try:
                micro_batches.append(next(batches))
            except StopIteration:  # start the next epoch, as Trainer does
                batches = iter(loader)
                micro_batches.append(next(batches))

        # Normalise by the label tokens of the whole accumulated batch, so every token has equal weight
        # no matter which micro-batch it landed in.
        n_tokens = sum(count_label_tokens(b["labels"]) for b in micro_batches)
        step_loss = 0.0
        for batch in micro_batches:
            logits = model(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"]).logits
            if normalize == "tokens":
                loss = summed_token_loss(logits, batch["labels"]) / n_tokens
            else:
                loss = summed_token_loss(logits, batch["labels"]) / count_label_tokens(batch["labels"])
                loss = loss / cfg.grad_accum
            loss.backward()
            step_loss += loss.item()

        grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.max_grad_norm)
        history["lr"].append(scheduler.get_last_lr()[0])
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()
        history["loss"].append(step_loss)
        history["grad_norm"].append(float(grad_norm))
Listing 14One optimizer step of the raw loop. The inner loop runs one micro-batch at a time.

The highlighted lines hold the important decision. Gradient accumulation splits one step into several micro-batches. Each micro-batch has a different number of label tokens. n_tokens counts them across all micro-batches first, so every token has the same weight, whichever micro-batch it landed in.

Here is the same run through Trainer. The arguments are grouped by what they control, which is the useful way to read them. There are many more options, and you rarely need them.

def training_arguments(cfg: LoopConfig, output_dir: str, **overrides) -> TrainingArguments:
    """The `TrainingArguments` that match `LoopConfig`, grouped by what they control."""
    kwargs = dict(
        output_dir=output_dir,
        # batch
        per_device_train_batch_size=cfg.batch_size,
        gradient_accumulation_steps=cfg.grad_accum,
        max_steps=cfg.max_steps,
        train_sampling_strategy="sequential",  # the raw loop does not shuffle; Trainer shuffles by default
        # optimisation
        learning_rate=cfg.learning_rate,
        weight_decay=cfg.weight_decay,
        warmup_steps=cfg.warmup_steps,  # a float below 1 is a ratio; transformers 5 has no warmup_ratio
        lr_scheduler_type="linear",
        optim="adamw_torch",  # the default "adamw_torch_fused" differs in the last float bits
        max_grad_norm=cfg.max_grad_norm,
        # precision and device
        use_cpu=True,
        bf16=False,
        # logging, checkpointing, evaluation
        logging_steps=1,
        save_strategy="no",
        eval_strategy="no",
        report_to="none",
        disable_tqdm=True,
        seed=cfg.seed,
        dataloader_num_workers=0,
    )
    kwargs.update(overrides)
    return TrainingArguments(**kwargs)
Listing 15Trainer settings that match the raw loop. The two highlighted lines change a Trainer default.
TrainingArguments by function
FunctionArgumentsWhat to know
Batchper_device_train_batch_size, gradient_accumulation_stepsThe global batch is their product times the process count.
Optimisationlearning_rate, weight_decay, warmup_steps, lr_scheduler_type, optimIn transformers 5, a warmup_steps below 1 is read as a ratio of total steps. There is no separate warmup_ratio.
Precisionbf16, fp16Off here, since this run is CPU float32.
Checkpointingsave_strategy, save_stepsA checkpoint holds weights, optimizer, scheduler and RNG state. save_total_limit caps how many stay on disk.
Evaluationeval_strategy, eval_stepsOff here.
Logginglogging_steps, report_toEvery step here, so we can compare curves.
DistributedSet by the launchertorchrun or accelerate launch decide this. Step 9 shows it.
$ .venv/bin/python c02-hf-stack/scripts/07_raw_vs_trainer.py
step   raw loss    Trainer    |diff|  raw gnorm    Trainer        lr
   0  10.656849  10.656851   1.4e-06   9.756635   9.756635  0.000000
   1  10.768548  10.768546   1.4e-06   8.579594   8.579594  0.000500
   2  10.111899  10.111900   9.5e-07   6.220482   6.220482  0.001000
   5   9.198092   9.198092   0.0e+00   4.314135   4.314135  0.002500
  10   6.124119   6.124119   2.4e-07   4.550033   4.550033  0.002778
  20   2.213951   2.213951   0.0e+00   1.481659   1.481659  0.002222
  30   2.118742   2.118742   3.0e-07   7.609955   7.609955  0.001667
  40   1.937739   1.937739   6.0e-08   2.213500   2.213500  0.001111
  50   1.818630   1.818630   6.0e-08   2.004753   2.004753  0.000556
  59   1.704628   1.704628   1.2e-07   1.366487   1.366487  0.000056

max |loss diff| over 60 steps : 1.43e-06
max |grad norm diff|        : 0.00e+00
wall clock (AMD EPYC 7R13, 8 threads): raw 22.9 s, Trainer 14.9 s

Over 60 steps, the largest loss difference is 1.43e-06, which is float32 rounding when losses near 10 are summed. The gradient norms print as equal.

Raw loop
Trainer
|Difference|
Averaged micro-batches
Grad norm, Trainer
Grad norm, averaged

Figure 7Real loss per step, read from results/raw_vs_trainer.json. A from-scratch two-layer Llama with hidden size 128, batch 8, accumulation 2 and 60 steps. Use the frames to add one curve at a time. Move the pointer over the chart, or use the slider, to read exact values at any step.

After that the runs drift apart. The largest gaps come later, once each: 3.39 in gradient norm at step 30, and 0.116 in loss at step 38. The median gradient-norm gap over the 60 steps is 0.047. These numbers come from results/raw_vs_trainer.json. So a small error at every step turns into a different run. To catch it, compare the two runs step by step from step 0, in loss or in gradient norm. The final loss will not show it.

The table maps each raw line to the part of Trainer that owns it.

Raw PyTorch against Trainer
Raw PyTorchIn TrainerDefault you may want to check
DataLoaderBuilt inside, from your dataset and collatorShuffles the training data.
Forward and losscompute_lossPasses num_items_in_batch if the model accepts **kwargs.
Backwardtraining_stepHandles mixed precision and accumulation.
Optimizercreate_optimizeradamw_torch_fused, with no decay on biases and norms.
Schedulercreate_schedulerLinear decay, from lr_scheduler_type.
DDP (distributed data parallel)Accelerate as the backendSet by the launcher.
CheckpointsBuilt inResume restores RNG, so the data order continues.
EvaluationBuilt inOff unless eval_strategy is set.
LoggingCallbacksreport_to is "none" in transformers 5, so no tracker starts unless you ask.

Abstractions cost time, so we measure that too.

$ .venv/bin/python c02-hf-stack/benchmarks/bench_loops.py
4-layer Llama, hidden 128, batch 8, 100 steps, AMD EPYC 7R13, 8 threads
  raw loop       3.21 s total,   32.1 ms/step
  Trainer        3.50 s total,   35.0 ms/step
  Accelerate     2.95 s total,   29.5 ms/step

What the raw loop did not have

Equal numbers cover the training step. Trainer also gives you evaluation, checkpoints, callbacks and resume, which our raw loop never had. Callbacks are how each of these reports what it does. Logging, early stopping and tracker integrations all listen to the same events.

class EventLog(TrainerCallback):
    """Logging is a callback. So are early stopping and the W&B integration. They all see these events."""

    def __init__(self) -> None:
        self.events: list[str] = []

    def on_evaluate(self, args, state, control, metrics=None, **kwargs):
        self.events.append(f"step {state.global_step:>2}: evaluate, eval_loss {metrics['eval_loss']:.4f}")

    def on_save(self, args, state, control, **kwargs):
        self.events.append(f"step {state.global_step:>2}: save")
Listing 16A callback sees training events without changing the loop.
$ .venv/bin/python c02-hf-stack/scripts/07b_trainer_eval_checkpoint.py
--- what the callback saw ---
step 10: evaluate, eval_loss 6.2735
step 10: save
step 20: evaluate, eval_loss 6.2984
step 20: save
step 30: evaluate, eval_loss 6.3036
step 30: save

--- save_total_limit=2 keeps the newest two checkpoints ---
['checkpoint-20', 'checkpoint-30']
inside checkpoint-20: ['config.json', 'generation_config.json', 'model.safetensors', 'optimizer.pt', 'rng_state.pth', 'scheduler.pt', 'trainer_state.json', 'training_args.bin']
trainer_state.json: global_step 20 | log entries 22

--- resume: a new Trainer and a new model object, starting from checkpoint-20 ---
max |weight difference| against the uninterrupted run: 0.00e+00

A checkpoint holds more than weights. optimizer.pt, scheduler.pt and rng_state.pth are what make resume exact: the run restarted from step 20 in a new Trainer ended with the same weights as a run with no stop. To match that with the raw loop, you would have to save and restore all of them yourself.

Checkpoint

  • The raw and Trainer curves agree to about 1e-6 at every step.
  • You can name the five choices that make them agree: data order, token-level normalisation, decay groups, schedule and clipping.
Step 08

Change one thing by subclassing Trainer

GoalOverride compute_loss to add a loss term and new metrics, and prove that the override changes nothing when the new term is off.

Often you want the whole of Trainer except one thing. A subclass is the right tool for that. As our example we add z-loss, a small penalty on the squared log of the softmax normaliser. PaLM used it with a weight of 10-4 to stop logits drifting large.

class ZLossTrainer(Trainer):
    # Our loss is divided by `num_items_in_batch` (all label tokens in the accumulated batch),
    # so Trainer must not divide it again by gradient_accumulation_steps.
    loss_is_scaled_for_ga = True

    def __init__(self, *args, z_loss_weight: float = 0.0, **kwargs):
        super().__init__(*args, **kwargs)
        self.z_loss_weight = z_loss_weight
        self._metrics: dict[str, list[float]] = defaultdict(list)

    def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
        labels = inputs.pop("labels")  # (B, N); keep it away from the model so it does not compute a loss
        outputs = model(**inputs)
        logits = outputs.logits[:, :-1, :].float()  # (B, N-1, V)
        targets = labels[:, 1:]  # (B, N-1)
        valid = targets != IGNORE_INDEX  # (B, N-1)

        if num_items_in_batch is None:  # model without **kwargs: fall back to this micro-batch only
            num_items_in_batch = valid.sum()

        ce_sum = F.cross_entropy(
            logits.reshape(-1, logits.size(-1)), targets.reshape(-1), ignore_index=IGNORE_INDEX, reduction="sum"
        )
        log_z = torch.logsumexp(logits, dim=-1)  # (B, N-1)
        z_sum = (log_z.pow(2) * valid).sum()
        loss = (ce_sum + self.z_loss_weight * z_sum) / num_items_in_batch

        with torch.no_grad():
            n_valid = valid.sum().clamp(min=1)
            correct = ((logits.argmax(-1) == targets) & valid).sum()
            self._metrics["token_accuracy"].append((correct / n_valid).item())
            self._metrics["mean_log_z"].append(((log_z * valid).sum() / n_valid).item())

        return (loss, outputs) if return_outputs else loss
Listing 17The override. The first highlighted line says the loss is already scaled.

We pop the labels so the model does not compute a loss of its own. Then we compute the summed cross-entropy and the z term, and divide both by num_items_in_batch. Trainer computes that number across the whole accumulated batch, which is the same n_tokens as our raw loop.

The first highlighted line makes one choice explicit. Trainer divides the loss by gradient_accumulation_steps unless it believes the loss is already scaled. When the flag is unset, it decides from the model: a model whose forward accepts **kwargs is assumed to scale its own loss. Ours does, so removing the line changes nothing here. We checked: the gap to the default stays at 9.54e-07. Setting the flag to False makes Trainer divide again, and the first logged loss halves, from 6.24 to 3.12. The documentation asks a subclass that computes its own loss to set the flag, so we set it.

$ .venv/bin/python c02-hf-stack/scripts/08_custom_trainer.py
logged keys: ['grad_norm', 'loss', 'lr', 'mean_log_z', 'token_accuracy']
max |loss diff|, default vs subclass with z=0: 9.54e-07

step   z=0 loss  accuracy  mean logZ |  z=1e-3 loss  mean logZ
   0     6.2409    0.0000      6.256 |       6.2801      6.256
   9     5.9257    0.0221      6.244 |       5.9644      6.244
  19     5.5949    0.0629      6.217 |       5.6341      6.216
  29     5.4111    0.0548      6.216 |       5.4507      6.214
  39     5.3098    0.1048      6.217 |       5.3489      6.214

With the weight at zero, the subclass equals the default to 9.54e-07. That is the test that lets us trust the override. Only then do we turn the new term on.

How far to customise

Four levels of control. Move down only when the level above cannot do the job.
LevelYou writeReach for it when
TrainerArguments and a collatorStandard supervised training.
Subclass TrainerOne or two methodsA new loss or metric. The loop stays standard.
AccelerateThe whole loopThe shape of the loop changes, for example several models or optimizers per step.
Raw PyTorchEverything, including process setupYou need exact control or no dependencies, or you are learning.

Checkpoint

  • test_custom_trainer_with_zero_weight_equals_default and test_z_loss_changes_the_run pass.
  • The logged keys include token_accuracy and mean_log_z.
Step 09

Run the raw loop on several processes with Accelerate

GoalKeep our own loop and hand over only devices and processes. Then check that two processes equal one.

The two libraries are easy to mix up, so state the difference plainly. Trainer is a training-loop abstraction: it owns the loop. Accelerate is an execution abstraction: you keep the loop, and it decides where the tensors live. Trainer itself uses Accelerate underneath.

Theory inThe parallelism playbook
    # The scheduler is left unprepared on purpose: a prepared scheduler steps once per process per
    # optimizer step, which changes the schedule when the process count changes.
    model, optimizer, loader = accelerator.prepare(model, optimizer, loader)

    history: dict[str, list[float]] = {"loss": [], "grad_norm": [], "lr": []}
    model.train()
    batches = iter(loader)
    for step in range(cfg.max_steps):
        micro_batches = []
        for _ in range(cfg.grad_accum):
            try:
                micro_batches.append(next(batches))
            except StopIteration:
                batches = iter(loader)
                micro_batches.append(next(batches))

        # Count label tokens on every process and sum them, so each token in the global batch has equal
        # weight. DDP averages gradients over processes, hence the factor num_processes.
        local_tokens = torch.tensor(sum(count_label_tokens(b["labels"]) for b in micro_batches))
        n_tokens = accelerator.reduce(local_tokens.to(accelerator.device), reduction="sum").item()
        scale = accelerator.num_processes / n_tokens

        step_loss = torch.zeros((), device=accelerator.device)
        for i, batch in enumerate(micro_batches):
            last = i == len(micro_batches) - 1
            # Only the last micro-batch triggers the all-reduce of gradients.
            with accelerator.no_sync(model) if not last else nullcontext():
                logits = model(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"]).logits
                loss = summed_token_loss(logits, batch["labels"]) * scale
                accelerator.backward(loss)
            step_loss += loss.detach() / accelerator.num_processes

        grad_norm = accelerator.clip_grad_norm_(model.parameters(), cfg.max_grad_norm)
        history["lr"].append(scheduler.get_last_lr()[0])
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()
        history["loss"].append(accelerator.reduce(step_loss, reduction="sum").item())
        history["grad_norm"].append(float(grad_norm))
Listing 18The raw loop again. The highlighted lines are the main changes.

Walk through the changes. prepare moves the model to the device, wraps it in DDP when there are several processes, and gives each process its own shard of the data.

Token counting now needs a network call. Each process only sees its own tokens, so reduce sums the counts across processes. Then comes a factor that looks odd: scale = num_processes / n_tokens. DDP averages gradients across processes, and we want a sum over tokens. Multiplying by the process count cancels that average.

no_sync skips the gradient all-reduce on every micro-batch but the last. An all-reduce sums a tensor across processes and gives every process the result. The gradients stay in local memory until the final one, which saves a round of communication.

Figure 8One optimizer step with 2 processes, batch 4 and accumulation 2. The two processes together see the same 16 examples as one process with batch 8. Both start and finish the step with identical weights.
$ .venv/bin/python c02-hf-stack/scripts/09_accelerate.py
$ .venv/bin/python -m torch.distributed.run --nproc_per_node 2 c02-hf-stack/scripts/09_accelerate.py --ddp
[rank 0] processes=1 backend=None device=cpu
Accelerate vs raw loop, 1 process: max |loss diff| 4.77e-07
first losses: [6.24093, 6.27106, 6.26745, 6.28221]
[rank 1] processes=2 backend=gloo device=cpu:0
[rank 0] processes=2 backend=gloo device=cpu:0
2 processes x batch 4 vs 1 process x batch 8: max |loss diff| 9.54e-07, max |grad norm diff| 5.96e-08

Checkpoint

  • Rank 0 and rank 1 both report processes=2.
  • test_accelerate_equals_raw passes, and test_two_processes_equal_one passes under the slow marker.
Step 10

Read model outputs, then write generate() as a loop

GoalLearn the shape of every field a forward pass returns, and reproduce model.generate token for token with a plain loop.

A Transformers forward pass returns a ModelOutput, a dataclass that also behaves like a dict. Empty fields are skipped when you iterate. We ask for everything and print its shape, using one small helper.

def shape_of(value: Any) -> str:
    """A short description of a tensor, a tuple of tensors, or a cache."""
    if isinstance(value, torch.Tensor):
        return f"{tuple(value.shape)} {str(value.dtype).replace('torch.', '')}"
    if isinstance(value, Cache):
        layer = value.layers[0]
        return (
            f"{type(value).__name__}: {len(value.layers)} layers, "
            f"keys {tuple(layer.keys.shape)}, values {tuple(layer.values.shape)}"
        )
    if isinstance(value, (tuple, list)) and value and isinstance(value[0], torch.Tensor):
        return f"tuple of {len(value)} × {tuple(value[0].shape)}"
    return type(value).__name__


def describe_outputs(outputs) -> dict[str, str]:
    """Every non-empty field of a ModelOutput and its shape."""
    return {key: shape_of(value) for key, value in outputs.items() if value is not None}
Listing 19Print any output field. A KV cache gets its own branch, because it holds tensors per layer.
$ .venv/bin/python c02-hf-stack/scripts/10_outputs_and_generate.py
input_ids [[504, 3575, 282, 4649, 314], [0, 0, 39844, 1010, 14735]]
attention [[1, 1, 1, 1, 1], [0, 0, 1, 1, 1]]

CausalLMOutputWithPast
  loss             () float32
  logits           (2, 5, 49152) float32
  past_key_values  DynamicCache: 30 layers, keys (2, 3, 5, 64), values (2, 3, 5, 64)
  hidden_states    tuple of 31 × (2, 5, 576)
  attentions       tuple of 30 × (2, 9, 5, 5)

hidden_states has num_hidden_layers + 1 entries: 31 = 30 + 1
attentions row sums to 1: 1.0000001192092896
cached key shape: (B, num_key_value_heads, T, head_dim) = (2, 3, 5, 64)
SmolLM2-135M outputs (B = 2, T = 5, V = 49152, D = 576, 30 layers)
FieldShapeMeaning
loss()Only when you pass labels. The shift by one happens inside.
logits(B, T, V)Next-token scores at every position.
hidden_states31 × (B, T, D)The embedding plus one per layer.
attentions30 × (B, 9, T, T)Weights per head. Needs attn_implementation="eager", because the SDPA kernel (PyTorch's fused scaled dot-product attention) never builds them.
past_key_values30 layers of (B, 3, T, 64)Keys and values, with 3 key-value heads, not 9.

The last row shows grouped-query attention from the config: 9 query heads share 3 key-value heads. The cache stores only key-value heads, so its size follows num_key_value_heads. C3 builds this from scratch.

generate() is a loop

Generating has five parts: a forward pass, a KV cache, logits processors, a sampler and a stopping rule. We write them in order. The first version is the simplest: run the whole sequence again at each step.

def greedy_no_cache(model, input_ids: torch.Tensor, max_new_tokens: int) -> torch.Tensor:
    """Reference loop: re-run the whole sequence every step. Cost per step grows with length. (B, T) → (B, T+K)."""
    for _ in range(max_new_tokens):
        logits = model(input_ids=input_ids, use_cache=False).logits  # (B, T, V)
        next_token = logits[:, -1, :].argmax(dim=-1, keepdim=True)  # (B, 1)
        input_ids = torch.cat([input_ids, next_token], dim=-1)
    return input_ids
Listing 20The reference. Slow, and clearly correct.

The cost per step grows with the length, since every step reprocesses the history. A KV cache removes that repeated work. The first forward pass, called prefill, runs the whole prompt and fills the cache. Each later pass, called decode, sends only the newest token.

    cache = DynamicCache(config=model.config)
    finished = torch.zeros(input_ids.size(0), dtype=torch.bool, device=input_ids.device)
    step_input = input_ids  # prefill: the whole prompt

    for _ in range(max_new_tokens):
        position_ids = positions_from_mask(attention_mask)[:, -step_input.size(1) :]
        out = model(
            input_ids=step_input,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=cache,
            use_cache=True,
        )
        logits = out.logits[:, -1, :].float()  # (B, V): only the last position predicts the next token
        if do_sample:
            probs = process_logits(logits, temperature, top_k, top_p).softmax(-1)
            next_token = torch.multinomial(probs, 1, generator=generator).squeeze(-1)  # (B,)
        else:
            next_token = logits.argmax(-1)
        next_token = torch.where(finished, torch.full_like(next_token, pad_token_id), next_token)

        input_ids = torch.cat([input_ids, next_token[:, None]], dim=-1)
        attention_mask = torch.cat([attention_mask, torch.ones_like(next_token[:, None])], dim=-1)
        step_input = next_token[:, None]  # decode: only the new token goes through the model

        if eos_token_id is not None:
            finished |= next_token == eos_token_id
            if finished.all():
                break
    return input_ids
Listing 21The cached loop. Only the last position predicts the next token.

positions_from_mask needs a word. With left padding, a position ID cannot be the column number, because the real tokens would start at 2. So we count real tokens instead: the mask [0, 0, 1, 1, 1] gives positions [0, 0, 0, 1, 2].

The processors are small. They reshape the last-position logits before sampling. Their theory is in the sampling post, so we only check that ours equal the library's TemperatureLogitsWarper, TopKLogitsWarper and TopPLogitsWarper.

def process_logits(
    logits: torch.Tensor, temperature: float = 1.0, top_k: int = 0, top_p: float = 1.0
) -> torch.Tensor:
    """Apply temperature, then top-k, then top-p to last-position logits (B, V). Removed entries become -inf."""
    logits = logits / temperature
    if top_k > 0:
        kth = torch.topk(logits, min(top_k, logits.size(-1)), dim=-1).values[..., -1:]  # (B, 1)
        logits = logits.masked_fill(logits < kth, float("-inf"))
    if top_p < 1.0:
        sorted_logits, order = torch.sort(logits, descending=True, dim=-1)
        cumulative = sorted_logits.softmax(-1).cumsum(-1)
        # Drop a token if the tokens ranked above it already cover top_p of the mass. Keep at least one.
        drop_sorted = (cumulative - sorted_logits.softmax(-1)) >= top_p
        drop_sorted[..., 0] = False
        drop = drop_sorted.scatter(-1, order, drop_sorted)
        logits = logits.masked_fill(drop, float("-inf"))
    return logits
Listing 22Temperature, then top-k, then top-p, on the last-position logits.
Theory inChoosing the next token

Figure 9The real run on SmolLM2-135M. The tokens are the real prompt and the first greedy tokens. The shapes come from the output below. After prefill the input is always one token, and the cache grows by one position per step.
--- the KV cache grows by one position per step ---
step 0: input (2, 5), logits (2, 5, 49152), cache keys (2, 3, 5, 64)
step 1: input (2, 1), logits (2, 1, 49152), cache keys (2, 3, 6, 64)
step 2: input (2, 1), logits (2, 1, 49152), cache keys (2, 3, 7, 64)

--- our loop against model.generate ---
greedy, tokens identical: True
[' the capital of the country.\n\nThe capital of France', ' algorithm.\n\nThe gradient descent algorithm is a simple yet']
sampling with the same seed, tokens identical: True

Our loop matches model.generate token for token. Sampling matches as well once both start from the same seed, because torch.multinomial draws from the same random stream. That also confirms that generate uses the processors in the same order as ours.

$ .venv/bin/python c02-hf-stack/benchmarks/bench_generate.py
SmolLM2-135M, prompt 6 tokens, 64 new tokens, AMD EPYC 7R13, 8 threads, float32
  no cache (recompute history)      5.39 s     11.9 tokens/s
  our loop with KV cache            3.79 s     16.9 tokens/s
  model.generate                    4.47 s     14.3 tokens/s
  all three produced the same tokens: True

All three produced the same tokens. The cached loop took 3.79 s and the no-cache loop took 5.39 s. A cache should win, because it does not recompute the history, and the gap should grow with length, because the no-cache cost per step keeps growing. We did not measure longer runs, and this single run on a busy machine does not pin down the ratio.

Our loop also finished ahead of model.generate, at 16.9 against 14.3 tokens/s. We draw no conclusion from that order. There are no repeats, so it may be noise.

We ran the same benchmark once on one NVIDIA H100 80GB HBM3 (torch 2.15.0, CUDA 13.2).

$ .venv/bin/python c02-hf-stack/benchmarks/bench_generate.py --device cuda
SmolLM2-135M, prompt 6 tokens, 64 new tokens, NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, float32
  no cache (recompute history)      2.38 s     26.9 tokens/s
  our loop with KV cache            2.16 s     29.7 tokens/s
  model.generate                    3.16 s     20.3 tokens/s
  all three produced the same tokens: True

On the H100 the tokens were again identical. The cache helped far less than on the CPU: 29.7 against 26.9 tokens/s. model.generate was the slowest of the three, at 20.3 tokens/s. With batch 1 and a 135 M model, each new token is one small forward pass, so the time likely goes to launching kernels and to Python, not to arithmetic. We did not profile it. This is one run, and a larger batch or model would change the picture.

Checkpoint

  • greedy, tokens identical: True and sampling with the same seed, tokens identical: True.
  • test_cache_equals_no_cache, test_greedy_equals_generate_with_left_padding, test_sampling_equals_generate_with_same_seed and test_processors_equal_library pass.
Step 11

Wrap a model with PEFT

GoalAdd LoRA adapters, see exactly what became trainable, check PEFT's arithmetic by hand, and merge the result.

PEFT (parameter-efficient fine-tuning) edits a model in place. It replaces chosen linear layers with wrappers that hold a small trainable update, and it freezes everything else. Why a low-rank update is enough is the subject of the theory post.

Theory inHow LoRA changes a model without rewriting it
def add_lora(model: nn.Module, r: int = 8, alpha: int = 16, targets: list[str] | None = None) -> PeftModel:
    """Freeze `model` and insert rank-`r` adapters into every module whose name ends in one of `targets`."""
    config = LoraConfig(
        r=r,
        lora_alpha=alpha,
        lora_dropout=0.0,
        target_modules=targets or ATTENTION_PROJECTIONS,
        task_type="CAUSAL_LM",
    )
    return get_peft_model(model, config)


def lora_shapes(peft_model: PeftModel) -> list[tuple[str, tuple[int, ...]]]:
    """Name and shape of every trainable tensor. These are the only tensors the optimizer sees."""
    return [(n, tuple(p.shape)) for n, p in peft_model.named_parameters() if p.requires_grad]


def manual_lora_forward(layer: nn.Module, x: torch.Tensor, adapter: str = "default") -> torch.Tensor:
    """Recompute a PEFT `lora.Linear` output from its parts. x: (..., d_in) → (..., d_out)."""
    base = layer.base_layer(x)  # W x (+ bias)
    A = layer.lora_A[adapter].weight  # (r, d_in)
    B = layer.lora_B[adapter].weight  # (d_out, r)
    scale = layer.scaling[adapter]  # alpha / r
    return base + scale * (x @ A.T @ B.T)
Listing 23Wrap the model, list what trains, and recompute a wrapped layer by hand.

target_modules matches module names by suffix. That is all PEFT needs to know about your model. manual_lora_forward is the check. It recomputes a wrapped layer from its parts: the frozen output, plus alpha / r times the two small matrices.

Trainable parameters
Share of the model
Adapter weights, float32

Figure 10LoRA on q_proj of SmolLM2-135M. W is frozen, A starts random, and B starts at zero, so a fresh adapter changes nothing. The rank slider shows the count over all four attention projections in all 30 layers, computed from the shapes. Those shapes differ: k_proj and v_proj have only 192 outputs. At r = 8 the count is 921,600, the same as the script prints.
$ .venv/bin/python c02-hf-stack/scripts/11_lora.py --steps 150 --seed 0
device cpu (AMD EPYC 7R13, 8 threads), seed 0
trainable 921,600 of 135,436,608 (0.68%)
  base_model.model.model.layers.0.self_attn.q_proj.lora_A.default.weight         (8, 576)
  base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight         (576, 8)
  base_model.model.model.layers.0.self_attn.k_proj.lora_A.default.weight         (8, 576)
  base_model.model.model.layers.0.self_attn.k_proj.lora_B.default.weight         (192, 8)
  ... 240 trainable tensors in total

wrapped layer: peft.tuners.lora.layer.Linear
lora_B starts at zero: True
|peft - by hand| max: 0.00e+00, scale = 2.0

trained 150 steps in 180 s (1.20 s/step)
loss: [(10, 2.52), (20, 1.126), (30, 0.804), (40, 0.627), (50, 0.65), (60, 0.543), (70, 0.487), (80, 0.478), (90, 0.396), (100, 0.448), (110, 0.408), (120, 0.404), (130, 0.347), (140, 0.288), (150, 0.295)]

exact-match accuracy on 182 held-out sums: before 0.000, after 0.593
  What is 86 + 11?   answer   97 | before 'To add 86 and'                    | after '97'
  What is 80 + 11?   answer   91 | before 'To add 80 and'                    | after '91'
  What is 84 - 74?   answer   10 | before 'To find the difference between '  | after '10'
  What is 93 + 76?   answer  169 | before 'To add 93 and'                    | after '169'
adapter sha256: acdd4ec449a3e83c

adapter checkpoint:
  README.md                           5,224
  adapter_config.json                 1,140
  adapter_model.safetensors       3,717,656
full model in float32 would be 541,746,432 bytes; the adapter is 0.69% of that
adapter_config target_modules: ['k_proj', 'o_proj', 'q_proj', 'v_proj']
|logits after reload - before| max: 0.00e+00

merge_and_unload: type LlamaForCausalLM, |logits merged - adapter| max: 1.03e-04
q_proj after merge: Linear

Read the output from the top. Only 0.68% of the model is trainable, and 240 tensors carry it: 30 layers, 4 projections, and 2 matrices each. PEFT and our hand-written formula agree exactly at 0.00e+00. With seed 0, training took 180 s for 150 steps on the CPU, at 1.20 s per step. The loss fell from 2.52 to 0.295.

One run could be luck, so a second script repeats it for seeds 0, 1 and 2. The held-out sums stay the same in every run. Only the adapter's starting values and the batch order change.

$ .venv/bin/python c02-hf-stack/scripts/11b_lora_seeds.py --seeds 0 1 2
182 held-out sums, 150 steps, exact match within 6 tokens
seed  before   after  final loss  merge gap  s/step  adapter sha256
   0   0.000   0.593       0.295   1.03e-04    1.20  acdd4ec449a3e83c
   1   0.000   0.560       0.326   8.39e-05    1.30  8adf6e4a726343eb
   2   0.000   0.566       0.267   7.82e-05    1.08  bb6e30d53b3971e2

after: min 0.560, mean 0.573, max 0.593
seed 0 run a second time, same accuracy, loss curve, merge gap and adapter hash: True

Exact-match accuracy on 182 held-out sums went from 0.000 to between 0.560 and 0.593, with a mean of 0.573. None of these sums appear in training. Three seeds give a range, not a confidence interval. A repeat of seed 0 gave the same result, down to the adapter's hash, so a fixed seed is reproducible on this machine.

Do not read the whole jump as arithmetic the adapter learned. The 0.000 is mostly a format effect. The base model opens with To add 86 and, and the script cuts each reply at 6 tokens. So the base model fails even on sums it might get right with more room. We did not measure that. After training, the model replies with a bare number.

So a small adapter can change what a model does. It does not make a good calculator: 41% to 44% of the answers are still wrong after this short run.

We repeated the three seeds once on one NVIDIA H100 80GB HBM3 (torch 2.15.0, CUDA 13.2).

$ .venv/bin/python c02-hf-stack/scripts/11b_lora_seeds.py --device cuda --prefix gpu_
182 held-out sums, 150 steps, exact match within 6 tokens
seed  before   after  final loss  merge gap  s/step  adapter sha256
   0   0.000   0.593       0.295   8.20e-05    0.22  31b1e7195ad46470
   1   0.000   0.560       0.326   5.91e-05    0.29  db852f0579c19c36
   2   0.000   0.566       0.267   4.72e-05    0.28  f528e9dc7d1a978e

after: min 0.560, mean 0.573, max 0.593
seed 0 run a second time, same accuracy, loss curve, merge gap and adapter hash: True

On the H100 a step took 0.22 to 0.29 s, against 1.08 to 1.30 s on the CPU. Accuracy and final loss match the CPU runs to the printed digits for each seed. The adapter hashes differ, so the weights agree only up to float rounding.

The adapter file ties to the shapes too: 921,600 × 4 = 3,686,400 bytes of weights, plus a header, gives the 3,717,656 bytes on disk. That is 0.69% of the full model in float32.

One wrapped q_proj on SmolLM2-135M (r = 8, D = 576)
TensorShapeState
base_layer.weight (W)(576, 576)Frozen
lora_A.default.weight (A)(8, 576)Trainable, random at the start
lora_B.default.weight (B)(576, 8)Trainable, zero at the start
scalingalpha / r = 2.0A constant

An adapter saves only the small matrices. To load it you need the base model too, which is why PeftModel.from_pretrained takes two arguments. merge_and_unload folds the update into W and removes the wrappers. You get a plain LlamaForCausalLM back, with no PEFT dependency at inference.

The merge is not exact. On the CPU, logits moved by up to 1.03e-04 for seed 0, and by 7.82e-05 to 1.03e-04 over the three seeds, so about 1e-4. On the H100 the gaps were 4.72e-05 to 8.20e-05. The likely cause is rounding: the merged path rounds W + 2 B A to float32 once, where the adapter path rounds two terms separately. We did not test that explanation.

Checkpoint

  • Every trainable name contains lora_.
  • The adapter reloads with no change in logits. Merging moves them by about 1e-4 on SmolLM2 (CPU), and by up to 8.20e-05 on the H100.
Step 12

Learn the data contract of each TRL trainer

GoalSee that TRL trainers are Trainer subclasses told apart by the shape of their data, and run each one for three steps.

TRL (Transformer Reinforcement Learning) holds post-training losses: SFT (supervised fine-tuning), DPO (direct preference optimization), reward models and GRPO (group relative policy optimization). The most useful thing to learn first is the dataset format, because each trainer expects a different one. Our arithmetic rows convert to all of them.

def to_messages(row: dict) -> dict:
    """Conversational SFT format: one `messages` list per example."""
    return {
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": question(row)},
            {"role": "assistant", "content": str(row["answer"])},
        ]
    }


def to_preference(row: dict) -> dict:
    """Conversational preference format: a shared prompt, a chosen reply and a rejected reply."""
    wrong = row["answer"] + random.Random(row["id"]).choice([-10, -2, -1, 1, 2, 10])
    return {
        "prompt": [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": question(row)}],
        "chosen": [{"role": "assistant", "content": str(row["answer"])}],
        "rejected": [{"role": "assistant", "content": str(wrong)}],
    }


def to_prompt_only(row: dict) -> dict:
    """RL format: only the prompt. The trainer generates completions; `answer` feeds the reward function."""
    return {
        "prompt": [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": question(row)}],
        "answer": str(row["answer"]),
Listing 24One row, three formats.
$ .venv/bin/python c02-hf-stack/scripts/12_trl.py
timings below: AMD EPYC 7R13, 8 threads
--- formats ---
SFT        {"messages": [{"role": "system", "content": "You are a careful calculator. Answer with the result only."}, {"role": "user", "content": "What is 49 - 97?"}, {"role": "assistant", "content": "-48"}]}
preference {"prompt": [{"role": "system", "content": "You are a careful calculator. Answer with the result only."}, {"role": "user", "content": "What is 49 - 97?"}], "chosen": [{"role": "assistant", "content": "-48"}], "rejected": [{"role": "assistant", "content": "-47"}]}
RL         {"prompt": [{"role": "system", "content": "You are a careful calculator. Answer with the result only."}, {"role": "user", "content": "What is 49 - 97?"}], "answer": "-48"}

--- SFTTrainer, assistant_only_loss=True ---
columns after preparation: ['messages', 'input_ids', 'labels']
batch: {'input_ids': (2, 41), 'labels': (2, 41), 'attention_mask': (2, 41)}
TRL labels == our assistant_labels_by_prefix: True
loss per step [10.564, 10.819, 10.787], 1.9 s

--- DPOTrainer ---
columns after preparation: ['prompt', 'chosen', 'rejected', 'prompt_ids', 'chosen_ids', 'rejected_ids']
loss per step [0.693, 0.693, 0.693], 2.4 s
ln 2 = 0.693 (the DPO loss at step 0, when model == reference)

--- RewardTrainer: same preference data, but the model outputs one score per sequence ---
columns after preparation: ['prompt', 'chosen', 'rejected', 'chosen_ids', 'rejected_ids']
batch (chosen rows, then rejected rows): {'input_ids': (4, 41), 'attention_mask': (4, 41)}
loss per step [0.69, 0.692, 0.692], 0.9 s

--- GRPOTrainer ---
columns: ['prompt', 'answer']
loss per step [0.0, 0.0, 0.0], 0.9 s
{'reward': 0.0, 'reward_std': 0.0, 'frac_reward_zero_std': 1.0, 'grad_norm': 0.0}
reward test: [1.0, 0.0]
TRL trainers in this tutorial
TrainerDataset columnsWhat the loss needsTheory
SFTTrainermessagesAssistant tokens as labelsSFT
DPOTrainerprompt, chosen, rejectedA second frozen reference modelPreferences
RewardTrainerchosen, rejected, prompt optionalA model with one score per sequencePreferences
GRPOTrainerprompt, plus columns for the rewardA reward function and online generationRL

The SFT run closes a loop with step 3. assistant_only_loss=True uses the {% generation %} markers we met there, and TRL labels == our assistant_labels_by_prefix: True confirms that the library and our function mark the same tokens.

The DPO number is a check we can do in our head. At step 0 the model equals the reference, so its preference margin is zero, and the loss is -log(sigmoid(0)) = ln 2 = 0.693. The run prints exactly that. RewardTrainer starts close to the same value, 0.69, because a random scorer gives chosen and rejected almost equal scores. It needs a different model class, LlamaForSequenceClassification with one label, and its batch stacks the chosen rows and then the rejected rows. Both losses stay near ln 2 over the three steps, so neither run shows learning.

Checkpoint

  • The DPO loss starts at 0.693.
  • test_sft_trainer_labels_equal_ours and test_reward_is_exact pass.
Step 13

Read what save_pretrained writes

GoalList every file in a checkpoint, parse a safetensors file by hand, and see how shards and the index work.

The Hub is a set of Git repositories that hold files. A model repo holds the same kinds of file that save_pretrained writes on your disk. So we save a model and look inside.

$ .venv/bin/python c02-hf-stack/scripts/13_hub_and_safetensors.py
--- save_pretrained + tokenizer.save_pretrained ---
  chat_template.jinja                   368
  config.json                           905
  generation_config.json                132
  model.safetensors             538,090,408
  tokenizer.json                  3,522,871
  tokenizer_config.json                 453

generation_config.json: {'_from_model_config': True, 'bos_token_id': 1, 'eos_token_id': 2, 'pad_token_id': 2, 'transformers_version': '5.22.2'}
What each file is for
FileHoldsRead by
config.jsonArchitecture and model_typeAutoConfig
generation_config.jsonDefault generate settings and token IDsgenerate
model.safetensorsThe weightsfrom_pretrained
tokenizer.jsonVocabulary and merge rulesAutoTokenizer
tokenizer_config.jsonSpecial tokens and class nameAutoTokenizer
chat_template.jinjaThe template from step 3apply_chat_template
README.mdThe model card. Not written by save_pretrained; add it before you publish.People and the Hub page

A safetensors file has a simple layout: 8 bytes for the header length, a JSON header, then raw tensor bytes. Nothing is pickled, so loading never runs code. Because the format is this simple, we can read it with the standard library.

def read_safetensors_header(path: str | Path) -> dict:
    """Parse the JSON header by hand, without the safetensors library."""
    with open(path, "rb") as f:
        (header_len,) = struct.unpack("<Q", f.read(8))
        header = json.loads(f.read(header_len))
    return header


def read_tensor_by_hand(path: str | Path, name: str) -> torch.Tensor:
    """Read one tensor using only the header offsets: seek, read bytes, reinterpret."""
    dtypes = {"F32": torch.float32, "F16": torch.float16, "BF16": torch.bfloat16, "I64": torch.int64}
    header = read_safetensors_header(path)
    entry = header[name]
    start, stop = entry["data_offsets"]  # relative to the end of the header
    with open(path, "rb") as f:
        (header_len,) = struct.unpack("<Q", f.read(8))
        f.seek(8 + header_len + start)
        raw = bytearray(f.read(stop - start))
    return torch.frombuffer(raw, dtype=dtypes[entry["dtype"]]).reshape(entry["shape"])
Listing 25Parse the header, then seek straight to one tensor. No other tensor is read.
--- inside model.safetensors, parsed by hand ---
first 8 bytes as little-endian u64 = header length: 30368
metadata: {'format': 'pt'}
tensors : 272
  model.embed_tokens.weight                      {'dtype': 'F32', 'shape': [49152, 576], 'data_offsets': [0, 113246208]}
  model.layers.0.input_layernorm.weight          {'dtype': 'F32', 'shape': [576], 'data_offsets': [113246208, 113248512]}
  model.layers.0.mlp.down_proj.weight            {'dtype': 'F32', 'shape': [576, 1536], 'data_offsets': [113248512, 116787456]}
lm_head.weight in the file: False (tied, so saved once)
tensor read with seek() equals the model's: True

Figure 11The real file. The strip is not to scale: the header is far smaller than the weights. Header length, offsets, shard sizes and tensor counts are from the output.

The sizes add up exactly: 8 + 30,368 + 538,060,032 = 538,090,408 bytes, the file size above. And 538,060,032 / 4 = 134,515,008, the parameter count from step 1. Each number ties to the others, so nothing is hidden in this file.

Large models are split. max_shard_size writes several files and one index, which maps each tensor name to its file.

--- sharded: max_shard_size='200MB' ---
  config.json                                       905
  generation_config.json                            132
  model-00001-of-00003.safetensors          198,217,056
  model-00002-of-00003.safetensors          198,259,352
  model-00003-of-00003.safetensors          141,613,808
  model.safetensors.index.json                   22,439
index metadata: {'total_parameters': 134515008, 'total_size': 538060032}
weight_map, first and last: ('model.embed_tokens.weight', 'model-00001-of-00003.safetensors') ('model.norm.weight', 'model-00003-of-00003.safetensors')
tensors per shard: {'model-00001-of-00003.safetensors': 56, 'model-00002-of-00003.safetensors': 126, 'model-00003-of-00003.safetensors': 90}
reload from shards in 0.35 s; identical weights: True

--- only the config: no weights touched ---
config in 1.6 ms, hidden_size 576
meta-device skeleton in 28 ms, 134,515,008 parameters, all on meta: True

Now compare with the same model's repo on the Hub. The script lists its files through the Hub API.

--- the same model on the Hub: HuggingFaceTB/SmolLM2-135M-Instruct ---
  README.md                           6,772
  all_results.json                      783
  config.json                           861
  eval_results.json                     586
  generation_config.json                132
  merges.txt                        466,391
  model.safetensors             269,060,552
  special_tokens_map.json               655
  tokenizer.json                  2,104,556
  tokenizer_config.json               3,764
  train_results.json                    232
  trainer_state.json                 57,225
  training_args.bin                   6,520
  vocab.json                        800,662

The weights file is 269,060,552 bytes on the Hub, about half of ours, because the checkpoint is stored in bfloat16 and we loaded it as float32. The other extra files come from the original training run or an older tokenizer format. README.md is the model card, and save_pretrained does not write one.

The last piece is publishing. This script does not upload anything. After logging in, these two lines put the folder on the Hub:

model.push_to_hub("your-name/smollm2-arithmetic")
tok.push_to_hub("your-name/smollm2-arithmetic")

Checkpoint

  • lm_head.weight is not in the file, since it is tied to the embedding.
  • test_safetensors_by_hand_equals_library and test_sharded_round_trip pass.
Step 14

Plug our own model into the stack

GoalWrite a config and model class, register them, and get saving, loading, generate, Trainer and PEFT without further work.

So far we have used Llama. Every library above worked because the model follows a contract. Now we write a model of our own that follows it. First the config.

class BackwardPassConfig(PreTrainedConfig):
    # model_type is written into config.json; AutoConfig reads it back to pick this class.
    model_type = "backward_pass"
    keys_to_ignore_at_inference = ["past_key_values"]

    # In transformers 5 a config is a dataclass: annotated fields with defaults.
    vocab_size: int = 512
    hidden_size: int = 64
    num_hidden_layers: int = 2
    num_attention_heads: int = 4
    intermediate_size: int = 256
    max_position_embeddings: int = 256
    rms_norm_eps: float = 1e-6
    initializer_range: float = 0.02
    use_cache: bool = True
    tie_word_embeddings: bool = True
    pad_token_id: int | None = 0
    bos_token_id: int | None = 1
    eos_token_id: int | None = 2

    def validate_architecture(self):
        if self.hidden_size % self.num_attention_heads != 0:
            raise ValueError(f"hidden_size {self.hidden_size} is not divisible by {self.num_attention_heads} heads")
Listing 26The config. In transformers 5 this is a dataclass with annotated fields.

model_type is the string that gets written into config.json. It is what the Auto classes read back. The block itself is a small pre-norm decoder and it is not the point here, so we skip to the plumbing. C3 and C4 build a modern block properly.

class BackwardPassPreTrainedModel(PreTrainedModel):
    """Shared plumbing: which config class to use, the weight-name prefix, init, and capabilities."""

    config: BackwardPassConfig  # transformers 5 reads the config class from this annotation
    base_model_prefix = "model"  # weights of the base model live under "model." in the causal-LM class
    _no_split_modules = ["BackwardPassBlock"]  # device_map="auto" never splits a block across devices
    supports_gradient_checkpointing = True
Listing 27The shared base class tells the library which config to use and where the weights live.

Now the top-level class with its head. The whole integration lives in a few lines: the two parent classes, the tied weights map, and a forward that accepts the standard arguments and returns a standard output.

class BackwardPassForCausalLM(BackwardPassPreTrainedModel, GenerationMixin):
    # transformers 5 format: {tied parameter: source parameter}. Saved once, re-tied on load.
    _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}

    def __init__(self, config: BackwardPassConfig):
        super().__init__(config)
        self.model = BackwardPassModel(config)
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
        self.post_init()

    def get_input_embeddings(self) -> nn.Embedding:
        return self.model.embed_tokens

    def set_input_embeddings(self, value: nn.Embedding) -> None:
        self.model.embed_tokens = value

    def forward(
        self,
        input_ids: torch.LongTensor | None = None,
        attention_mask: torch.Tensor | None = None,
        position_ids: torch.LongTensor | None = None,
        past_key_values: Cache | None = None,
        inputs_embeds: torch.Tensor | None = None,
        labels: torch.LongTensor | None = None,
        use_cache: bool | None = None,
        output_hidden_states: bool | None = None,
        **kwargs,  # accepting **kwargs lets Trainer pass num_items_in_batch for exact gradient accumulation
    ) -> CausalLMOutputWithPast:
        out = self.model(
            input_ids=input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_hidden_states=output_hidden_states,
        )
        logits = self.lm_head(out.last_hidden_state)  # (B, T, V)
        loss = None
        if labels is not None:
            # The library's causal-LM loss: shift by one, ignore -100, divide by num_items_in_batch if given.
            loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
        return CausalLMOutputWithPast(
            loss=loss, logits=logits, past_key_values=out.past_key_values, hidden_states=out.hidden_states
        )


def register() -> None:
    """Teach the Auto classes about model_type="backward_pass". Safe to call more than once."""
    AutoConfig.register("backward_pass", BackwardPassConfig, exist_ok=True)
    AutoModel.register(BackwardPassConfig, BackwardPassModel, exist_ok=True)
    AutoModelForCausalLM.register(BackwardPassConfig, BackwardPassForCausalLM, exist_ok=True)
Listing 28The head, the tie, the forward contract and the registration.

Two details in this listing are easy to miss. GenerationMixin is what gives us generate(); a PreTrainedModel alone no longer has it. And **kwargs in forward is not decoration. Trainer checks for it, and only then passes num_items_in_batch, which is what makes token-weighted accumulation exact.

What PreTrainedModel adds to nn.Module
Capabilityclass MyModel(nn.Module)class MyModel(PreTrainedModel)
ConfigYour own argumentsA config object, saved as config.json
InitialisationYou call itpost_init runs _init_weights
Saving and loadingtorch.save of a state dictsave_pretrained, from_pretrained, safetensors, shards
Weight tyingBy hand in __init__; it stays tied through load_state_dictDeclared once, saved once, re-tied on load
HubNot includedpush_to_hub
GenerationYour own loopgenerate, with GenerationMixin
Device placementYou place each moduledevice_map="auto", using _no_split_modules
$ .venv/bin/python c02-hf-stack/scripts/14_custom_model.py
--- what PreTrainedModel adds on top of nn.Module ---
  method                           nn.Module  BackwardPassForCausalLM
  forward                          True       True
  state_dict                       True       True
  save_pretrained                  False      True
  from_pretrained                  False      True
  push_to_hub                      False      True
  generate                         False      True
  resize_token_embeddings          False      True
  gradient_checkpointing_enable    False      True
  tie_weights                      False      True
  post_init drew embeddings with std 0.0200, config.initializer_range = 0.02
--- after register() ---
  config.json                      477
  generation_config.json           216
  model.safetensors            595,472
  architectures: ['BackwardPassForCausalLM']
  lm_head saved separately: False
AutoConfig           -> BackwardPassConfig
AutoModel            -> BackwardPassModel
AutoModelForCausalLM -> BackwardPassForCausalLM
save/load round trip, logits identical: True
tied after load: True

--- outputs ---
  loss             () float32
  logits           (2, 7, 512) float32
  past_key_values  DynamicCache: 2 layers, keys (2, 4, 7, 16), values (2, 4, 7, 16)
  hidden_states    tuple of 3 × (2, 7, 64)

--- generate(), from GenerationMixin ---
generate equals a no-cache greedy loop: True

--- Trainer treats it like any other model ---
raw vs Trainer, max |loss diff|: 7.15e-07

--- PEFT needs only module names ---
trainable, total: (3072, 151488)

Checkpoint

  • The save and load round trip gives identical logits, and the head stays tied.
  • test_save_load_round_trip_through_auto_classes, test_causality, test_cached_forward_equals_full_forward, test_generate_matches_reference_loops and test_trainer_equals_raw_loop_because_forward_accepts_kwargs pass.
Step 15

Add vision to the custom model

GoalSee the pieces a VLM needs on top of a language model: nested configs, an image token, a processor step, and a forward that mixes the two.

A VLM is a vision encoder feeding a language model. The new code is small, but each piece has to agree with the others. The processor from step 4 has its own half of this contract.

Theory inTeaching language models to see
class BackwardPassVLMConfig(PreTrainedConfig):
    model_type = "backward_pass_vlm"
    # Sub-configs: each is saved as a nested dict in config.json and rebuilt as its own config class.
    sub_configs_defaults = {"vision_config": SiglipVisionConfig, "text_config": BackwardPassConfig}

    vision_config: dict | PreTrainedConfig | None = None
    text_config: dict | PreTrainedConfig | None = None
    image_token_id: int = 3  # a token the tokenizer reserves for "an image feature goes here"


def expand_image_tokens(input_ids: list[int], image_token_id: int, tokens_per_image: int) -> list[int]:
    """The processor's core job: replace each single image placeholder with `tokens_per_image` copies."""
    out: list[int] = []
    for tok in input_ids:
        out.extend([tok] * tokens_per_image if tok == image_token_id else [tok])
    return out
Listing 29Two sub-configs, one image token, and the processor's core job.

Nested configs save as nested dicts in one config.json, and each one is rebuilt as its own class. expand_image_tokens does what SmolVLM's processor did in step 4, without the tiles.

    def image_features(self, pixel_values: torch.Tensor) -> torch.Tensor:
        """pixel_values: (B_img, 3, H, W) → (B_img, P, D_text), P = (H / patch)²."""
        patches = self.vision(pixel_values=pixel_values).last_hidden_state  # (B_img, P, D_vision)
        return self.projector(patches)

    def forward(
        self,
        input_ids: torch.LongTensor | None = None,
        pixel_values: torch.Tensor | None = None,
        attention_mask: torch.Tensor | None = None,
        labels: torch.LongTensor | None = None,
        past_key_values=None,
        inputs_embeds: torch.Tensor | None = None,
        use_cache: bool | None = None,
        **kwargs,
    ) -> CausalLMOutputWithPast:
        if inputs_embeds is None:
            inputs_embeds = self.get_input_embeddings()(input_ids)  # (B, T, D)
        if pixel_values is not None:
            features = self.image_features(pixel_values)  # (B_img, P, D)
            slots = input_ids == self.config.image_token_id  # (B, T)
            if slots.sum() != features.shape[0] * features.shape[1]:
                raise ValueError(
                    f"{int(slots.sum())} image tokens in the text but {features.shape[0] * features.shape[1]} "
                    "image features: the processor and the vision encoder disagree on tokens per image"
                )
            # Fill the placeholder positions, in order, with the image feature vectors.
            inputs_embeds = inputs_embeds.masked_scatter(slots[..., None], features.to(inputs_embeds.dtype))
Listing 30The multimodal forward. Embed the text, encode the image, and pour image features into the placeholder positions.

Figure 12The real shapes from the script. A 32 × 32 image with 8 × 8 patches gives 16 feature vectors. One placeholder becomes 16 image tokens, and masked_scatter fills them in order. The language model then sees a normal sequence of embeddings.
$ .venv/bin/python c02-hf-stack/scripts/15_custom_vlm.py
vision_config: SiglipVisionConfig | text_config: BackwardPassConfig
parameters: 178,496

processor step: 5 tokens with 1 placeholder -> 20 tokens (16 image tokens)
pixel_values   (1, 3, 32, 32)
image features (1, 16, 64)
input_ids      (1, 20)
logits         (1, 20, 512) | loss 6.1393

config.json keys: ['architectures', 'dtype', 'image_token_id', 'model_type', 'text_config', 'vision_config']
vision_config.model_type: siglip_vision_model
text_config.model_type  : backward_pass
Auto class -> BackwardPassVLMForConditionalGeneration | round trip logits match: True

generate: (1, 20) -> (1, 25)
Custom VLM forward (B = 1, P = 16, T = 20, D = 64, V = 512)
TensorShapeMeaning
pixel_values(1, 3, 32, 32)One RGB image.
image features(1, 16, 64)Patches, projected to the text width.
input_ids(1, 20)4 text tokens and 16 image tokens.
inputs_embeds(1, 20, 64)Text embeddings with the image features written in.
logits(1, 20, 512)Next-token scores at every position.

Generation has one wrinkle. Images are encoded once, during prefill. After that the KV cache holds what the text attended to, so prepare_inputs_for_generation passes pixel_values only on the first iteration. test_generate_with_cache_matches_full_recompute checks this.

Checkpoint

  • The Auto class returns our VLM after a round trip, and the logits match.
  • test_forward_shapes, test_image_changes_the_prediction, test_misaligned_image_tokens_raise and test_round_trip pass.

The layers compared

Rows are the ways we ran a training loop. Columns are the aspects we measured or built. Read down the agreement column first. The first four rows compute the same thing, so among them the choice is about who owns the code and not about the result. The TRL row is different. Those trainers add new losses, and here we only checked that the SFT labels match ours.

Five ways to run training in this tutorial. Step times: 4-layer Llama, batch 8, AMD EPYC 7R13, 8 threads, a single run at a load average above 70, so differences of a few milliseconds mean nothing.
LayerOwns the loopYou writeAgreement with the raw loopStep timeProcessesBest for
Raw PyTorchYouEverythingThe reference32.1 msYour own DDP setupLearning, exact control
TrainerLibraryArguments, collator1.43e-06 in loss over 60 steps35.0 msSet by the launcherStandard training
Subclass of TrainerLibraryOne or two methods9.54e-07 against default Trainer, with the new term offNot measuredSet by the launcherA new loss or metric
AccelerateYouThe loop, minus devices4.77e-07 on 1 process, 9.54e-07 on 2 CPU processes29.5 msSet by the launcherUnusual loop shapes
TRL trainersLibraryA dataset in the right formatSFT labels equal ours. Losses not compared here; C6 does that.Not measuredSet by the launcherSFT, DPO, reward models, GRPO

The pattern to notice: across the first four rows, moving down the table does not change the mathematics. It moves one decision at a time between you and the library. That is why equivalence tests are possible at all, and why they are the best way to learn a new layer.

That is the idea behind this whole tutorial. Hugging Face should automate mechanics you already understand, not hide them from you.

Run everything

The final folder, and every command that produced a number in this post.

c02-hf-stack/ final tree
c02-hf-stack/
├── README.md
├── conftest.py
├── hfstack/
│   ├── utils.py
│   ├── inspection.py
│   ├── chat.py
│   ├── data.py
│   ├── collators.py
│   ├── training.py
│   ├── custom_trainer.py
│   ├── accelerate_loop.py
│   ├── generation.py
│   ├── lora.py
│   ├── trl_runs.py
│   ├── hub.py
│   ├── custom_model.py
│   └── custom_vlm.py
├── scripts/
│   ├── 01_config_and_auto.py
│   ├── 02_tokenizer.py
│   ├── 03_chat_template.py
│   ├── 04_processor.py
│   ├── 05_datasets.py
│   ├── 06_collator.py
│   ├── 07_raw_vs_trainer.py
│   ├── 07b_trainer_eval_checkpoint.py
│   ├── 08_custom_trainer.py
│   ├── 09_accelerate.py
│   ├── 10_outputs_and_generate.py
│   ├── 11_lora.py
│   ├── 11b_lora_seeds.py
│   ├── 12_trl.py
│   ├── 13_hub_and_safetensors.py
│   ├── 14_custom_model.py
│   ├── 15_custom_vlm.py
│   └── 16_side_checks.py
├── benchmarks/
│   ├── bench_map.py
│   ├── bench_loops.py
│   └── bench_generate.py
├── tests/
└── results/
$ for s in c02-hf-stack/scripts/*.py; do .venv/bin/python "$s"; done
$ OMP_NUM_THREADS=1 .venv/bin/python -m torch.distributed.run --nproc_per_node 2 c02-hf-stack/scripts/09_accelerate.py --ddp
$ for b in map loops generate; do .venv/bin/python c02-hf-stack/benchmarks/bench_$b.py; done
$ .venv/bin/python -m pytest c02-hf-stack -m "not slow and not gpu and not network"
$ .venv/bin/python -m pytest c02-hf-stack -m network
$ .venv/bin/python -m pytest c02-hf-stack -m slow
51 passed, 12 deselected in 33.54s
11 passed, 52 deselected in 40.01s
1 passed, 62 deselected in 54.59s

The tests marked network download tokenizers and processors from the Hub. The one marked slow starts two processes for the DDP comparison.

Key insights and nuances

Exercises

  1. Find a label bug in a new templateEasy Pick another chat model from the Hub and run assistant_labels_by_prefix on it. Does the prefix check pass? Which tokens are labelled? Write a test that decodes the labelled tokens and compares them with the reply.
    Hint

    Some templates insert date lines or thinking blocks, and those can break prefix preservation.

  2. Break the match on purposeMedium Remove one choice at a time from the raw loop: decay groups, clipping, then the warmup. Print the first step where the loss differs from Trainer by more than 1e-4, and explain why it is that step.
    Hint

    Look at the learning rate column first. It is 0 at step 0, so the first update changes nothing. Removing the warmup can show at step 1. Clipping and decay can first show at step 2, the first loss computed after a nonzero update.

  3. Add an evaluation loopMedium Add a held-out loss to train_raw and match it to Trainer with eval_strategy="steps". Check the mode of the model and the padding of the eval batch.
  4. Write a bigger custom lossMedium Add label smoothing to ZLossTrainer. Then compare it with label_smoothing_factor in TrainingArguments until they agree, or until you can explain why they do not.
  5. Make the custom VLM trainHard Write a VisionChatCollator for BackwardPassVLMForConditionalGeneration and train it on rendered images of digits. Check that test_image_changes_the_prediction still holds after training, and that loss falls. C7 and C8 build the full version.

Continue reading

References

Grouped by topic. Every entry links to its primary source.

Library documentation

File formats

Methods used in the examples

Models and code