# Instrumented generator

Original LearnAI teaching material, CC0. Python 3.10+ standard library only. No pretrained model, network, dependencies or paid service. The model has fixed **authored, untrained** weights and four token IDs. It teaches execution, numerical agreement and measurement; its output is not meaningful natural language.

## Setup and first run

Extract into a fresh folder and open a terminal there. Check `python --version` (use `py` on Windows or `python3` on macOS/Linux if appropriate). If Python is absent, install it using your operating system package manager or official Python installer; ask your school technician where required. These are terminal commands, not statements to paste at Python's `>>>` prompt.

```
python generator.py --prompt 0,1 --limit 4 --output cached-1.json
python generator.py --prompt 0,1 --limit 4 --uncached --output uncached-1.json
python -m unittest test_generator.py
python -m unittest test_learner.py
```

The reference tests should pass. Learner tests intentionally fail at a TODO until you implement `learner.generate_ids`. Do not edit expected values to make a bug pass. `--output` refuses to overwrite existing reports; choose new filenames for repeats. The command without `--output` prints JSON.

If a file is missing, inspect the current folder. If Python reports indentation, use four spaces consistently. A traceback's last line names the immediate error; inspect the indicated source line and the expected input contract. Limit and ID errors are deliberate validation, not permission to remove the bounds.

## Mechanism, notation and units

A token is an integer ID 0–3; 3 is EOS, the stop token. Each ID has two numerical embedding coordinates. For the current final token, query `q` is its embedding. Every prefix token has key `k` equal to its embedding and value `v = (0.5*x+y, x-0.5*y)`. The score is `(q1*k1 + q2*k2)/sqrt(2)`. The subscript identifies one of two coordinates. Softmax converts the scores to positive weights summing to one; the weighted values form the current two-coordinate state. Dot-products with the four embeddings produce output scores. Greedy selection chooses the largest score, breaking ties toward the smallest ID. This single-layer last-query calculation is not a full transformer.

For prompt `[0]`, attention has one weight equal to one. Its value is `(0.5,1)`, giving output scores `[0.5,1,0,-0.3]` and selected token 1. Predict the next result before inspecting its trace.

Cached execution retains keys/values for the exact previous prefix. It projects only appended tokens but still computes attention against every prefix position for each new query. Uncached execution recomputes all prefix projections. Prefix edits, truncation or changed model identity reject reuse; create a fresh cache. Every score must agree within `1e-12`, not just the winning token. A cache is in-memory only; imported files never execute.

## Measurement boundaries

`perf_counter_ns` is a monotonic elapsed-time clock. Nanoseconds divided by 1,000,000 give milliseconds. Preparation, prefill, first selection and subsequent decode have separate reported intervals. Time to first token runs from start (after imports) through first selection. Total generation includes validation and loop bookkeeping, but excludes subsequent environment inspection, JSON serialization, disk writing and terminal display. No model-loading or user-interface latency is measured. Times are measured, while projection-token and attention-term counts are exact operation accounting, not estimates of milliseconds.

Later-token rate is `(generated tokens - 1) / decode seconds`; fewer than two tokens or zero clock duration gives `null` (unavailable). Limit zero generates nothing and has no first-token time. EOS stopping and output-limit stopping have different reasons. Cancellation is checked before each bounded model call; already selected tokens remain. Prompts contain 1–16 token IDs, each in the range 0–3; generated output contains 0–16 tokens, with a maximum scored prefix of 31 tokens.

## Implementation and project

Implement `learner.generate_ids` and add tests for cancellation after one accepted token, malformed scorer output, exact caps and ties. Never evaluate arbitrary downloaded or imported text. The reference's scorer is a callable supplied by your own local code.

For the separate project, use its new prompts and implement instrumentation around your own loop. Run at least five repeats per matched setting; retain raw reports, code/input digests, Python version and the boundary definition. Compare per-step scores, token counts and stop reasons before comparing timing medians and ranges. Add serialization timing as a separate metric rather than silently redefining total generation. Provide exact fresh-folder run commands and ask a reviewer to introduce a prefix change or cancellation. No local timing result establishes vendor performance or independent implementation proficiency.
