Example

Separate accepting a long prompt from using it

Run a toy attention workload at three context lengths and mark which long-context claim the measurement actually supports.

A long-context claim bundles at least five separate questions: does the model accept the tokens, does it behave correctly at those positions, does the state fit in memory, does it answer in acceptable time, and does it use the evidence it was given? A benchmark that shows only the first or the fourth has not shown the rest.

This example runs a toy attention calculation at 1,024, 8,192 and 32,768 positions. It measures wall-clock time and a Python allocation peak, and it marks whether the prompt was truncated at max_context. It says nothing about a real model’s quality or retrieval. The value is the separation: the run supports a statement about cost growth and acceptance, not about understanding.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch23/long_context.py --lengths 1024,8192,32768 --max-context 32768 --json

Python 3.11 or later with PyTorch. CPU-only, seeded, no model download, network, GPU or credentials. The 32,768-position case is quadratic and takes several seconds on this machine; the smaller lengths are fast.

Implementation

run_prompt truncates the length to max_context, builds random query, key and value tensors, and computes full attention. tracemalloc measures Python allocations, not the tensor storage owned by PyTorch. The truncated flag is a simple length comparison, not a tokeniser decision.

def run_prompt(prompt_len: int, max_context: int, seed: int = 0) -> WorkloadResult:
    torch.manual_seed(seed)
    truncated = prompt_len > max_context
    effective = min(prompt_len, max_context)
    q = torch.randn(effective, 8)
    k = torch.randn(effective, 8)
    v = torch.randn(effective, 8)
    tracemalloc.start()
    start = time.perf_counter()
    scores = torch.matmul(q, k.T) / (8 ** 0.5)
    weights = torch.softmax(scores, dim=-1)
    out = torch.matmul(weights, v)
    latency = time.perf_counter() - start
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return WorkloadResult(
        prompt_len=prompt_len,
        latency_seconds=latency,
        peak_memory_bytes=peak,
        truncated=truncated,
        metadata={"effective_len": effective, "max_context": max_context},
    )

Expected outcome

Observed with the command above (exit 0). Selected stable fields from the first result:

    "prompt_len": 1024,
    "truncated": false,
      "effective_len": 1024,
      "max_context": 32768

In this run the measured attention times rose from about 0.0029 s at 1,024 positions to 0.276 s at 8,192 and 6.20 s at 32,768, roughly the quadratic growth expected from full attention. The reported peak_memory_bytes stayed at 240 for all three because tracemalloc does not see PyTorch’s tensor allocations. That field is therefore not evidence about KV-cache or activation memory.

Mechanism and limitations

Documented: run_prompt truncates to max_context, computes full attention over random tensors, times the calculation and records a tracemalloc peak. The tests check truncation and non-truncation, non-negative latency, cache invalidation on a length change, the workload list and JSON serialisation.

Observed: the command exited 0 with truncated: false and the effective lengths above; the times grew with length. The targeted tests.test_ch23_long_context is part of the canonical suite; no independent test count is claimed here.

Not shown: a real model’s context window, tokeniser, positional behaviour, retrieval accuracy, memory footprint, or serving latency. The toy attention uses random tensors and no KV cache, so it is a cost demonstration, not a model evaluation. The peak_memory_bytes field is misleading for tensor memory and must not be quoted as a memory result.

Challenge this result

Run with --lengths 40000 --max-context 32768. Predict truncated, effective_len and whether the time matches the 32,768 case. Then design one measurement for each of the five long-context claims: acceptance, positional behaviour, memory fit, latency, and use of evidence. State which of those can be answered by this toy and which require a real model and a controlled task.

Source and verification

Canonical source: examples/ch23/long_context.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch23_long_context.py . Chapter: Long-Context Inference . The run above is a fresh local execution on Windows 11 with Python 3.13.15 and PyTorch 2.6.0+cu124; it uses random tensors, not a model.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.