Build next-token training pairs with a sliding window and stride

Why it matters Every GPT-style pretraining data loader turns a token stream into (input, target) windows like this.

A language model learns by predicting token t+1 from tokens up to t. A long token stream is cut into fixed windows, and the target window is the input window moved one step right.

Write next_token_pairs(ids, context, stride). ids is a 1D list or array of ints of length n. Window i starts at s = i * stride. Its input is ids[s : s + context] and its target is ids[s + 1 : s + context + 1]. Keep only windows whose full target fits inside ids. Return a tuple (X, Y) of int arrays, each of shape (num_windows, context). If no window fits, both arrays have shape (0, context).

Signaturedef next_token_pairs(ids, context, stride)

Example

next_token_pairs([10, 11, 12, 13, 14, 15, 16], 3, 2) returns X = [[10, 11, 12], [12, 13, 14]] and Y = [[11, 12, 13], [13, 14, 15]].

Understand the idea

A language model is trained to guess the next token. So one training example is a window of tokens as input, and the same window moved one step to the right as the answer.

Take the stream 10 11 12 13 14 15 16 with context 3. The first input is 10 11 12 and its target is 11 12 13: under each input token sits the token that comes after it. With stride 2 the next window starts two tokens later: input 12 13 14, target 13 14 15. A window starting at 14 would need a target 15 16 ?, which does not exist, so it is dropped.

Rule: for start s = 0, stride, 2*stride, ... keep the window when s + context + 1 <= n; input = ids[s : s+context], target = ids[s+1 : s+context+1].

Stride equal to context gives no overlap and uses each token once per epoch. A smaller stride gives more, overlapping examples. Pretraining loaders for GPT-style models build batches exactly this way.

Shapes and data flow

ids (n,) -> X (num_windows, context), Y (num_windows, context); Y[i] = X[i] shifted left by one plus the next token
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplenext_token_pairs([10, 11, 12, 13, 14, 15, 16], 3, 2)
  • Sample 2: stride equals contextnext_token_pairs(list(range(10)), 4, 4)
  • Test 3: overlappingnext_token_pairs([7, 8, 9, 7, 8], 2, 1)
  • Test 4: too shortnext_token_pairs([1, 2, 3], 3, 1)[0].shape