liveBook · Manning

Collate function

As explained in Build a Large Language Model (From Scratch)

A data-loading function that merges a list of individual samples into a single batch, optionally applying padding and other formatting.

A collate function merges individual tokenized samples into one training batch. Instruction fine-tuning needs a custom function because sequences require task-specific padding, targets, and loss masking. section 7.3

A custom collate function prepares the model-facing tensors in a fixed sequence:

  • Find the longest sample, append the end-of-text padding token 50256, and pad every sequence to the batch length. section 7.3

Three variable-length samples

For [0,1,2,3,4], [5,6], and [7,8,9], the input batch becomes [[0,1,2,3,4], [5,6,50256,50256,50256], [7,8,9,50256,50256]]. Targets shift each row one position and replace extra padding targets with -100.

How Build a Large Language Model (From Scratch) covers it

How deep it goes
Details padding, shifted targets, device placement, maximum length, and loss masking, but not DataLoader internals.
Examples
Demonstrates variable-length token lists, padded input tensors, shifted targets, and -100 loss masking.
What it assumes
Assumes tokenized samples and basic tensor batching while teaching padding, next-token alignment, and ignored loss positions.
What you can do after
Build it from scratch as a PyTorch collate function returning padded input and target tensors for instruction fine-tuning.
How it connects
Connects tokenization, padding, target token IDs, cross-entropy loss, DataLoader, and instruction fine-tuning.

Also explained in

Compare how 2 books explain collate function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Large Language Model (From Scratch). The section links point to the parts of the book it draws on.