Evaluate perplexity of a long text with a strided sliding window

Why it matters Reported perplexities for long texts depend on this exact windowing; a smaller stride gives more context per token and a lower, fairer perplexity.

A model with context length max_len cannot score a long text in one pass. A strided sliding window gives every scored token as much context as possible while scoring each token exactly once.

Write strided_perplexity(ids, logprob_fn, max_len, stride). ids has length n >= 2. logprob_fn(window) returns an array of len(window) values where entry j is log p(window[j] | window[:j]) (entry 0 has no context). Loop: prev_end = 0; for begin = 0, stride, 2*stride, ...: end = min(begin + max_len, n); score the last (end - prev_end) entries of logprob_fn(ids[begin:end]), except that global position 0 is never scored; set prev_end = end; stop after the window that reaches end == n. Return (ppl, count) with ppl = exp(-total / count) and count the number of scored tokens.

Signaturedef strided_perplexity(ids, logprob_fn, max_len, stride)

Example

with the toy model logprob_fn(w)[j] = -1/(j+1) - 0.1*w[j], ids = [0, 1, 2, 3, 4, 5], max_len 4 and stride 2 score global positions 1, 2, 3 in the first window and 4, 5 in the second, so count is 5 (and the perplexity is about 1.8839).

Understand the idea

A model that reads 1024 tokens cannot score a 10,000-token book in one go. Cutting the book into separate chunks works but is unfair: the first tokens of each chunk get almost no context. A sliding window moves forward by a stride and scores only the tokens that are new in each window, while the earlier part of the window serves as context, like re-reading the last page before starting a new one.

Example: 6 tokens, window 4, stride 2. Window 1 covers tokens 0 to 3 and scores 1, 2, 3 (token 0 has no context). Window 2 covers tokens 2 to 5; tokens 2 and 3 are context only, and 4 and 5 are scored. Every token from 1 to 5 is scored exactly once: count 5.

Rule: targets in a window = its last (end - prev_end) positions; ppl = exp(-sum log p / count).

Stride equal to max_len is fastest but gives the least context; stride 1 gives the most context but costs n forward passes. Published perplexity numbers depend on this choice.

Shapes and data flow

ids (n,) -> windows of length <= max_len -> scored targets per window (end - prev_end,) -> total count n - 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: examplestrided_perplexity([0, 1, 2, 3, 4, 5], toy, 4, 2)[1]
  • Sample 2: overlapstrided_perplexity([0, 1, 2, 3, 4, 5], toy, 4, 2)