Pack examples into fixed-length training rows

MediumFine-tuningPro

Why it matters Packing is a 2x to 5x throughput win in SFT on short chat examples.

Packing concatenates short examples into full rows so no compute is wasted on padding, with position ids that restart per example.

Write pack_sequences(examples, max_len). examples is a list of token lists, each of length <= max_len. Greedily fill rows in order: append an example to the current row if it fits, otherwise start a new row. Return (rows, positions, seg_ids), each a list of lists, where positions restart at 0 for every example and seg_ids number the examples within a row starting at 1. Do not pad.

Signaturedef pack_sequences(examples, max_len)

Example

pack_sequences([[1, 2], [3], [4, 5, 6]], 4) gives rows [[1, 2, 3], [4, 5, 6]], positions [[0, 1, 0], [0, 1, 2]], seg_ids [[1, 1, 2], [1, 1, 1]].

Understand the idea

Fine-tuning data has many short examples. Padding each one to the full length wastes compute. Packing places several examples back to back in one row. To keep them separate, each token gets a position id that restarts at 0 for every example, and a segment id telling which example in the row it belongs to, so attention can be blocked across examples. Worked example: examples [[1, 2, 3], [4, 5], [6], [7, 8, 9, 10]], max_len 5. Row 1 takes [1, 2, 3] and then [4, 5] (total 5). [6] would make 6, so start row 2 with [6], then add [7, 8, 9, 10] (total 5). Rows [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]; positions [[0, 1, 2, 0, 1], [0, 0, 1, 2, 3]]; seg_ids [[1, 1, 1, 2, 2], [1, 2, 2, 2, 2]]. Rule: go through examples in order; if the current row length plus the example length is at most max_len, append it, else start a new row; positions are 0 .. len - 1 per example; segment numbers restart at 1 in each new row. Do not pad. Used in: efficient SFT and pretraining pipelines.

Shapes and data flow

examples [2, 1, 3] tokens, max_len 4
row 1: [ex1 ex1 ex2] seg [1 1 2]
row 2: [ex3 ex3 ex3] seg [1 1 1]
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplepack_sequences([[1, 2], [3], [4, 5, 6]], 4)
  • Sample 2: exact fitpack_sequences([[1, 2], [3, 4], [5]], 4)