diff --git a/PROJECT_MANIFEST.sha256 b/PROJECT_MANIFEST.sha256 index 2066f28..8a5f924 100644 --- a/PROJECT_MANIFEST.sha256 +++ b/PROJECT_MANIFEST.sha256 @@ -16,11 +16,13 @@ e4e7fe0fb913eda0e53509083b9dc25680cc8e5e68ef5c22a60543ddc7c5a79d ./assets/chart f65bd5f8df765c5247a2808ab465c8f7cb12381c9789949f19b462e8ee6a1125 ./CITATION.cff 7ddc4d0bcf64d5f8bc42be909b7a1a1a959b02004106e33f82e1b9ad85b1771e ./config/default.yaml c091241a730c6245becafe6634947f35575f0a941d8375022cac8ecfd5549ded ./config/tensorrt-llm-capacity-120k.yaml +9877c3549295259f15cec64262cec9ee51d4aa329e2b7da97da95b14bad61bb5 ./config/tensorrt-llm-context-scaling.yaml 1b4ab1268e0c5f4e5c6948067944d4b7506e40617bad1aceff9b6f1339f5b174 ./config/tensorrt-llm-profile-c4.yaml 9828c4c66605cc2c93859ffa7484c472d69587c6be94acd250748dd1f7cf6afa ./config/tensorrt-llm-smoke.yaml e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./data/.gitkeep 72784da5ab0d762248ed8526fe3284e32c15a15eb1e9c2e99ed5b801bfed4176 ./docs/architecture.md a7de43adec127ff112ab556095247b019f362d63460f294d33fb2f50785aad7f ./docs/capacity.md +51cdd637b3114158b5a93275aaa06ad27308c338ad38e7659ab296659997f1d3 ./docs/context-scaling.md 67dab2a1559389f73148d1055fc20c2de0eae79c625985c011fca438d9b7140a ./docs/DESIGN_MAPPING.md cb7cbbbf69a14ccced146130f9735ce76dc72f4d77c349a42889954767e07b82 ./docs/fairness-and-limitations.md 181ed639e1a1553745d78d9ff99219f4b73a86be2b0b48601cefd0671024a0db ./docs/methodology.md @@ -36,7 +38,7 @@ fc9737e71d1258113190b602d769a91537979af56cefe3b6bf1d763b08cece97 ./.env.example 9a76f67fdf6e34a5a296fc0c6dc8790f68c980da882fe7dfcfa7c239181fa602 ./.gitignore 1126322e2cc8d165adc4c792eeb195717de2bcc7b39be1ce77959d78e87ef685 ./LICENSE c6ce66613fe24e44b86db05bb0ff42734f3109cff378eea1f33a5738463667d3 ./pyproject.toml -2ab3775a9eba72ecc6c79b7754788762761a2095bb90b3351c03bf43c6e643be ./README.md +98837d71e9c8efc8834e94e82740ee2efa11c52b1291c768b10a44973a9d75c5 ./README.md f9d4e391eee30f9d6cb74404521826859c0aabe7a88708899ecf51c1da090626 ./reports/benchmark-report.md b8b508ae02706f1f807ef74add54aefe1f4cd488f45684e215a0241c891c269a ./reports/executive-summary.md a3eb564b35671d3757bc5cc5387f8eeca05f865ecc991fb5eaed003528bf6d11 ./requirements.lock @@ -49,6 +51,9 @@ a35a62233b000188b3f22a1acfcf6a2f2cccdb9dfe7324a7d5870f0b8eea36f2 ./results/summ 6f2b6c6306d42fd9f848eb299d4e46b20d94bbdb19100753107212a39b34a620 ./results/summaries/tensorrt-llm-capacity-analysis.md 3943bd5d7494ded94b75977fa12befe278ee2deb4246eb013b67703ed0f1009b ./results/summaries/tensorrt-llm-capacity-provenance.json 09d5cb91d8aa05ae9c19839f3967b1b08ec1404cca67a1e5108c9bf35ec10f4f ./results/summaries/tensorrt-llm-capacity-validation.csv +a1bec1f39ec8103505a86c45553d95b6b2d455a09040ce973e4bda183cf81e71 ./results/summaries/tensorrt-llm-context-scaling-analysis.md +792bb9e84fda513aa8b2d71f8c3397b756af81ba1dda634b9a0500750e62a3e4 ./results/summaries/tensorrt-llm-context-scaling-provenance.json +0f25c359b35bae0ec6af80c330ff37dd69b0f129f61d572027ba8ee25d51eabe ./results/summaries/tensorrt-llm-context-scaling-validation.csv f68cfded99ca189e652973d85c02ec637b13f09d0010598453783b728e5a86a0 ./results/summaries/tensorrt-llm-prefill-budget-analysis.md a0870ff18a976b91ddb91fd2c28f4d14cab8fb9b52d797d2fdc8eefe93eae257 ./results/summaries/tensorrt-llm-prefill-budget-profiling.csv 4867a7373ee0695c9bf49496a4ed9d3de655aafcfdb266d3d58f98c12649d022 ./results/summaries/tensorrt-llm-prefill-budget-provenance.json @@ -56,15 +61,19 @@ a0870ff18a976b91ddb91fd2c28f4d14cab8fb9b52d797d2fdc8eefe93eae257 ./results/summ f7de43402a7474aa39f3e4bac55e59933ac930577e34f94405ad165446f717b6 ./results/summaries/tensorrt-llm-summary.csv b23f3b977e56f77d35b562b226ec112d2cebd11fccedddd81e60650ca5846fa3 ./results/summaries/vllm-summary.csv aba14f17fa19bd6e9e4413c8997eeafd63f383fc6c7117621b25cfdcab4433a2 ./scripts/analyze_capacity_boundary.py +a94ab61cde2db57941d58fda29324ff965205f08ea6b7565340864219441927e ./scripts/analyze_context_scaling.py e35723c2ebd5531edd871209fe43a4c9e1f2d2c20b4de2f217e920800af2206b ./scripts/analyze_prefill_budget.py 1f4a4309a8f5a9909dae41b5ce7738968848f967f74e8c04a2e5e8a155ee1876 ./scripts/full_benchmark.sh 9380bbc0f80642d14cefa04c5cd8fb8c166b3b5d117cada91b8bf1e1fff39ffd ./scripts/generate_charts.py +cd738a4e620a7fbf7719bb0ea7a935f9cf94d1b34c5355cf447456c21ab4d049 ./scripts/run_context_scaling.py 52cd89acdd68d2dae50a3ad3ffcf90e1fe32eb3fe01a896dcdda5759dd6cb33f ./scripts/smoke_test.sh 04e686f48e0096f64f19f2eb1262c143bc0aa55cc561da3c5901eab8ea61b4c2 ./src/llm_engine_benchmark/capacity_analysis.py d6a0ad368e1fe8b757deb56a9d41f86891adc3630b4ac7885872277898132742 ./src/llm_engine_benchmark/capacity.py 1da2ff0df243bc9db2fdcc8250c915151f222b4b29afa18c2979385b90865717 ./src/llm_engine_benchmark/client.py 821afb010e241333b6eab9c1dd353035509c3a737a1668a4c45be888f064ef13 ./src/llm_engine_benchmark/cli.py 844b2c190ebf00118095ce5c92723081e065e3eb0f0599102b5c09d6594e4bc3 ./src/llm_engine_benchmark/config.py +b5fce406ab84a6f879f301189ee0414f605c764c4808f99ec8976ee40b1b0bb1 ./src/llm_engine_benchmark/context_analysis.py +5ad52bdb3db54f29e8ae9dec5fc8e93923d6db0e9ac2836a1a80d77b5fc535f8 ./src/llm_engine_benchmark/context_scaling.py e43a14a1019d648bdca921c9cd966996319a0817b047b7f093485887806af1d3 ./src/llm_engine_benchmark/datasets.py 7ddc4d0bcf64d5f8bc42be909b7a1a1a959b02004106e33f82e1b9ad85b1771e ./src/llm_engine_benchmark/default.yaml 1db5a9299c1ea0c77660af3f63783919ae14c7ee78c6e49cd5825a7dd8ff1692 ./src/llm_engine_benchmark/environment.py @@ -85,6 +94,8 @@ df823bfd5f8ea0d70ba68e3d6179beccc56f4d5b517551a8d1417b1457b5c230 ./tests/test_c 89c8fe02dba6b2f3fccd9dd2bb32933cd2c612c251dc10ebea5dfcab10c58b17 ./tests/test_client.py a1d02b16aa83bdfc805dd8610f8973452fa3264b51c5e87d4fbc2c85b407a5a4 ./tests/test_cli.py 3b74c7b4d48d9be2c383cd03c2d6779da495b6beb8b258253e06e5a9306ece24 ./tests/test_config.py +6fdb2831427d2d30cf8b3f759b75e219bebdee3cff8f2d2b0ca5146b0f277dd5 ./tests/test_context_analysis.py +c3a6a9cf09931c84ea16cd9c5dbe97592deb50a2e4e9cc674551c58709ba2e86 ./tests/test_context_scaling.py 49b879b257a013957a5a90bda9ae0812fad67cb7d19a40d3965448ba0ea1b367 ./tests/test_datasets.py 3f856fa35069b6b359ac0454eeb91d9206f57fa620d26cf7fb4fade2b589ae38 ./tests/test_locking.py 092803291540aa802307989209272861c4888a9a5b55c4bf9144d6e6ce6d7717 ./tests/test_normalize.py diff --git a/README.md b/README.md index c1a4269..ed076ea 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,9 @@ accepted run JSON + request timings - [Profiling plan](docs/profiling.md) - [Prefill-budget case study](docs/prefill-budget-case-study.md) - [SLA-constrained capacity runbook](docs/capacity.md) +- [Context-length characterization runbook](docs/context-scaling.md) +- Context campaigns support immutable-contract resume and compatible multi-source + consolidation through `scripts/analyze_context_scaling.py`. - [Fairness and limitations](docs/fairness-and-limitations.md) - [Production recommendations](docs/production-recommendations.md) - [Reproducibility and implementation details](docs/reproducibility.md) @@ -142,7 +145,7 @@ The repository excludes model weights, Hugging Face caches, TensorRT engines, se - [x] Nsight Systems capture integration - [x] Profiler-backed root cause for the TensorRT-LLM cold-C4 ITL anomaly - [ ] TensorRT-LLM through Triton -- [ ] Context scaling: 8K, 32K, 64K, 120K +- [ ] Context scaling: 8K, 32K, 64K, 120K ([isolated workflow implemented](docs/context-scaling.md); GPU validation pending) - [x] SLA-constrained throughput with [validated production capacity evidence](results/summaries/tensorrt-llm-capacity-analysis.md) ## Authorship and citation diff --git a/config/tensorrt-llm-context-scaling.yaml b/config/tensorrt-llm-context-scaling.yaml new file mode 100644 index 0000000..4d09577 --- /dev/null +++ b/config/tensorrt-llm-context-scaling.yaml @@ -0,0 +1,13 @@ +# Layered on default.yaml. Input lengths are selected by the standalone runner. +# Keep the server context ceiling fixed across cells to isolate input-length effects. +project: + engines: [tensorrt_llm] + cache_modes: [cold] + output_tokens: 512 + context_length: 131072 +engines: + tensorrt_llm: + max_batch_size: 4 + max_num_tokens: 2048 + kv_cache_free_gpu_memory_fraction: 0.80 + kv_cache_dtype: fp8 diff --git a/docs/context-scaling.md b/docs/context-scaling.md new file mode 100644 index 0000000..19f726e --- /dev/null +++ b/docs/context-scaling.md @@ -0,0 +1,204 @@ +# Phase 1: context-length characterization + +This opt-in workflow measures fixed-length cold-prefix requests at bounded client +concurrency. It is **not** mixed-workload production capacity, an accuracy benchmark, +or evidence of P99 reliability. Existing `bench run`, `bench capacity`, preparation, +and reporting code paths are unchanged. + +## Experimental contract + +| Dimension | Default | +| --- | --- | +| Engine and model | Direct TensorRT-LLM, existing pinned model/tokenizer lock | +| Input lengths | 8,000 / 32,000 / 64,000 / 120,000 tokens, exactly | +| Client concurrency | 1 and 4 | +| Output | 512 tokens; server usage required | +| Server context ceiling | Fixed at 131,072; not resized per input length | +| Prefill budget | Fixed at 2,048; not claimed optimal at every length | +| KV dtype / memory fraction | FP8 / 0.80 | +| Discovery | 20 measured requests, one repetition per cell | +| Warm-up | Two waves of C unique requests, target input length and full output length | +| Run order | Seeded shuffle of eight cells; reversed on even repetitions | + +Client-observed overlap is verified during warm-up and measurement. It does not +prove simultaneous GPU execution or that every compilation path is initialized. +Raw warm-up timings are retained for inspection. Warm-up requests are never +counted in the measured report. Nsight captures can include startup/warm-up; +filter the timeline before attributing activity to the measurement interval. + +## Preservation and isolation + +- Start from an idle Spark1. Do not run other GPU workloads during the experiment. +- The existing lock and canonical manifest are mandatory, checked, and read-only. + The runner never auto-prepares or refreshes the canonical dataset or lock. +- New prompts are generated from a deterministic task-stratified source subset. + The same selected samples are used at each length; source context is truncated + or extended through the existing normalizer, retaining the instruction suffix. + Truncation may remove answer evidence. This measures serving cost, not quality. +- Derived prompts live under the new results directory, never `data/prepared`. +- Phase 1 prompt format v3 allocates deterministic markers using the pinned + tokenizer so every prompt starts with a different token. Allocation covers the + entire measured set and every warm-up wave together. Markers are selected from + decimal and letter candidates; insufficient distinct tokens fail preparation. + The variable body is refitted to preserve the exact token count and task + instruction suffix. The legacy benchmark prompt builder remains unchanged. +- Saved prompt text is re-tokenized and hashed. Duplicate IDs or even a single + shared first token across measured/warm-up requests are rejected. Actual server + usage is still checked; no cached-token tolerance is introduced. +- Any reported cached input tokens reject the run. Missing cache usage is labeled + protocol-only evidence, not a measured zero cache-hit rate. +- Active benchmark containers, active GPU compute processes, or a busy server port + stop execution without killing another workload. This is a preflight check, not + a reservation against unrelated applications starting later. +- Containers use unique names. Existing benchmark containers are never removed. +- The results directory must not exist for a new campaign. There is no overwrite + option. `--resume` accepts only an existing campaign whose source hashes, lock, + resolved configuration, plan, prompt format, measurement protocol and immutable + options match. Every accepted cell is revalidated from its metadata, request + counts, zero-cache evidence, prepared-input hashes and observed concurrency. + Accepted cells are never overwritten. An incomplete cell is moved intact under + `interrupted/` before the same planned cell is attempted again. +- Model/runtime caches remain shared as in the existing server wrapper; they may + be populated by the engine. Existing benchmark result files are not modified. + +## Safe launch sequence + +Use the repository's installed virtual environment and run from the repository root. +First inspect the plan; this command performs no preparation, Docker calls, or writes: + +```bash +.venv/bin/python scripts/run_context_scaling.py \ + --results-dir results/context-scaling/discovery-01 \ + --dry-run +``` + +Then smoke-test the smallest length at both concurrencies. Use at least four +requests so C4 actually has four requests to issue: + +```bash +.venv/bin/python -u scripts/run_context_scaling.py \ + --lengths 8000 --concurrency 1,4 \ + --samples 4 --repetitions 1 \ + --results-dir results/context-scaling/smoke-8k-01 \ + --skip-image-pull +``` + +After checking `context_status.json`, `context_report.md`, warm-up metadata and +token usage, run all eight discovery cells in a tmux session: + +```bash +.venv/bin/python -u scripts/run_context_scaling.py \ + --samples 20 --repetitions 1 \ + --results-dir results/context-scaling/discovery-01 \ + --skip-image-pull +``` + +If the controlling process is interrupted, first stop only the uniquely named +orphan container recorded for that cell and verify that no benchmark process is +active. Resume with the identical experimental arguments plus `--resume`: + +```bash +.venv/bin/python -u scripts/run_context_scaling.py \ + --samples 20 --repetitions 1 \ + --results-dir results/context-scaling/discovery-01 \ + --skip-image-pull --resume +``` + +Changing lengths, concurrencies, sample count, repetitions, warm-up, profiling, +cooldown, image-pull policy, source data, lock or configuration rejects resume. +The runner records resume history and archived attempts in the experiment artifacts. +It does not remove containers automatically because ownership must be checked by the +operator after abrupt process termination. + +Confirm the matrix in another fresh directory: + +```bash +.venv/bin/python -u scripts/run_context_scaling.py \ + --samples 20 --repetitions 3 \ + --results-dir results/context-scaling/confirmation-01 \ + --skip-image-pull +``` + +Twenty requests per repetition supports exploratory comparison, not precise tail +estimation. For stronger request-tail evidence use `--samples 100` at selected +cells. The runner accepts up to the canonical 100 samples without duplicating them. + +Optional targeted profiling, **separate** from primary latency results: + +```bash +.venv/bin/python -u scripts/run_context_scaling.py \ + --lengths 64000 --concurrency 4 --samples 20 \ + --profile-nsys \ + --results-dir results/context-scaling/profile-64k-c4-01 \ + --skip-image-pull +``` + +`--config` can select another override file. Inspect and retain the resolved config +before comparing studies. All lengths must fit input + output within the fixed +server context ceiling; invalid options fail before workload execution. + +## Consolidating discovery or validation campaigns + +Recovery cells may be collected in new output directories when they predate resume +support. Consolidate compatible, non-overlapping sources without copying raw data: + +```bash +.venv/bin/python scripts/analyze_context_scaling.py \ + --source results/context-scaling/discovery-01 \ + --source results/context-scaling/discovery-01-recovery-120k-c1 \ + --source results/context-scaling/discovery-01-recovery-32k-c4 \ + --repetitions 1 \ + --output-dir results/summaries +``` + +The analyzer requires matching source hashes, lock, resolved configuration, image +digest, sample count, warm-up policy, prompt format and measurement protocol. It +rejects duplicate accepted cells and measured-prompt hash differences. Its CSV +retains each run; Markdown reports per-cell summaries and C4/C1 ratios; provenance +hashes every consumed plan, metadata, result and request-timing file. Missing cells +produce `incomplete`, one complete repetition produces `complete_discovery`, and at +least three complete repetitions produce `complete_repeated_validation`. + +## Evidence and interpretation + +Each experiment contains a plan, pinned source hashes, code hashes and Git identity, +resolved config/environment, prepared prompts, image identity, per-cell artifacts, +CSV/Markdown reports and SHA-256 provenance. Per-cell files include client request +timings, warm-up timings, server logs/command, metrics snapshots and telemetry status. +The default telemetry records GPU, power/thermal and system resource information +where supported. Inspect availability before making memory/utilization claims; +unavailable Spark counters are not zero. GPU process overlap is not proof of GPU +occupancy. Peak memory extraction/visualization is not part of this initial report. + +CSV rows retain per-repetition TTFT P50/P95, ITL P50/P95, TPOT mean, E2E P95, +output token throughput, request throughput, sample count and maximum observed ITL. +Markdown is a compact view. No averaging of percentiles is presented as a pooled +percentile, and no P99 claim is generated. ITL is based on observed SSE events, not +independently timestamped hardware tokens. Closed-loop client waiting is not a +production admission-queue measurement. + +Only cells accepted after measurement, cleanup and optional CUDA trace validation +enter numeric summaries. Failed and unrun cells remain visible. Whole-process +termination (SIGKILL, power loss) may prevent final reports or cleanup; inspect and +stop only the uniquely named container before using `--resume`. The runner preserves +the interrupted evidence directory rather than deleting it. + +The next phase adds workload mixtures, arrival-rate sweeps, cache-locality scenarios +and per-class SLOs using the capacity harness. It is intentionally outside this runner. + +## Initial smoke-test correction + +The initial 8K C4 warm-up reported cached tokens of 0, 8, 8, and 8. The former +32-token uniqueness check allowed a common leading header to survive. Format v2 +moved hashes to the beginning but still allowed first-token collisions: w0-0 and +w0-2 both began with token 69, and one reported one cached token. Format v3 assigns +distinct first tokens using the actual tokenizer, then validates the fitted text. +This does not relax zero-cache acceptance or disable engine prefix caching. +Retain `smoke-8k-01` and `smoke-8k-02`; rerun in `smoke-8k-03`. GPU validation is +required before launching the full matrix. Do not pool different prompt formats. + +Offline validation used the tokenizer JSON pinned at +`6cee5e81ee83917806bbde320786a8fb61efebee`: allocation produced 108 distinct +starting tokens, and 12 synthetic prompts at each of 8,000 and 120,000 tokens +passed exact-length and first-token checks. These checks do not substitute for +the next GPU smoke test or establish engine-reported zero cache usage. diff --git a/results/summaries/tensorrt-llm-context-scaling-analysis.md b/results/summaries/tensorrt-llm-context-scaling-analysis.md new file mode 100644 index 0000000..7cca54a --- /dev/null +++ b/results/summaries/tensorrt-llm-context-scaling-analysis.md @@ -0,0 +1,35 @@ +# TensorRT-LLM Context-Scaling Analysis + +- Evidence status: **complete_discovery**. +- Accepted cells: 8 / 8. +- Repetitions expected per cell: 1. +- Controlled closed-loop cold-prefix characterization; not production capacity. + +## Context matrix + +| Input tokens | C | Runs | TTFT P95 | ITL P95 | E2E P95 | Output tok/s | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 8000 | 1 | 1 | 0.879 s | 0.023 s | 11.966 s | 42.859 | +| 8000 | 4 | 1 | 2.661 s | 0.040 s | 23.643 s | 93.228 | +| 32000 | 1 | 1 | 5.531 s | 0.024 s | 17.522 s | 29.314 | +| 32000 | 4 | 1 | 16.974 s | 0.306 s | 52.228 s | 48.011 | +| 64000 | 1 | 1 | 16.864 s | 0.027 s | 30.146 s | 17.081 | +| 64000 | 4 | 1 | 51.807 s | 0.663 s | 120.516 s | 22.783 | +| 120000 | 1 | 1 | 50.050 s | 0.031 s | 65.361 s | 7.860 | +| 120000 | 4 | 1 | 146.148 s | 1.225 s | 305.989 s | 9.362 | + +## Concurrency effect + +| Input tokens | TTFT C4/C1 | ITL C4/C1 | E2E C4/C1 | Throughput C4/C1 | +| ---: | ---: | ---: | ---: | ---: | +| 8000 | 3.03× | 1.79× | 1.98× | 2.18× | +| 32000 | 3.07× | 12.48× | 2.98× | 1.64× | +| 64000 | 3.07× | 24.44× | 4.00× | 1.33× | +| 120000 | 2.92× | 39.40× | 4.68× | 1.19× | + +## Interpretation guardrails + +- This is complete discovery evidence, but one run per cell does not establish repeatability or confidence intervals. +- P95 values are per-run summaries; averaging repeated P95 values is not a pooled percentile. +- Concurrency ratios describe this fixed workload and do not identify a kernel-level cause. +- Use separate Nsight runs before attributing changes to attention, KV memory, or scheduling. diff --git a/results/summaries/tensorrt-llm-context-scaling-provenance.json b/results/summaries/tensorrt-llm-context-scaling-provenance.json new file mode 100644 index 0000000..0ca3a0d --- /dev/null +++ b/results/summaries/tensorrt-llm-context-scaling-provenance.json @@ -0,0 +1,245 @@ +{ + "benchmark_commit": "eacf23f5c5639ccb7584e8079b2e58930648a2a0", + "compatibility": { + "config": { + "engines": { + "sglang": { + "chunked_prefill_size": 8192, + "container_name": "llmbench-sglang", + "container_port": 30000, + "dtype": "bfloat16", + "extra_args": [ + "--enable-metrics", + "--enable-cache-report", + "--sampling-defaults", + "openai" + ], + "host_port": 30000, + "image": "lmsysorg/sglang@sha256:00c53fe4c31bf22d7b37537f28bbdfd924c02de13cdfb4bff7378c9c34d75ab2", + "kv_cache_dtype": "fp8_e4m3", + "mem_fraction_static": 0.8, + "quantization": "mxfp4", + "request_extra": { + "add_special_tokens": false, + "ignore_eos": true, + "skip_special_tokens": false, + "stream_options": { + "include_usage": true + } + } + }, + "tensorrt_llm": { + "backend": "pytorch", + "container_name": "llmbench-tensorrt-llm", + "container_port": 8000, + "dtype": "bfloat16", + "extra_args": [], + "host_port": 8001, + "image": "nvcr.io/nvidia/tensorrt-llm/release:1.3.0rc21", + "kv_cache_dtype": "fp8", + "kv_cache_free_gpu_memory_fraction": 0.8, + "max_batch_size": 4, + "max_num_tokens": 2048, + "quantization": "mxfp4", + "request_extra": { + "add_special_tokens": false, + "ignore_eos": true, + "skip_special_tokens": false, + "stream_options": { + "include_usage": true + } + } + }, + "vllm": { + "container_name": "llmbench-vllm", + "container_port": 8000, + "dtype": "bfloat16", + "extra_args": [], + "generation_config": "vllm", + "gpu_memory_utilization": 0.8, + "host_port": 8000, + "image": "nvcr.io/nvidia/vllm:26.06-py3", + "kv_cache_dtype": "fp8_e4m3", + "kv_cache_dtype_skip_layers": "sliding_window", + "max_num_batched_tokens": 8192, + "quantization": "mxfp4", + "request_extra": { + "add_special_tokens": false, + "ignore_eos": true, + "skip_special_tokens": false, + "stream_options": { + "include_usage": true + } + } + } + }, + "normalization": { + "controlled_distractor_min_chars": 640000, + "extra_source_tokens": 4096, + "instruction_reserve_tokens": 1024, + "max_source_context_chars": 4000000, + "prefix_boundary_candidates": [ + "\u001e", + "\n\u001e\n", + "\n\n<<>>\n", + "\n--- UNIQUE SUFFIX ---\n", + " \u00a7 " + ], + "validation_first_tokens": 256 + }, + "paths": { + "data_dir": "/home/ramsred/projects/llm-engine-benchmark/data", + "hf_cache_dir": "/home/ramsred/.cache/huggingface", + "lock_file": "/home/ramsred/projects/llm-engine-benchmark/experiment.lock.json", + "results_dir": "/home/ramsred/projects/llm-engine-benchmark/results", + "sglang_cache_dir": "/home/ramsred/.cache/sglang", + "triton_cache_dir": "/home/ramsred/.cache/triton", + "vllm_cache_dir": "/home/ramsred/.cache/vllm" + }, + "project": { + "cache_modes": [ + "cold" + ], + "concurrency": [ + 1, + 2, + 4 + ], + "context_length": 131072, + "cooldown_seconds": 60, + "engines": [ + "tensorrt_llm" + ], + "gpus": "all", + "input_tokens": 120000, + "model": "openai/gpt-oss-20b", + "model_revision": null, + "output_tokens": 512, + "readiness_timeout_seconds": 3600, + "repetitions": 3, + "request_timeout_seconds": 3600, + "require_server_token_usage": true, + "run_order": "alternate", + "samples": 100, + "save_outputs": true, + "seed": 20250308, + "shared_prefix_tokens": 100000, + "tokenizer_revision": null, + "trust_remote_code": false, + "warm_groups": 10 + }, + "sources": { + "infinitebench": { + "repo_id": "xinrongzhang2022/InfiniteBench", + "revision": "main" + }, + "longbench_v2": { + "repo_id": "THUDM/LongBench-v2", + "revision": "main" + }, + "ruler": { + "fetch_upstream_source": true, + "repo_url": "https://github.com/NVIDIA/RULER.git", + "revision": "main" + } + }, + "telemetry": { + "enabled": true, + "interval_seconds": 1.0, + "nvidia_dmon": true, + "pidstat": true, + "psutil": true + } + }, + "context_measurement_protocol_version": 1, + "context_prompt_format_version": 3, + "lock": { + "created_at": "2026-07-18T01:48:57+00:00", + "datasets": { + "infinitebench": { + "commit_sha": "90f0394333616266d9fe85824ceaf505093cbaa5", + "repo_id_requested": "xinrongzhang2022/InfiniteBench", + "repo_id_resolved": "xinrongzhang2022/InfiniteBench", + "revision_requested": "main" + }, + "longbench_v2": { + "commit_sha": "2b48e494f2c7a2f0af81aae178e05c7e1dde0fe9", + "repo_id_requested": "THUDM/LongBench-v2", + "repo_id_resolved": "zai-org/LongBench-v2", + "revision_requested": "main" + } + }, + "format_version": 1, + "model": { + "commit_sha": "6cee5e81ee83917806bbde320786a8fb61efebee", + "repo_id": "openai/gpt-oss-20b", + "revision_requested": "main", + "tokenizer_commit_sha": "6cee5e81ee83917806bbde320786a8fb61efebee", + "tokenizer_revision_requested": "main" + }, + "sources": { + "ruler": { + "commit_sha": "38da79d79519ef87aa46ae804f838e1eab7f86d7", + "generation_mode": "neutral_builtin_task_families", + "repo_url": "https://github.com/NVIDIA/RULER.git", + "revision_requested": "main" + } + } + }, + "profile_nsys": false, + "samples": 20, + "scope": "context_characterization_no_quality_or_production_capacity_claim", + "source_sha256": { + "/home/ramsred/projects/llm-engine-benchmark/data/canonical/manifest.jsonl": "bb239d19d15dc07f39cf5892d273bf4656ef4f7bb6dfccd266d530c6d78d67c7", + "/home/ramsred/projects/llm-engine-benchmark/data/canonical/manifest_metadata.json": "53b8b388b4faa6a650e2d4e591bb5c465b2d46dacbacdd08fc2a0d92f66d9dd8", + "/home/ramsred/projects/llm-engine-benchmark/experiment.lock.json": "db0478cc4b9611d98116393752ecf0ee93d2d766aed28a4472ba766f46f2f3e3" + }, + "warmup_waves": 2 + }, + "decision": { + "accepted_cells": 8, + "complete": true, + "expected_cells": 8, + "missing_cells": [], + "status": "complete_discovery" + }, + "generated_at": "2026-09-11T14:45:30.697756+00:00", + "generated_by": "llm_engine_benchmark.context_analysis", + "source_roots": [ + "results/context-scaling/discovery-01", + "results/context-scaling/discovery-01-recovery-120k-c1", + "results/context-scaling/discovery-01-recovery-32k-c4" + ], + "source_sha256": { + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-120k-c1/context_plan.json": "97a2cecac73a360d626af34b43681fd55dd25e6a275c24b1f5ffb42beebe08f3", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-120k-c1/image_identity.json": "a2a22e8cea99bbc7c81f887633d593e1d70affe067f6c2e1e7762ce77d39450f", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-120k-c1/input_120000/c1/run_01/client_results.json": "666c2755f3b8e24ce176a60c6d6050ddb7cce19e29f0ac58ebdf883070044ccf", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-120k-c1/input_120000/c1/run_01/context_metadata.json": "85d29c81ea8e84eb9537e8cd3903ddf83e8eb349d64302ad63f7ce187789d2e7", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-120k-c1/input_120000/c1/run_01/request_timings.jsonl": "388a7bab24b4923955a3c550fb3283526d5cb0194b686dede0d594b60885a776", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-32k-c4/context_plan.json": "a761cc25b612cfcde5efe4965ef3dd0947d9a3e2aba4bddfcac9f57215c68661", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-32k-c4/image_identity.json": "a2a22e8cea99bbc7c81f887633d593e1d70affe067f6c2e1e7762ce77d39450f", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-32k-c4/input_32000/c4/run_01/client_results.json": "bbe717211c841b62139f4b2c7881b54f8351fd57fb959fbfdaf9fa4009375f77", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-32k-c4/input_32000/c4/run_01/context_metadata.json": "6221c74a42ec4f3f22b3b9fb1c306958bd2c7936f940cc14f1800b5611d952c8", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-32k-c4/input_32000/c4/run_01/request_timings.jsonl": "eb088bc22b4d79ba36a2514963a930e6fef41a5173a7fd89518ad245f90e24c0", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/context_plan.json": "0e3a16679248905cad8fc813b6c03a9b30575d0024436dc5d6c4fa41e1d2f8cc", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/image_identity.json": "a2a22e8cea99bbc7c81f887633d593e1d70affe067f6c2e1e7762ce77d39450f", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_120000/c4/run_01/client_results.json": "e96392f4b78dffc0604d67a043240b32580bbf0169a5cd48055846f6c9f2b1be", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_120000/c4/run_01/context_metadata.json": "5013d4417f6a7499105e046f0d6d45df200b47d3faf33a491f46d67d9cac4f71", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_120000/c4/run_01/request_timings.jsonl": "2f3881600f29f53b45fc9eb33e3ac783ee7f01449af5e9f3e621288fcd9dd3a6", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_32000/c1/run_01/client_results.json": "fefb52452d447cb56ab9a9e1d116a0a1ccf13808a2e19726f75832595086e256", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_32000/c1/run_01/context_metadata.json": "7e4949961a044fc12e048189fd9e0dd6366c74906c6b6b77f6791205b4b5fa62", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_32000/c1/run_01/request_timings.jsonl": "fd856b88c1afb864d954f7509dda4d241ff2c2f5a350ccdf79b95fee17d5b624", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_64000/c1/run_01/client_results.json": "e637f7000ee7b0d188bc4a0b9d0c486eb0f2cc3bf41964977eeb3028a079e6ab", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_64000/c1/run_01/context_metadata.json": "da2d4ac7bc8ffdc0eb02781abbfd8d067c0b7e32b8d0ed24a2003153a304863b", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_64000/c1/run_01/request_timings.jsonl": "b0587b0b577fefaec230577be9b86ca975279b47fb089c02a96ee2e0f65ac364", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_64000/c4/run_01/client_results.json": "3f85494270ca3ea1f585a4d550776df2428e9332637acb4cc24bec93e32356ff", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_64000/c4/run_01/context_metadata.json": "280992826f2e172c2392b048b16915f583de67e44f5bcb1df96791ae793fe47f", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_64000/c4/run_01/request_timings.jsonl": "52c587cc344d3f0780b838d37aad50d7528467df0f0ac18c7ca302a0e56ed91d", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_8000/c1/run_01/client_results.json": "ec0925b26cd03835e34504c2a4a59bcb71d44baf32fcaf79567a19b928b75850", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_8000/c1/run_01/context_metadata.json": "aba3b09ff315aebd2323a8db67fb207db5e89394551756cc0e9447b450cb97d2", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_8000/c1/run_01/request_timings.jsonl": "5bbbedf165bf3e6de3c11c90bd5c3cb800682b0f6904a303df54fbfecc681d1c", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_8000/c4/run_01/client_results.json": "2d9a47b1edeb8c3958797e91a874ab6defeddf2ae7a2b493109391e714ecb5b8", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_8000/c4/run_01/context_metadata.json": "727c753e26dda81d2e6fedd9245a5c7cb8e9d91682796bd773a6f2c219c9ffcb", + "/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_8000/c4/run_01/request_timings.jsonl": "a9c187ae98215eefaf55536fc3a2f9a6989fb82e8c1d9b07b804eae61003a745" + } +} diff --git a/results/summaries/tensorrt-llm-context-scaling-validation.csv b/results/summaries/tensorrt-llm-context-scaling-validation.csv new file mode 100644 index 0000000..bea86dd --- /dev/null +++ b/results/summaries/tensorrt-llm-context-scaling-validation.csv @@ -0,0 +1,9 @@ +input_tokens,concurrency,repetition,valid,successful_requests,cached_prompt_tokens,ttft_p50_seconds,ttft_p95_seconds,itl_p50_seconds,itl_p95_seconds,tpot_mean_seconds,e2e_p95_seconds,output_tok_s,request_rps,max_observed_itl_seconds,source +8000,1,1,True,20,0,0.8683026194921695,0.8790319364226888,0.021570645971223712,0.022632111533312127,0.021679680080345782,11.966103379300328,42.859387261319874,0.08370974074476538,0.029624207993038,/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_8000/c1/run_01/client_results.json +8000,4,1,True,20,0,1.343030609015841,2.6607450225623333,0.036824477021582425,0.040421214699745175,0.04013310125254372,23.643211058177986,93.22760627045419,0.18208516849698084,0.2527518030256033,/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_8000/c4/run_01/client_results.json +32000,1,1,True,20,0,5.483334659482352,5.530747614050051,0.023404168023262173,0.024499797041062265,0.023466468344254823,17.522331217926695,29.31395128119104,0.05725381109607625,0.030653067980892956,/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_32000/c1/run_01/client_results.json +32000,4,1,True,20,0,7.172367456485517,16.97373967190506,0.04216973506845534,0.30587352316360933,0.06706593604205921,52.227827880793484,48.01142400455576,0.09377231250889796,1.0240221410058439,/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-32k-c4/input_32000/c4/run_01/client_results.json +64000,1,1,True,20,0,16.729392216482665,16.864388378389414,0.025988624489400536,0.027125421579694376,0.026004689350624437,30.145835497952067,17.080990814090523,0.03336131018377055,0.03614521399140358,/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_64000/c1/run_01/client_results.json +64000,4,1,True,20,0,21.17170663550496,51.80691897215439,0.048724170483183116,0.6628684827534016,0.12701292424286176,120.51620164624184,22.782802038847272,0.04449766023212358,0.8965168279828504,/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_64000/c4/run_01/client_results.json +120000,1,1,True,20,0,49.91526076052105,50.049579040525714,0.029938396997749805,0.03109557138523087,0.029949915104517406,65.36112847918993,7.859817412324401,0.015351205883446096,0.06044922594446689,/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01-recovery-120k-c1/input_120000/c1/run_01/client_results.json +120000,4,1,True,20,0,57.204304405953735,146.1482956571854,0.06257847597589716,1.2251458650745901,0.29305360684557014,305.9892580691551,9.361855329480598,0.018284873690391792,1.495877823093906,/home/ramsred/projects/llm-engine-benchmark/results/context-scaling/discovery-01/input_120000/c4/run_01/client_results.json diff --git a/scripts/analyze_context_scaling.py b/scripts/analyze_context_scaling.py new file mode 100755 index 0000000..bb76654 --- /dev/null +++ b/scripts/analyze_context_scaling.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Consolidate context-scaling campaigns into auditable evidence.""" + +from llm_engine_benchmark.context_analysis import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/run_context_scaling.py b/scripts/run_context_scaling.py new file mode 100644 index 0000000..48e32e3 --- /dev/null +++ b/scripts/run_context_scaling.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Opt-in context characterization; does not invoke the canonical preparation pipeline.""" + +from llm_engine_benchmark.context_scaling import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/llm_engine_benchmark/context_analysis.py b/src/llm_engine_benchmark/context_analysis.py new file mode 100644 index 0000000..232b618 --- /dev/null +++ b/src/llm_engine_benchmark/context_analysis.py @@ -0,0 +1,439 @@ +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +import statistics +import subprocess +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from .util import BenchmarkError + + +@dataclass(frozen=True) +class ContextEvidence: + input_tokens: int + concurrency: int + repetition: int + valid: bool + successful_requests: int + cached_prompt_tokens: int + ttft_p50_seconds: float + ttft_p95_seconds: float + itl_p50_seconds: float + itl_p95_seconds: float + tpot_mean_seconds: float + e2e_p95_seconds: float + output_tok_s: float + request_rps: float + max_observed_itl_seconds: float + source: str + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _git_commit() -> str: + try: + return subprocess.check_output( + ["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL + ).strip() + except (OSError, subprocess.CalledProcessError): + return "unknown" + + +def _read(path: Path) -> dict[str, Any]: + if not path.is_file(): + raise BenchmarkError(f"Required context artifact is missing: {path}") + value = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(value, dict): + raise BenchmarkError(f"Expected a JSON object: {path}") + return value + + +def _nested_float(value: Mapping[str, Any], *keys: str) -> float: + current: Any = value + for key in keys: + if not isinstance(current, Mapping) or key not in current: + raise BenchmarkError(f"Missing context result field: {'.'.join(keys)}") + current = current[key] + result = float(current) + if not math.isfinite(result) or result < 0: + raise BenchmarkError(f"Invalid context metric {'.'.join(keys)}: {result}") + return result + + +def _compatibility(plan: Mapping[str, Any]) -> dict[str, Any]: + options = plan.get("options") or {} + return { + "source_sha256": plan.get("source_sha256"), + "lock": plan.get("lock"), + "config": plan.get("config"), + "scope": plan.get("scope"), + "context_prompt_format_version": plan.get("context_prompt_format_version"), + "context_measurement_protocol_version": plan.get( + "context_measurement_protocol_version", 1 + ), + "samples": options.get("samples"), + "warmup_waves": options.get("warmup_waves"), + "profile_nsys": options.get("profile_nsys"), + } + + +def _timing_max(path: Path) -> float: + maximum: float | None = None + if not path.is_file(): + raise BenchmarkError(f"Context timing evidence is missing: {path}") + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + row = json.loads(line) + for gap in row.get("itl_seconds", []): + value = float(gap) + if not math.isfinite(value) or value < 0: + raise BenchmarkError(f"Invalid ITL timing evidence: {path}") + maximum = value if maximum is None else max(maximum, value) + if maximum is None: + raise BenchmarkError(f"No ITL timing evidence found: {path}") + return maximum + + +def load_context_evidence( + source_roots: Sequence[Path], +) -> tuple[list[ContextEvidence], list[Path], dict[str, Any]]: + rows: list[ContextEvidence] = [] + inputs: list[Path] = [] + compatibility: dict[str, Any] | None = None + seen: dict[tuple[int, int, int], Path] = {} + request_hashes: dict[int, str] = {} + image_digest: str | None = None + for root in source_roots: + root = root.resolve() + plan_path = root / "context_plan.json" + plan = _read(plan_path) + current = _compatibility(plan) + if compatibility is None: + compatibility = current + elif current != compatibility: + raise BenchmarkError(f"Incompatible context experiment source: {root}") + identity_path = root / "image_identity.json" + identity = _read(identity_path) + current_digest = str(identity.get("image_digest") or "") + if not current_digest: + raise BenchmarkError(f"Missing image digest: {identity_path}") + if image_digest is None: + image_digest = current_digest + elif current_digest != image_digest: + raise BenchmarkError(f"Context image digest differs: {root}") + inputs.extend((plan_path, identity_path)) + + for metadata_path in sorted(root.glob("input_*/c*/run_*/context_metadata.json")): + metadata = _read(metadata_path) + if metadata.get("status") != "accepted": + continue + run_dir = metadata_path.parent + result_path = run_dir / "client_results.json" + timings_path = run_dir / "request_timings.jsonl" + result = _read(result_path) + tokens = int(metadata["input_tokens"]) + concurrency = int(metadata["concurrency"]) + repetition = int(metadata["repetition"]) + key = (tokens, concurrency, repetition) + if key in seen: + raise BenchmarkError( + f"Duplicate accepted context cell {key}: {seen[key]} and {run_dir}" + ) + seen[key] = run_dir + expected = int(current["samples"]) + if result.get("valid") is not True: + raise BenchmarkError(f"Accepted context result is invalid: {result_path}") + if int(result.get("successful_requests", -1)) != expected: + raise BenchmarkError(f"Context request count differs: {result_path}") + if int(result.get("failed_requests", 0)) != 0: + raise BenchmarkError(f"Context result contains failed requests: {result_path}") + if int(result.get("server_reported_prompt_token_coverage_requests", -1)) != expected: + raise BenchmarkError(f"Context token-usage coverage differs: {result_path}") + cached = int(result.get("server_reported_cached_prompt_tokens_total", 0)) + if cached != 0: + raise BenchmarkError(f"Context cold run contains cached tokens: {result_path}") + request_hash = str(metadata.get("requests_sha256") or "") + if not request_hash: + raise BenchmarkError(f"Context measured prompt hash is missing: {metadata_path}") + previous_hash = request_hashes.setdefault(tokens, request_hash) + if previous_hash != request_hash: + raise BenchmarkError( + f"Measured prompts differ between sources at {tokens} tokens" + ) + if metadata.get("image_digest") != image_digest: + raise BenchmarkError(f"Context cell image digest differs: {metadata_path}") + rows.append( + ContextEvidence( + input_tokens=tokens, + concurrency=concurrency, + repetition=repetition, + valid=True, + successful_requests=expected, + cached_prompt_tokens=cached, + ttft_p50_seconds=_nested_float(result, "ttft_seconds", "p50"), + ttft_p95_seconds=_nested_float(result, "ttft_seconds", "p95"), + itl_p50_seconds=_nested_float(result, "itl_seconds", "p50"), + itl_p95_seconds=_nested_float(result, "itl_seconds", "p95"), + tpot_mean_seconds=_nested_float(result, "tpot_seconds", "mean"), + e2e_p95_seconds=_nested_float(result, "e2e_seconds", "p95"), + output_tok_s=_nested_float( + result, "output_throughput_tokens_per_second" + ), + request_rps=_nested_float(result, "request_throughput_per_second"), + max_observed_itl_seconds=_timing_max(timings_path), + source=str(result_path), + ) + ) + inputs.extend((metadata_path, result_path, timings_path)) + return rows, inputs, compatibility or {} + + +def _mean(rows: Sequence[ContextEvidence], field: str) -> float: + return statistics.mean(float(getattr(row, field)) for row in rows) + + +def _stdev(rows: Sequence[ContextEvidence], field: str) -> float: + values = [float(getattr(row, field)) for row in rows] + return statistics.stdev(values) if len(values) > 1 else 0.0 + + +def classify_context_evidence( + rows: Sequence[ContextEvidence], + lengths: Sequence[int], + concurrencies: Sequence[int], + repetitions: int, +) -> dict[str, Any]: + expected = { + (length, concurrency, repetition) + for length in lengths + for concurrency in concurrencies + for repetition in range(1, repetitions + 1) + } + observed = {(row.input_tokens, row.concurrency, row.repetition) for row in rows} + unexpected = sorted(observed - expected) + missing = sorted(expected - observed) + if unexpected: + raise BenchmarkError(f"Unexpected context cells were loaded: {unexpected}") + complete = not missing + return { + "status": ( + "complete_repeated_validation" + if complete and repetitions >= 3 + else "complete_discovery" + if complete + else "incomplete" + ), + "complete": complete, + "expected_cells": len(expected), + "accepted_cells": len(observed), + "missing_cells": [ + {"input_tokens": length, "concurrency": concurrency, "repetition": repetition} + for length, concurrency, repetition in missing + ], + } + + +def _write_csv(path: Path, rows: Sequence[ContextEvidence]) -> None: + fields = list(asdict(rows[0])) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for row in sorted( + rows, key=lambda item: (item.input_tokens, item.concurrency, item.repetition) + ): + writer.writerow(asdict(row)) + + +def _write_markdown( + path: Path, + rows: Sequence[ContextEvidence], + lengths: Sequence[int], + concurrencies: Sequence[int], + repetitions: int, + decision: Mapping[str, Any], +) -> None: + lines = [ + "# TensorRT-LLM Context-Scaling Analysis", + "", + f"- Evidence status: **{decision['status']}**.", + f"- Accepted cells: {decision['accepted_cells']} / {decision['expected_cells']}.", + f"- Repetitions expected per cell: {repetitions}.", + "- Controlled closed-loop cold-prefix characterization; not production capacity.", + "", + "## Context matrix", + "", + ( + "| Input tokens | C | Runs | TTFT P95 | ITL P95 | E2E P95 | " + "Output tok/s |" + ), + "| ---: | ---: | ---: | ---: | ---: | ---: | ---: |", + ] + grouped: dict[tuple[int, int], list[ContextEvidence]] = {} + for row in rows: + grouped.setdefault((row.input_tokens, row.concurrency), []).append(row) + for length in sorted(lengths): + for concurrency in sorted(concurrencies): + selected = grouped.get((length, concurrency), []) + if not selected: + lines.append(f"| {length} | {concurrency} | 0 | — | — | — | — |") + continue + + def metric( + field: str, suffix: str = "", selected=selected + ) -> str: + mean = _mean(selected, field) + if len(selected) > 1: + return f"{mean:.3f} ± {_stdev(selected, field):.3f}{suffix}" + return f"{mean:.3f}{suffix}" + + lines.append( + f"| {length} | {concurrency} | {len(selected)} | " + f"{metric('ttft_p95_seconds', ' s')} | " + f"{metric('itl_p95_seconds', ' s')} | " + f"{metric('e2e_p95_seconds', ' s')} | {metric('output_tok_s')} |" + ) + lines.extend(["", "## Concurrency effect", ""]) + if 1 in concurrencies and 4 in concurrencies: + lines.extend( + [ + "| Input tokens | TTFT C4/C1 | ITL C4/C1 | E2E C4/C1 | Throughput C4/C1 |", + "| ---: | ---: | ---: | ---: | ---: |", + ] + ) + for length in sorted(lengths): + c1 = grouped.get((length, 1), []) + c4 = grouped.get((length, 4), []) + if not c1 or not c4: + continue + ttft_ratio = _mean(c4, "ttft_p95_seconds") / _mean(c1, "ttft_p95_seconds") + itl_ratio = _mean(c4, "itl_p95_seconds") / _mean(c1, "itl_p95_seconds") + e2e_ratio = _mean(c4, "e2e_p95_seconds") / _mean(c1, "e2e_p95_seconds") + throughput_ratio = _mean(c4, "output_tok_s") / _mean(c1, "output_tok_s") + lines.append( + f"| {length} | {ttft_ratio:.2f}× | {itl_ratio:.2f}× | " + f"{e2e_ratio:.2f}× | {throughput_ratio:.2f}× |" + ) + lines.extend(["", "## Interpretation guardrails", ""]) + if repetitions == 1: + lines.append( + "- This is complete discovery evidence, but one run per cell does not establish " + "repeatability or confidence intervals." + ) + if decision["missing_cells"]: + lines.append(f"- Missing cells: `{json.dumps(decision['missing_cells'])}`.") + lines.extend( + [ + ( + "- P95 values are per-run summaries; averaging repeated P95 values is not " + "a pooled percentile." + ), + ( + "- Concurrency ratios describe this fixed workload and do not identify a " + "kernel-level cause." + ), + ( + "- Use separate Nsight runs before attributing changes to attention, KV memory, " + "or scheduling." + ), + "", + ] + ) + path.write_text("\n".join(lines), encoding="utf-8") + + +def generate_context_analysis( + *, + source_roots: Sequence[Path], + lengths: Sequence[int], + concurrencies: Sequence[int], + repetitions: int, + output_dir: Path, +) -> dict[str, Path]: + if repetitions < 1: + raise BenchmarkError("repetitions must be at least one") + if not lengths or not concurrencies: + raise BenchmarkError("lengths and concurrencies must not be empty") + rows, inputs, compatibility = load_context_evidence(source_roots) + if not rows: + raise BenchmarkError("No accepted context evidence was loaded") + decision = classify_context_evidence(rows, lengths, concurrencies, repetitions) + output_dir.mkdir(parents=True, exist_ok=True) + outputs = { + "summary": output_dir / "tensorrt-llm-context-scaling-validation.csv", + "report": output_dir / "tensorrt-llm-context-scaling-analysis.md", + "provenance": output_dir / "tensorrt-llm-context-scaling-provenance.json", + } + _write_csv(outputs["summary"], rows) + _write_markdown( + outputs["report"], rows, lengths, concurrencies, repetitions, decision + ) + outputs["provenance"].write_text( + json.dumps( + { + "generated_at": datetime.now(timezone.utc).isoformat(), + "generated_by": "llm_engine_benchmark.context_analysis", + "benchmark_commit": _git_commit(), + "source_roots": [str(path) for path in source_roots], + "source_sha256": {str(path): _sha256(path) for path in sorted(set(inputs))}, + "compatibility": compatibility, + "decision": decision, + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + return outputs + + +def _parse_ints(value: str) -> tuple[int, ...]: + try: + parsed = tuple(int(item.strip()) for item in value.split(",")) + except ValueError as exc: + raise argparse.ArgumentTypeError("Expected comma-separated integers") from exc + if not parsed: + raise argparse.ArgumentTypeError("Expected comma-separated integers") + return parsed + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Consolidate context-scaling campaigns") + parser.add_argument("--source", action="append", type=Path, required=True) + parser.add_argument("--lengths", type=_parse_ints, default=(8000, 32000, 64000, 120000)) + parser.add_argument("--concurrency", type=_parse_ints, default=(1, 4)) + parser.add_argument("--repetitions", type=int, default=1) + parser.add_argument("--output-dir", type=Path, default=Path("results/summaries")) + args = parser.parse_args(argv) + try: + outputs = generate_context_analysis( + source_roots=args.source, + lengths=args.lengths, + concurrencies=args.concurrency, + repetitions=args.repetitions, + output_dir=args.output_dir, + ) + except (BenchmarkError, ValueError, KeyError, json.JSONDecodeError) as exc: + parser.error(str(exc)) + for label, path in outputs.items(): + print(f"{label}: {path}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/llm_engine_benchmark/context_scaling.py b/src/llm_engine_benchmark/context_scaling.py new file mode 100644 index 0000000..4cea0c7 --- /dev/null +++ b/src/llm_engine_benchmark/context_scaling.py @@ -0,0 +1,900 @@ +"""Isolated, fixed-length closed-loop characterization, not production capacity. + +Only reads the existing lock and canonical manifest. All derived data and runtime +artifacts belong to an owned output directory. Resume is fail-closed and never +overwrites an accepted cell. +""" + +from __future__ import annotations + +import argparse +import copy +import csv +import json +import math +import random +import socket +import string +import subprocess +import time +import uuid +from dataclasses import asdict, dataclass +from pathlib import Path + +from .client import ClientRunOptions, run_benchmark_client +from .config import PROJECT_ROOT, load_config, validate_config +from .datasets import _canonical_manifest_reuse_error, manifest_signature +from .environment import capture_environment +from .locking import _validate_lock, _validate_lock_against_config +from .metrics import write_metrics_diff +from .normalize import ( + _build_cold_records, + encode, + fit_variable_segment, + instruction_suffix_with_budget, + load_pinned_tokenizer, +) +from .orchestrator import select_stratified_records +from .server import DockerEngineServer +from .telemetry import TelemetrySession +from .util import ( + BenchmarkError, + atomic_write_json, + atomic_write_text, + load_json, + read_jsonl, + redact_mapping, + sha256_file, + sha256_text, + sha256_token_ids, + utc_now, + write_jsonl, +) + + +@dataclass(frozen=True) +class ContextOptions: + output_dir: Path + lengths: tuple[int, ...] = (8000, 32000, 64000, 120000) + concurrencies: tuple[int, ...] = (1, 4) + samples: int = 20 + repetitions: int = 1 + warmup_waves: int = 2 + cooldown_seconds: float = 60.0 + skip_image_pull: bool = False + profile_nsys: bool = False + dry_run: bool = False + resume: bool = False + + +@dataclass(frozen=True) +class ContextCell: + input_tokens: int + concurrency: int + repetition: int + + @property + def relative_dir(self) -> Path: + return Path(f"input_{self.input_tokens}/c{self.concurrency}/run_{self.repetition:02d}") + + +CONTEXT_PROMPT_FORMAT_VERSION = 3 +CONTEXT_MEASUREMENT_PROTOCOL_VERSION = 1 + + +def _json_compatible(value): + """Return the representation used by JSON artifacts for stable comparisons.""" + return json.loads(json.dumps(value, default=str)) + + +def _context_contract( + config: dict, + lock: dict, + hashes: dict, + plan: list[ContextCell], + options: ContextOptions, + root: Path, +) -> dict: + return { + "source_sha256": hashes, + "lock": lock, + "config": redact_mapping(config), + "runs": [asdict(cell) for cell in plan], + "options": { + "output_dir": str(root), + "lengths": list(options.lengths), + "concurrencies": list(options.concurrencies), + "samples": options.samples, + "repetitions": options.repetitions, + "warmup_waves": options.warmup_waves, + "cooldown_seconds": options.cooldown_seconds, + "skip_image_pull": options.skip_image_pull, + "profile_nsys": options.profile_nsys, + "dry_run": False, + }, + "scope": "context_characterization_no_quality_or_production_capacity_claim", + "context_prompt_format_version": CONTEXT_PROMPT_FORMAT_VERSION, + "context_measurement_protocol_version": CONTEXT_MEASUREMENT_PROTOCOL_VERSION, + } + + +def _contract_signature(contract: dict) -> str: + serialized = json.dumps( + _json_compatible(contract), sort_keys=True, separators=(",", ":") + ) + return sha256_text(serialized) + + +def _validate_resume_contract(root: Path, expected: dict) -> dict: + plan_path = root / "context_plan.json" + if not plan_path.is_file(): + raise BenchmarkError("Resume requires the original context_plan.json") + recorded = load_json(plan_path) + for key in ("source_sha256", "lock", "config", "runs", "scope"): + if _json_compatible(recorded.get(key)) != _json_compatible(expected[key]): + raise BenchmarkError(f"Resume experiment mismatch: {key}") + recorded_format = recorded.get("context_prompt_format_version") + if recorded_format != expected["context_prompt_format_version"]: + raise BenchmarkError("Resume experiment mismatch: context prompt format") + recorded_protocol = recorded.get( + "context_measurement_protocol_version", CONTEXT_MEASUREMENT_PROTOCOL_VERSION + ) + if recorded_protocol != expected["context_measurement_protocol_version"]: + raise BenchmarkError("Resume experiment mismatch: measurement protocol") + recorded_options = recorded.get("options") or {} + for key, value in expected["options"].items(): + if _json_compatible(recorded_options.get(key)) != _json_compatible(value): + raise BenchmarkError(f"Resume experiment mismatch: option {key}") + recorded_signature = recorded.get("experiment_signature") + expected_signature = _contract_signature(expected) + if recorded_signature is not None and recorded_signature != expected_signature: + raise BenchmarkError("Resume experiment signature mismatch") + return recorded + + +def cell_config(config: dict, length: int) -> dict: + derived = copy.deepcopy(config) + derived["project"]["input_tokens"] = length + # Shared-prefix preparation is never invoked, but retain a valid config. + derived["project"]["shared_prefix_tokens"] = min( + int(config["project"]["shared_prefix_tokens"]), length - 1 + ) + validate_config(derived) + return derived + + +def build_context_plan(config: dict, options: ContextOptions) -> list[ContextCell]: + for name, values in (("lengths", options.lengths), ("concurrencies", options.concurrencies)): + if not values or len(set(values)) != len(values) or any(v <= 0 for v in values): + raise BenchmarkError(f"{name} must contain unique positive integers") + if not max(options.concurrencies) <= options.samples <= 100: + raise BenchmarkError("samples must be at least the largest concurrency and at most 100") + if options.repetitions < 1 or options.warmup_waves < 1: + raise BenchmarkError("repetitions and warmup-waves must be positive") + if not math.isfinite(options.cooldown_seconds) or options.cooldown_seconds < 0: + raise BenchmarkError("cooldown-seconds must be finite and nonnegative") + if max(options.concurrencies) > int(config["engines"]["tensorrt_llm"]["max_batch_size"]): + raise BenchmarkError("concurrency exceeds configured TensorRT-LLM max_batch_size") + for length in options.lengths: + cell_config(config, length) + pairs = [(length, c) for length in options.lengths for c in options.concurrencies] + random.Random(int(config["project"]["seed"])).shuffle(pairs) + return [ + ContextCell(length, concurrency, rep) + for rep in range(1, options.repetitions + 1) + for length, concurrency in (pairs if rep % 2 else list(reversed(pairs))) + ] + + +def allocate_context_prefixes(tokenizer, sources: list[dict], seed: int) -> dict[str, str]: + """Allocate prefixes by actual first token, jointly for an entire experiment set. + + Fixed-width decimal markers normally supply many distinct starting tokens. + Letter fallbacks support tokenizers with different number segmentation. This + deliberately checks the tokenizer rather than assuming either segmentation. + Exhaustion fails closed instead of accepting a collision or changing cache policy. + """ + sample_ids = sorted(str(source["sample_id"]) for source in sources) + if len(set(sample_ids)) != len(sample_ids): + raise BenchmarkError("Duplicate sample ID in context prefix allocation") + markers = iter([*(f"{i:03d}" for i in range(1000)), *string.ascii_letters]) + used: set[int] = set() + prefixes = {} + for sample_id in sample_ids: + nonce = sha256_text( + json.dumps( + { + "format": "context-prefix-v3", + "seed": seed, + "sample_id": sample_id, + }, + sort_keys=True, + ) + ) + for marker in markers: + prefix = marker + "\n" + nonce + "\n" + tokens = encode(tokenizer, prefix) + if tokens and tokens[0] not in used: + used.add(tokens[0]) + prefixes[sample_id] = prefix + break + else: + raise BenchmarkError("Tokenizer cannot supply enough distinct first-token prefixes") + return prefixes + + +def build_context_records(config: dict, tokenizer, sources: list[dict]) -> list[dict]: + """Add an early unique prefix without changing the legacy cold-prompt builder. + + The canonical builder starts every prompt with the same descriptive header. + A unique sample ID later in that header does not prevent reuse of its first + eight tokens. Even unrelated hashes may share their first token. Allocate + distinct first tokens before fitting; the caller must include measured and + warm-up sources together. Refit only the variable body to retain the exact + length and task suffix, then verify the fitted prompts together. + """ + records = _build_cold_records(config, tokenizer, sources) + target = int(config["project"]["input_tokens"]) + prefixes = allocate_context_prefixes(tokenizer, sources, int(config["project"]["seed"])) + for record, source in zip(records, sources, strict=True): + suffix, _ = instruction_suffix_with_budget(config, tokenizer, source) + old_prompt = record["prompt"] + if not old_prompt.endswith(suffix): + raise BenchmarkError("Cannot preserve instruction suffix during context prefix refit") + prompt, tokens, fit = fit_variable_segment( + tokenizer, + prefix=prefixes[str(record["sample_id"])], + segment_source=old_prompt[: -len(suffix)], + suffix=suffix, + target_tokens=target, + label=f"context-prefix:{record['sample_id']}", + ) + record["prompt"] = prompt + record["prompt_tokens"] = len(tokens) + record["metadata"].update( + { + "context_prompt_format_version": 3, + "first_token_id": tokens[0], + "context_prefix_refit": fit, + "prompt_sha256": sha256_text(prompt), + "first_256_token_sha256": sha256_token_ids(tokens[:256]), + } + ) + validate_prompt_set(tokenizer, records, target) + return records + + +def validate_prompt_set(tokenizer, records: list[dict], target: int) -> dict: + """Check exact retokenization and reject any shared first token. + + This is protocol evidence, not proof of engine cache hits/misses. Actual + cached-token usage, when available, is checked separately after execution. + """ + heads: set[tuple[int, ...]] = set() + ids: set[str] = set() + hashes = {} + for record in records: + tokens = encode(tokenizer, record["prompt"]) + if len(tokens) != target or record["prompt_tokens"] != target: + raise BenchmarkError(f"Incorrect token count: {record['sample_id']}") + head = tuple(tokens[:1]) + if head in heads or record["sample_id"] in ids: + raise BenchmarkError("Duplicate sample ID or shared first-token prefix") + heads.add(head) + ids.add(record["sample_id"]) + hashes[record["sample_id"]] = sha256_text(record["prompt"]) + return {"input_tokens": target, "unique_prefix_check_tokens": 1, "prompt_sha256": hashes} + + +def load_sources(config: dict) -> tuple[dict, list[dict], dict]: + lock_path = Path(config["paths"]["lock_file"]) + manifest = Path(config["paths"]["data_dir"]) / "canonical/manifest.jsonl" + metadata = manifest.with_name("manifest_metadata.json") + if not all(p.is_file() for p in (lock_path, manifest, metadata)): + raise BenchmarkError("Existing experiment.lock.json and canonical manifest required") + lock = load_json(lock_path) + _validate_lock(lock) + _validate_lock_against_config(lock, config) + error = _canonical_manifest_reuse_error( + manifest, metadata, signature=manifest_signature(config, lock) + ) + if error: + raise BenchmarkError(f"Canonical source validation failed: {error}") + records = list(read_jsonl(manifest)) + if len(records) != 100 or len({r["sample_id"] for r in records}) != 100: + raise BenchmarkError("Expected 100 unique canonical source records") + return lock, records, {str(p): sha256_file(p) for p in (lock_path, manifest, metadata)} + + +def assert_idle(config: dict) -> None: + """Never remove another benchmark's container or run over an active GPU process.""" + for command in ( + ["docker", "ps", "--filter", "name=llmbench", "--format", "{{.Names}}"], + ["nvidia-smi", "--query-compute-apps=pid", "--format=csv,noheader,nounits"], + ): + result = subprocess.run(command, capture_output=True, text=True, check=True, timeout=30) + if result.stdout.strip(): + raise BenchmarkError(f"Host is not idle ({command[0]}): {result.stdout.strip()}") + port = int(config["engines"]["tensorrt_llm"]["host_port"]) + with socket.socket() as sock: + try: + sock.bind(("127.0.0.1", port)) + except OSError as exc: + raise BenchmarkError( + f"Port {port} is busy; no existing service will be stopped" + ) from exc + + +def accept_result(result: dict, expected: int) -> None: + if result.get("valid") is not True or result.get("successful_requests") != expected: + raise BenchmarkError("Client rejected request counts, outputs, or timing measurements") + if result.get("server_reported_prompt_token_coverage_requests") != expected: + raise BenchmarkError("Server input-token usage is required for every request") + if result.get("server_reported_cached_prompt_tokens_total", 0) != 0: + cached = result["server_reported_cached_prompt_tokens_total"] + raise BenchmarkError( + f"Observed prefix-cache reuse in a cold characterization run: {cached} cached tokens" + ) + + +def observed_concurrency(timings: Path) -> int: + events = [] + for row in read_jsonl(timings): + start = float(row["request_start_offset_seconds"]) + end = float(row["request_end_offset_seconds"]) + if not math.isfinite(start) or not math.isfinite(end) or end <= start: + raise BenchmarkError("Invalid request interval in concurrency evidence") + events.extend(((start, 1), (end, -1))) + active = peak = 0 + for _, delta in sorted(events): + active += delta + peak = max(peak, active) + return peak + + +def validate_prepared_context( + root: Path, + tokenizer, + options: ContextOptions, + selected: list[dict], + warm_sources: list[dict], +) -> None: + expected_measured_ids = [str(row["sample_id"]) for row in selected] + expected_warm_ids = [str(row["sample_id"]) for row in warm_sources] + for length in options.lengths: + directory = root / "prepared" / f"input_{length}" + measured_path = directory / "measured.jsonl" + warmup_path = directory / "warmup.jsonl" + validation_path = directory / "validation.json" + if not all(path.is_file() for path in (measured_path, warmup_path, validation_path)): + raise BenchmarkError(f"Resume prepared artifacts are incomplete for {length} tokens") + measured = list(read_jsonl(measured_path)) + warmups = list(read_jsonl(warmup_path)) + if [str(row["sample_id"]) for row in measured] != expected_measured_ids: + raise BenchmarkError(f"Resume measured sample IDs differ for {length} tokens") + if [str(row["sample_id"]) for row in warmups] != expected_warm_ids: + raise BenchmarkError(f"Resume warm-up sample IDs differ for {length} tokens") + checks = validate_prompt_set(tokenizer, measured + warmups, length) + if _json_compatible(load_json(validation_path)) != _json_compatible(checks): + raise BenchmarkError(f"Resume prompt validation differs for {length} tokens") + + +def accepted_cell_is_valid( + root: Path, + cell: ContextCell, + options: ContextOptions, + image_digest: str, +) -> bool: + run_dir = root / cell.relative_dir + if not run_dir.exists(): + return False + metadata_path = run_dir / "context_metadata.json" + if not metadata_path.is_file(): + return False + metadata = load_json(metadata_path) + if metadata.get("status") != "accepted": + return False + expected_metadata = { + "input_tokens": cell.input_tokens, + "concurrency": cell.concurrency, + "repetition": cell.repetition, + "profile_nsys": options.profile_nsys, + "context_prompt_format_version": CONTEXT_PROMPT_FORMAT_VERSION, + "image_digest": image_digest, + "warmup_waves": options.warmup_waves, + "warmup_requests_per_wave": cell.concurrency, + } + for key, value in expected_metadata.items(): + if metadata.get(key) != value: + raise BenchmarkError(f"Accepted resume cell metadata mismatch: {cell} field {key}") + prepared = root / "prepared" / f"input_{cell.input_tokens}" + expected_hashes = { + "requests_sha256": sha256_file(prepared / "measured.jsonl"), + "warmup_sha256": sha256_file(prepared / "warmup.jsonl"), + } + for key, value in expected_hashes.items(): + if metadata.get(key) != value: + raise BenchmarkError(f"Accepted resume cell input hash mismatch: {cell} field {key}") + result_path = run_dir / "client_results.json" + timings_path = run_dir / "request_timings.jsonl" + if not result_path.is_file() or not timings_path.is_file(): + raise BenchmarkError(f"Accepted resume cell artifacts are incomplete: {cell}") + accept_result(load_json(result_path), options.samples) + if observed_concurrency(timings_path) != cell.concurrency: + raise BenchmarkError(f"Accepted resume cell concurrency evidence differs: {cell}") + peaks = metadata.get("warmup_client_peak_concurrency") + if peaks != [cell.concurrency] * options.warmup_waves: + raise BenchmarkError(f"Accepted resume cell warm-up evidence differs: {cell}") + for wave in range(options.warmup_waves): + wave_dir = run_dir / "warmup" / f"wave_{wave + 1:02d}" + result_path = wave_dir / "client_results.json" + timings_path = wave_dir / "request_timings.jsonl" + if not result_path.is_file() or not timings_path.is_file(): + raise BenchmarkError(f"Accepted resume cell warm-up artifacts are incomplete: {cell}") + accept_result(load_json(result_path), cell.concurrency) + if observed_concurrency(timings_path) != cell.concurrency: + raise BenchmarkError(f"Accepted resume cell warm-up concurrency differs: {cell}") + if options.profile_nsys: + validation_path = run_dir / "profiling/cuda_trace_validation.json" + if not validation_path.is_file() or load_json(validation_path).get("valid") is not True: + raise BenchmarkError(f"Accepted resume cell CUDA validation is missing: {cell}") + return True + + +def archive_incomplete_cell(root: Path, cell: ContextCell) -> Path | None: + run_dir = root / cell.relative_dir + if not run_dir.exists(): + return None + attempt = f"attempt_{utc_now().replace(':', '').replace('+', '_')}_{uuid.uuid4().hex[:8]}" + destination = root / "interrupted" / cell.relative_dir / attempt + destination.parent.mkdir(parents=True, exist_ok=True) + run_dir.rename(destination) + return destination + + +def execute_cell(config, lock, tokenizer, cell, options, prepared, digest, root) -> dict: + run_dir = root / cell.relative_dir + run_dir.mkdir(parents=True, exist_ok=False) + derived = cell_config(config, cell.input_tokens) + # UUID ownership avoids DockerEngineServer's legacy stale-container cleanup + # ever targeting a container belonging to bench run/capacity or another run. + derived["engines"]["tensorrt_llm"]["container_name"] = f"llmbench-context-{uuid.uuid4().hex}" + server = DockerEngineServer( + engine="tensorrt_llm", + config=derived, + lock=lock, + run_dir=run_dir, + skip_image_pull=True, + profile_nsys=options.profile_nsys, + ) + server.image_digest = digest + telemetry = TelemetrySession(run_dir, derived.get("telemetry", {})) + metadata = { + **asdict(cell), + "started_at": utc_now(), + "status": "starting", + "profile_nsys": options.profile_nsys, + "context_prompt_format_version": 3, + "image_digest": digest, + "warmup_excluded_from_measurement": True, + "warmup_waves": options.warmup_waves, + "warmup_requests_per_wave": cell.concurrency, + "warmup_output_tokens": derived["project"]["output_tokens"], + "steady_state_limitation": "Representative warm-up, not proof of complete compilation", + "requests_sha256": sha256_file(prepared / "measured.jsonl"), + "warmup_sha256": sha256_file(prepared / "warmup.jsonl"), + } + atomic_write_json(run_dir / "context_metadata.json", metadata) + result = None + try: + assert_idle(derived) + server.start() + server.wait_ready(float(derived["project"]["readiness_timeout_seconds"])) + metadata["runtime_versions"] = server.capture_runtime_versions() + metadata["server_command"] = server.run_command + request_options = ClientRunOptions( + base_url=server.base_url, + model=server.api_model, + engine="tensorrt_llm", + cache_mode="cold", + concurrency=cell.concurrency, + output_tokens=int(derived["project"]["output_tokens"]), + request_timeout_seconds=float(derived["project"]["request_timeout_seconds"]), + request_extra=dict(derived["engines"]["tensorrt_llm"].get("request_extra", {})), + require_server_token_usage=True, + save_outputs=bool(derived["project"].get("save_outputs", True)), + ) + metadata["warmup_client_peak_concurrency"] = [] + for wave in range(options.warmup_waves): + wave_dir = run_dir / "warmup" / f"wave_{wave + 1:02d}" + warmup = run_benchmark_client( + records_path=prepared / "warmup.jsonl", + run_dir=wave_dir, + tokenizer=tokenizer, + options=request_options, + sample_ids=[f"w{wave}-{i}" for i in range(cell.concurrency)], + ) + accept_result(warmup, cell.concurrency) + peak = observed_concurrency(wave_dir / "request_timings.jsonl") + metadata["warmup_client_peak_concurrency"].append(peak) + if peak != cell.concurrency: + raise BenchmarkError("Warm-up did not exercise the requested client concurrency") + server.snapshot_metrics("metrics_before.prom") + telemetry.start() + try: + result = run_benchmark_client( + records_path=prepared / "measured.jsonl", + run_dir=run_dir, + tokenizer=tokenizer, + options=request_options, + sample_limit=options.samples, + ) + finally: + telemetry.stop() + server.snapshot_metrics("metrics_after.prom") + write_metrics_diff( + run_dir / "metrics_before.prom", + run_dir / "metrics_after.prom", + run_dir / "metrics_diff.json", + ) + accept_result(result, options.samples) + metadata["measured_client_peak_concurrency"] = observed_concurrency( + run_dir / "request_timings.jsonl" + ) + if metadata["measured_client_peak_concurrency"] != cell.concurrency: + raise BenchmarkError("Measurement did not exercise the requested client concurrency") + if not server.is_running(): + raise BenchmarkError("Server exited during measurement") + # Shutdown exports the profile; only accept after its CUDA validation. + server.stop() + if options.profile_nsys: + server.validate_profile_artifacts() + metadata["status"] = "accepted" + metadata["cache_evidence"] = ( + "observed_zero_cached_tokens" + if result.get("cache_report_coverage_fraction") == 1.0 + else "unique_prefix_protocol_only; cache usage not fully reported" + ) + return result + except BaseException as exc: + metadata["status"] = "failed" + metadata["error"] = f"{type(exc).__name__}: {exc}" + if result is not None: + result["valid"] = False + result.setdefault("validation_errors", []).append(metadata["error"]) + atomic_write_json(run_dir / "client_results.json", result) + raise + finally: + try: + telemetry.stop() + finally: + try: + if server.started: + server.stop() + finally: + metadata["finished_at"] = utc_now() + atomic_write_json(run_dir / "context_metadata.json", metadata) + + +def write_context_report( + root: Path, + plan: list[ContextCell], + profiled: bool, + *, + resumed: bool = False, + skipped_runs: int = 0, + archived_attempts: list[str] | None = None, +) -> dict: + rows = [] + for cell in plan: + run_dir = root / cell.relative_dir + metadata_path = run_dir / "context_metadata.json" + metadata = load_json(metadata_path) if metadata_path.exists() else {} + row = {**asdict(cell), "status": metadata.get("status", "not_run")} + result_path = run_dir / "client_results.json" + if row["status"] == "accepted" and result_path.is_file(): + result = load_json(result_path) + for metric, statistic in ( + ("ttft", "p50"), + ("ttft", "p95"), + ("itl", "p50"), + ("itl", "p95"), + ("tpot", "mean"), + ("e2e", "p95"), + ): + row[f"{metric}_{statistic}_seconds"] = result[f"{metric}_seconds"][statistic] + row["output_tok_s"] = result["output_throughput_tokens_per_second"] + row["request_rps"] = result["request_throughput_per_second"] + row["successful_requests"] = result["successful_requests"] + timings = read_jsonl(run_dir / "request_timings.jsonl") + row["max_observed_itl_seconds"] = max( + (gap for r in timings for gap in r.get("itl_seconds", [])), default=None + ) + rows.append(row) + fields = list(dict.fromkeys(key for row in rows for key in row)) + with (root / "context_summary.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + lines = [ + "# Context-length characterization", + "", + "Controlled closed-loop cold-prefix workload; not production capacity or answer quality.", + f"Profiled run: {profiled}. Do not combine profiled and unprofiled timings.", + "Concurrency-matched warm-up is excluded; full runtime stability is not proven.", + "Server context ceiling, output length and prefill budget are fixed across input lengths.", + "P95 values are per-run exploratory estimates, not pooled percentiles or P99 evidence.", + "ITL uses observed SSE timings; multiple tokens may share a timestamp.", + "Cache protocol checks are not a substitute for measured engine cache-hit evidence.", + "GPU/memory/thermal telemetry stays in each run directory; missing is not zero.", + "", + "| Input tokens | C | Rep | Status | TTFT P95 (s) | ITL P95 (s) | Output tok/s |", + "| ---: | ---: | ---: | --- | ---: | ---: | ---: |", + ] + for row in rows: + + def display(key, row=row): + value = row.get(key) + return "—" if value is None else f"{value:.3f}" + + lines.append( + f"| {row['input_tokens']} | {row['concurrency']} | {row['repetition']} | " + f"{row['status']} | {display('ttft_p95_seconds')} | " + f"{display('itl_p95_seconds')} | {display('output_tok_s')} |" + ) + atomic_write_text(root / "context_report.md", "\n".join(lines) + "\n") + summary = { + "planned_runs": len(plan), + "accepted_runs": sum(r["status"] == "accepted" for r in rows), + "resumed": resumed, + "skipped_accepted_runs": skipped_runs, + "archived_incomplete_attempts": archived_attempts or [], + "finished_at": utc_now(), + "report": str(root / "context_report.md"), + } + atomic_write_json(root / "context_status.json", summary) + return summary + + +def run_context_scaling(config: dict, options: ContextOptions) -> dict: + plan = build_context_plan(config, options) + if options.dry_run: + return { + "dry_run": True, + "planned_runs": len(plan), + "runs": [asdict(cell) for cell in plan], + "output_dir": str(options.output_dir.resolve()), + "warmup_requests_per_cell": f"{options.warmup_waves} * concurrency", + } + root = options.output_dir.resolve() + if root.exists() and not options.resume: + raise BenchmarkError( + "Output directory already exists; choose a new directory or use --resume" + ) + if options.resume and not root.is_dir(): + raise BenchmarkError("Resume requires an existing results directory") + for protected in ( + Path(config["paths"]["data_dir"]), + PROJECT_ROOT / "src", + PROJECT_ROOT / "config", + PROJECT_ROOT / "tests", + ): + if root == protected.resolve() or protected.resolve() in root.parents: + raise BenchmarkError( + "Output directory must not be inside canonical data or source code" + ) + lock, sources, hashes = load_sources(config) + contract = _context_contract(config, lock, hashes, plan, options, root) + payload = { + "created_at": utc_now(), + **contract, + "experiment_signature": _contract_signature(contract), + } + try: + payload["git_commit"] = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=PROJECT_ROOT, text=True, timeout=10 + ).strip() + payload["git_dirty"] = bool( + subprocess.check_output( + ["git", "status", "--porcelain"], cwd=PROJECT_ROOT, text=True, timeout=10 + ).strip() + ) + except (OSError, subprocess.SubprocessError): + payload["git_commit"] = "unavailable" + implementation_sha256 = { + p.name: sha256_file(p) for p in sorted(Path(__file__).parent.glob("*.py")) + } + payload["implementation_sha256"] = implementation_sha256 + if options.resume: + recorded = _validate_resume_contract(root, contract) + history = list(recorded.get("resume_history") or []) + history.append( + { + "resumed_at": utc_now(), + "git_commit": payload.get("git_commit", "unavailable"), + "git_dirty": payload.get("git_dirty"), + "implementation_sha256": implementation_sha256, + } + ) + recorded["resume_history"] = history + recorded.setdefault( + "context_measurement_protocol_version", CONTEXT_MEASUREMENT_PROTOCOL_VERSION + ) + recorded.setdefault("experiment_signature", _contract_signature(contract)) + atomic_write_json(root / "context_plan.json", recorded) + else: + root.mkdir(parents=True, exist_ok=False) + atomic_write_json(root / "context_plan.json", payload) + skipped_runs = 0 + archived_attempts: list[str] = [] + try: + if not options.resume: + capture_environment(config, lock, root) + tokenizer = load_pinned_tokenizer(config, lock) + selected = select_stratified_records(sources, options.samples) + warm_sources = [ + { + "sample_id": f"w{wave}-{i}", + "source": "synthetic", + "task": "runtime_warmup", + "context": "Unrelated initialization document.", + "instruction": "Return READY.", + "answer": "READY", + } + for wave in range(options.warmup_waves) + for i in range(max(options.concurrencies)) + ] + if options.resume: + validate_prepared_context(root, tokenizer, options, selected, warm_sources) + identity_path = root / "image_identity.json" + if not identity_path.is_file(): + raise BenchmarkError("Resume image identity is missing") + digest = str(load_json(identity_path).get("image_digest") or "") + if not digest: + raise BenchmarkError("Resume image digest is missing") + else: + for length in options.lengths: + derived = cell_config(config, length) + # One allocation covers ALL prompts sharing a server, including all + # warm-up waves. Independent allocations could reuse starting tokens. + combined = build_context_records(derived, tokenizer, selected + warm_sources) + measured = combined[: len(selected)] + warmups = combined[len(selected) :] + checks = validate_prompt_set(tokenizer, measured + warmups, length) + directory = root / "prepared" / f"input_{length}" + directory.mkdir(parents=True) + write_jsonl(directory / "measured.jsonl", measured) + write_jsonl(directory / "warmup.jsonl", warmups) + atomic_write_json(directory / "validation.json", checks) + assert_idle(config) + image_server = DockerEngineServer( + engine="tensorrt_llm", + config=config, + lock=lock, + run_dir=root / "image", + skip_image_pull=options.skip_image_pull, + ) + digest = image_server.prepare_image() + atomic_write_json(root / "image_identity.json", {"image_digest": digest}) + + pending: list[ContextCell] = [] + for cell in plan: + if options.resume and accepted_cell_is_valid(root, cell, options, digest): + skipped_runs += 1 + continue + pending.append(cell) + if options.resume and pending: + assert_idle(config) + if options.resume and pending: + image_server = DockerEngineServer( + engine="tensorrt_llm", + config=config, + lock=lock, + run_dir=root / "image-resume", + skip_image_pull=options.skip_image_pull, + ) + current_digest = image_server.prepare_image() + if current_digest != digest: + raise BenchmarkError( + f"Resume image digest mismatch: {current_digest} != {digest}" + ) + for index, cell in enumerate(plan): + print(f"[context] {index + 1:02d}/{len(plan):02d} {cell}", flush=True) + if cell not in pending: + print(f"[context] skipping accepted cell {cell}", flush=True) + continue + archived = archive_incomplete_cell(root, cell) + if archived is not None: + archived_attempts.append(str(archived.relative_to(root))) + print(f"[context] archived incomplete attempt at {archived}", flush=True) + execute_cell( + config, + lock, + tokenizer, + cell, + options, + root / "prepared" / f"input_{cell.input_tokens}", + digest, + root, + ) + if any(candidate in pending for candidate in plan[index + 1 :]): + time.sleep(options.cooldown_seconds) + except BaseException as exc: + atomic_write_json( + root / "context_failure.json", + { + "error": f"{type(exc).__name__}: {exc}", + "at": utc_now(), + }, + ) + raise + finally: + write_context_report( + root, + plan, + options.profile_nsys, + resumed=options.resume, + skipped_runs=skipped_runs, + archived_attempts=archived_attempts, + ) + artifacts = { + str(p.relative_to(root)): sha256_file(p) + for p in sorted(root.rglob("*")) + if p.is_file() and p.name != "context_provenance.json" + } + atomic_write_json( + root / "context_provenance.json", + { + "source_sha256": hashes, + "artifact_sha256": artifacts, + "generated_at": utc_now(), + }, + ) + return load_json(root / "context_status.json") + + +def parse_ints(value: str) -> tuple[int, ...]: + try: + return tuple(int(item.strip()) for item in value.split(",")) + except ValueError as exc: + raise argparse.ArgumentTypeError("Expected comma-separated integers") from exc + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--config", default=str(PROJECT_ROOT / "config/tensorrt-llm-context-scaling.yaml") + ) + parser.add_argument("--results-dir", type=Path, required=True) + parser.add_argument("--lengths", type=parse_ints, default=(8000, 32000, 64000, 120000)) + parser.add_argument("--concurrency", type=parse_ints, default=(1, 4)) + parser.add_argument("--samples", type=int, default=20) + parser.add_argument("--repetitions", type=int, default=1) + parser.add_argument("--warmup-waves", type=int, default=2) + parser.add_argument("--cooldown-seconds", type=float, default=60.0) + parser.add_argument("--skip-image-pull", action="store_true") + parser.add_argument("--profile-nsys", action="store_true") + parser.add_argument("--resume", action="store_true") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args(argv) + try: + result = run_context_scaling( + load_config(args.config), + ContextOptions( + output_dir=args.results_dir, + lengths=args.lengths, + concurrencies=args.concurrency, + samples=args.samples, + repetitions=args.repetitions, + warmup_waves=args.warmup_waves, + cooldown_seconds=args.cooldown_seconds, + skip_image_pull=args.skip_image_pull, + profile_nsys=args.profile_nsys, + dry_run=args.dry_run, + resume=args.resume, + ), + ) + except (BenchmarkError, OSError, ValueError, subprocess.SubprocessError) as exc: + parser.error(str(exc)) + print(json.dumps(result, indent=2)) + return 0 diff --git a/tests/test_context_analysis.py b/tests/test_context_analysis.py new file mode 100644 index 0000000..40df22f --- /dev/null +++ b/tests/test_context_analysis.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +import csv +import json +import tempfile +import unittest +from pathlib import Path + +from llm_engine_benchmark.context_analysis import generate_context_analysis +from llm_engine_benchmark.util import BenchmarkError + + +def write_source(root: Path, cells: list[tuple[int, int, int]], *, marker: str = "same") -> None: + root.mkdir() + plan = { + "source_sha256": {"manifest": "abc"}, + "lock": {"model": "test"}, + "config": {"project": {"output_tokens": 512}, "engines": {"test": {}}}, + "scope": "context_characterization_no_quality_or_production_capacity_claim", + "context_prompt_format_version": 3, + "options": {"samples": 20, "warmup_waves": 2, "profile_nsys": False}, + } + (root / "context_plan.json").write_text(json.dumps(plan)) + (root / "image_identity.json").write_text(json.dumps({"image_digest": "sha256:image"})) + for tokens, concurrency, repetition in cells: + run = root / f"input_{tokens}/c{concurrency}/run_{repetition:02d}" + run.mkdir(parents=True) + metadata = { + "status": "accepted", + "input_tokens": tokens, + "concurrency": concurrency, + "repetition": repetition, + "requests_sha256": f"{marker}-{tokens}", + "image_digest": "sha256:image", + } + result = { + "valid": True, + "successful_requests": 20, + "failed_requests": 0, + "server_reported_prompt_token_coverage_requests": 20, + "server_reported_cached_prompt_tokens_total": 0, + "output_throughput_tokens_per_second": 40.0 / concurrency, + "request_throughput_per_second": 0.1, + } + for name, value in ( + ("ttft", tokens / 1000 * concurrency), + ("itl", 0.01 * concurrency), + ("tpot", 0.02 * concurrency), + ("e2e", tokens / 500 * concurrency), + ): + result[f"{name}_seconds"] = {"p50": value / 2, "p95": value, "mean": value} + (run / "context_metadata.json").write_text(json.dumps(metadata)) + (run / "client_results.json").write_text(json.dumps(result)) + (run / "request_timings.jsonl").write_text(json.dumps({"itl_seconds": [0.1]}) + "\n") + + +class ContextAnalysisTests(unittest.TestCase): + def test_consolidates_split_discovery_sources(self) -> None: + with tempfile.TemporaryDirectory() as temp: + base = Path(temp) + first = base / "first" + second = base / "second" + output = base / "output" + write_source(first, [(8000, 1, 1), (32000, 1, 1), (32000, 4, 1)]) + write_source(second, [(8000, 4, 1)]) + + outputs = generate_context_analysis( + source_roots=[first, second], + lengths=(8000, 32000), + concurrencies=(1, 4), + repetitions=1, + output_dir=output, + ) + + with outputs["summary"].open() as handle: + rows = list(csv.DictReader(handle)) + self.assertEqual(len(rows), 4) + self.assertNotIn(b"\r\n", outputs["summary"].read_bytes()) + report = outputs["report"].read_text() + self.assertIn("complete_discovery", report) + self.assertIn("Concurrency effect", report) + provenance = json.loads(outputs["provenance"].read_text()) + self.assertTrue(provenance["decision"]["complete"]) + self.assertEqual(provenance["decision"]["accepted_cells"], 4) + + def test_missing_cell_is_reported_without_claiming_completion(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "source" + output = Path(temp) / "output" + write_source(root, [(8000, 1, 1)]) + outputs = generate_context_analysis( + source_roots=[root], + lengths=(8000,), + concurrencies=(1, 4), + repetitions=1, + output_dir=output, + ) + provenance = json.loads(outputs["provenance"].read_text()) + self.assertEqual(provenance["decision"]["status"], "incomplete") + self.assertEqual( + provenance["decision"]["missing_cells"], + [{"input_tokens": 8000, "concurrency": 4, "repetition": 1}], + ) + + def test_duplicate_cell_across_sources_is_rejected(self) -> None: + with tempfile.TemporaryDirectory() as temp: + first = Path(temp) / "first" + second = Path(temp) / "second" + write_source(first, [(8000, 1, 1)]) + write_source(second, [(8000, 1, 1)]) + with self.assertRaisesRegex(BenchmarkError, "Duplicate accepted"): + generate_context_analysis( + source_roots=[first, second], + lengths=(8000,), + concurrencies=(1,), + repetitions=1, + output_dir=Path(temp) / "output", + ) + + def test_incompatible_source_is_rejected(self) -> None: + with tempfile.TemporaryDirectory() as temp: + first = Path(temp) / "first" + second = Path(temp) / "second" + write_source(first, [(8000, 1, 1)]) + write_source(second, [(8000, 4, 1)]) + plan = json.loads((second / "context_plan.json").read_text()) + plan["options"]["samples"] = 100 + (second / "context_plan.json").write_text(json.dumps(plan)) + with self.assertRaisesRegex(BenchmarkError, "Incompatible"): + generate_context_analysis( + source_roots=[first, second], + lengths=(8000,), + concurrencies=(1, 4), + repetitions=1, + output_dir=Path(temp) / "output", + ) + + def test_measured_prompt_difference_between_sources_is_rejected(self) -> None: + with tempfile.TemporaryDirectory() as temp: + first = Path(temp) / "first" + second = Path(temp) / "second" + write_source(first, [(8000, 1, 1)], marker="first") + write_source(second, [(8000, 4, 1)], marker="second") + with self.assertRaisesRegex(BenchmarkError, "Measured prompts differ"): + generate_context_analysis( + source_roots=[first, second], + lengths=(8000,), + concurrencies=(1, 4), + repetitions=1, + output_dir=Path(temp) / "output", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_context_scaling.py b/tests/test_context_scaling.py new file mode 100644 index 0000000..eb47c7d --- /dev/null +++ b/tests/test_context_scaling.py @@ -0,0 +1,620 @@ +from __future__ import annotations + +import copy +import json +import subprocess +import tempfile +import unittest +from contextlib import ExitStack +from dataclasses import replace +from pathlib import Path +from unittest.mock import Mock, patch + +from llm_engine_benchmark.config import load_config +from llm_engine_benchmark.context_scaling import ( + ContextCell, + ContextOptions, + accept_result, + allocate_context_prefixes, + assert_idle, + build_context_plan, + build_context_records, + cell_config, + load_sources, + observed_concurrency, + run_context_scaling, + validate_prompt_set, + write_context_report, +) +from llm_engine_benchmark.normalize import _build_cold_records, instruction_suffix_with_budget +from llm_engine_benchmark.util import BenchmarkError, load_json, read_jsonl, write_jsonl + +MODULE = "llm_engine_benchmark.context_scaling" + + +class CharTokenizer: + def encode(self, text, add_special_tokens=False): + return [ord(c) for c in text] + + def decode(self, ids, **kwargs): + return "".join(chr(i) for i in ids) + + +class FakeServer: + instances = [] + + def __init__(self, **kwargs): + self.kwargs = kwargs + self.started = False + self.base_url = "http://localhost:8001" + self.api_model = "test-model" + self.run_command = ["fake-server"] + self.instances.append(self) + + def start(self): + self.started = True + + def stop(self): + self.started = False + + def prepare_image(self): + return "sha256:test-image" + + def wait_ready(self, timeout): + pass + + def capture_runtime_versions(self): + return {"test": "1"} + + def snapshot_metrics(self, filename): + pass + + def is_running(self): + return self.started + + def validate_profile_artifacts(self): + pass + + +def fake_client(**kwargs): + directory = Path(kwargs["run_dir"]) + directory.mkdir(parents=True, exist_ok=True) + records = list(read_jsonl(kwargs["records_path"])) + if kwargs.get("sample_ids") is not None: + by_id = {r["sample_id"]: r for r in records} + records = [by_id[key] for key in kwargs["sample_ids"]] + else: + records = records[: kwargs["sample_limit"]] + count = len(records) + result = { + "valid": True, + "successful_requests": count, + "server_reported_prompt_token_coverage_requests": count, + "server_reported_cached_prompt_tokens_total": 0, + "cache_report_coverage_fraction": 1.0, + "output_throughput_tokens_per_second": 10.0, + "request_throughput_per_second": 0.1, + } + for name in ("ttft", "itl", "tpot", "e2e"): + result[f"{name}_seconds"] = {"p50": 1.0, "p95": 2.0, "mean": 1.5} + (directory / "client_results.json").write_text(json.dumps(result)) + write_jsonl( + directory / "request_timings.jsonl", + [ + { + "request_start_offset_seconds": i // kwargs["options"].concurrency, + "request_end_offset_seconds": i // kwargs["options"].concurrency + 1, + "itl_seconds": [0.1, 0.3], + } + for i in range(count) + ], + ) + return result + + +class ContextScalingTests(unittest.TestCase): + def setUp(self): + self.config = load_config() + self.config["normalization"]["controlled_distractor_min_chars"] = 128 + self.config["normalization"]["extra_source_tokens"] = 128 + self.options = ContextOptions(output_dir=Path("unused")) + + def test_plan_has_eight_cells_and_reverses_between_repetitions(self): + options = replace(self.options, repetitions=3) + plan = build_context_plan(self.config, options) + self.assertEqual(len(plan), 24) + + def pairs(cells): + return [(c.input_tokens, c.concurrency) for c in cells] + + self.assertEqual(pairs(plan[:8]), list(reversed(pairs(plan[8:16])))) + self.assertEqual(plan, build_context_plan(self.config, options)) + self.assertEqual(len(set(pairs(plan[:8]))), 8) + + def test_invalid_options_fail_before_execution(self): + cases = [ + {"lengths": ()}, + {"lengths": (8000, 8000)}, + {"lengths": (-1,)}, + {"lengths": (131072,)}, + {"lengths": (32,)}, + {"concurrencies": (0,)}, + {"concurrencies": (1, 8)}, + {"samples": 2}, + {"samples": 101}, + {"repetitions": 0}, + {"warmup_waves": 0}, + {"cooldown_seconds": -1}, + {"cooldown_seconds": float("nan")}, + ] + for changes in cases: + with self.subTest(changes=changes), self.assertRaises(BenchmarkError): + build_context_plan(self.config, replace(self.options, **changes)) + + def test_cell_config_leaves_base_unchanged_and_keeps_server_ceiling(self): + original = copy.deepcopy(self.config) + derived = cell_config(self.config, 8000) + self.assertEqual(derived["project"]["input_tokens"], 8000) + self.assertEqual(derived["project"]["context_length"], 131072) + self.assertEqual(derived["engines"], original["engines"]) + self.assertEqual(self.config, original) + + def test_dry_run_does_not_create_files_load_sources_or_contact_gpu(self): + with tempfile.TemporaryDirectory() as temp, patch(f"{MODULE}.load_sources") as sources: + root = Path(temp) / "new" + with patch(f"{MODULE}.assert_idle") as idle: + result = run_context_scaling( + self.config, replace(self.options, output_dir=root, dry_run=True) + ) + self.assertEqual(result["planned_runs"], 8) + self.assertFalse(root.exists()) + sources.assert_not_called() + idle.assert_not_called() + + def test_existing_results_never_overwritten(self): + with tempfile.TemporaryDirectory() as temp: + sentinel = Path(temp) / "existing.txt" + sentinel.write_text("preserve") + with self.assertRaisesRegex(BenchmarkError, "already exists"): + run_context_scaling(self.config, replace(self.options, output_dir=Path(temp))) + self.assertEqual(sentinel.read_text(), "preserve") + + def test_canonical_data_path_is_protected(self): + with tempfile.TemporaryDirectory() as temp: + self.config["paths"]["data_dir"] = temp + with self.assertRaisesRegex(BenchmarkError, "canonical data"): + run_context_scaling( + self.config, replace(self.options, output_dir=Path(temp) / "new") + ) + + def test_existing_source_lock_is_required_not_created(self): + with tempfile.TemporaryDirectory() as temp: + self.config["paths"]["lock_file"] = str(Path(temp) / "absent.json") + with self.assertRaisesRegex(BenchmarkError, "Existing"): + load_sources(self.config) + self.assertEqual(list(Path(temp).iterdir()), []) + + def test_exact_lengths_and_prefixes(self): + tokenizer = CharTokenizer() + records = [ + {"sample_id": "a", "prompt": "a" * 40, "prompt_tokens": 40}, + {"sample_id": "b", "prompt": "b" * 40, "prompt_tokens": 40}, + ] + self.assertEqual(validate_prompt_set(tokenizer, records, 40)["input_tokens"], 40) + records[1]["prompt"] = "a" * 32 + "b" * 8 + with self.assertRaisesRegex(BenchmarkError, "prefix"): + validate_prompt_set(tokenizer, records, 40) + records[1]["prompt"] = "b" * 39 + with self.assertRaisesRegex(BenchmarkError, "token count"): + validate_prompt_set(tokenizer, records, 40) + + def test_eight_common_tokens_are_rejected_even_with_distinct_32_token_heads(self): + records = [ + {"sample_id": "a", "prompt": "header00" + "a" * 32, "prompt_tokens": 40}, + {"sample_id": "b", "prompt": "header00" + "b" * 32, "prompt_tokens": 40}, + ] + with self.assertRaisesRegex(BenchmarkError, "shared first-token prefix"): + validate_prompt_set(CharTokenizer(), records, 40) + + def test_early_prefix_removes_common_header_without_changing_legacy_builder(self): + tokenizer = CharTokenizer() + config = cell_config(self.config, 2048) + sources = [ + { + "sample_id": key, + "source": "synthetic", + "task": "qa", + "context": "Document.", + "instruction": "Preserve this task instruction.", + } + for key in ("w0-0", "w0-1", "w1-0", "measured-1") + ] + original_sources = copy.deepcopy(sources) + legacy = _build_cold_records(config, tokenizer, sources) + with self.assertRaisesRegex(BenchmarkError, "shared first-token prefix"): + validate_prompt_set(tokenizer, legacy, 2048) + current = build_context_records(config, tokenizer, sources) + self.assertEqual(current, build_context_records(config, tokenizer, sources)) + self.assertEqual( + validate_prompt_set(tokenizer, current, 2048)["unique_prefix_check_tokens"], 1 + ) + self.assertEqual(sources, original_sources) + self.assertEqual(legacy, _build_cold_records(config, tokenizer, sources)) + for record, source in zip(current, sources, strict=True): + suffix, _ = instruction_suffix_with_budget(config, tokenizer, source) + self.assertTrue(record["prompt"].endswith(suffix)) + self.assertEqual(record["metadata"]["context_prompt_format_version"], 3) + + def test_block_cache_model_observes_no_reuse_across_warmups_and_measurement(self): + prefixes_by_run = {} + + def cache_client(**kwargs): + result = fake_client(**kwargs) + directory = Path(kwargs["run_dir"]) + run = next(p for p in (directory, *directory.parents) if p.name == "run_01") + seen = prefixes_by_run.setdefault(run, set()) + records = list(read_jsonl(kwargs["records_path"])) + if kwargs.get("sample_ids") is not None: + by_id = {r["sample_id"]: r for r in records} + records = [by_id[key] for key in kwargs["sample_ids"]] + cached = 0 + for record in records: + head = tuple(CharTokenizer().encode(record["prompt"])[:1]) + cached += 1 if head in seen else 0 + seen.add(head) + result["server_reported_cached_prompt_tokens_total"] = cached + return result + + with tempfile.TemporaryDirectory() as temp: + _, result, _ = self.mocked_run(temp, client=cache_client) + self.assertEqual(result["accepted_runs"], 2) + + def test_one_common_token_is_rejected_even_if_remaining_tokens_differ(self): + records = [ + {"sample_id": "w0-0", "prompt": "f" + "6" * 39, "prompt_tokens": 40}, + {"sample_id": "w0-2", "prompt": "f" + "9" * 39, "prompt_tokens": 40}, + ] + with self.assertRaisesRegex(BenchmarkError, "shared first-token"): + validate_prompt_set(CharTokenizer(), records, 40) + + def test_first_token_allocator_handles_full_100_samples_plus_8_warmups(self): + class NumericTokenizer: + def encode(self, text, add_special_tokens=False): + # Simulates the numeric marker segmentation, not the whole model tokenizer. + return [int(text[:3]) + 1000, 10] + + sources = [{"sample_id": f"sample-{i}"} for i in range(100)] + sources += [{"sample_id": f"w{wave}-{i}"} for wave in range(2) for i in range(4)] + tokenizer = NumericTokenizer() + prefixes = allocate_context_prefixes(tokenizer, sources, 1) + self.assertEqual(len({tokenizer.encode(p)[0] for p in prefixes.values()}), 108) + self.assertEqual(prefixes, allocate_context_prefixes(tokenizer, list(reversed(sources)), 1)) + + def test_first_token_allocator_fails_closed_on_invariant_first_token(self): + class FixedFirstTokenizer: + def encode(self, text, add_special_tokens=False): + return [99, len(text)] + + with self.assertRaisesRegex(BenchmarkError, "enough distinct"): + allocate_context_prefixes( + FixedFirstTokenizer(), [{"sample_id": "a"}, {"sample_id": "b"}], 1 + ) + + def test_first_token_allocator_rejects_duplicate_ids(self): + with self.assertRaisesRegex(BenchmarkError, "Duplicate"): + allocate_context_prefixes(CharTokenizer(), [{"sample_id": "a"}, {"sample_id": "a"}], 1) + + def test_invalid_missing_usage_and_cache_hits_rejected(self): + valid = { + "valid": True, + "successful_requests": 4, + "server_reported_prompt_token_coverage_requests": 4, + } + accept_result(valid, 4) + for changes in ( + {"valid": False}, + {"successful_requests": 3}, + {"server_reported_prompt_token_coverage_requests": 0}, + {"server_reported_cached_prompt_tokens_total": 1}, + ): + with self.subTest(changes=changes), self.assertRaises(BenchmarkError): + accept_result({**valid, **changes}, 4) + + def test_busy_host_guard_uses_read_only_commands(self): + for outputs in (("llmbench-tensorrt-llm",), ("", "12345")): + completed = [subprocess.CompletedProcess([], 0, text) for text in outputs] + with patch(f"{MODULE}.subprocess.run", side_effect=completed) as command: + with self.assertRaisesRegex(BenchmarkError, "not idle"): + assert_idle(self.config) + self.assertTrue(all("rm" not in c.args[0] for c in command.call_args_list)) + + def test_busy_port_guard(self): + with ( + patch(f"{MODULE}.subprocess.run", return_value=Mock(stdout="")), + patch(f"{MODULE}.socket.socket") as sock, + ): + sock.return_value.__enter__.return_value.bind.side_effect = OSError("busy") + with self.assertRaisesRegex(BenchmarkError, "Port"): + assert_idle(self.config) + + def test_concurrency_uses_half_open_intervals(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / "timings.jsonl" + write_jsonl( + path, + [ + {"request_start_offset_seconds": 0, "request_end_offset_seconds": 1}, + {"request_start_offset_seconds": 1, "request_end_offset_seconds": 2}, + ], + ) + self.assertEqual(observed_concurrency(path), 1) + + def mocked_run(self, temp, client=fake_client, **changes): + root = Path(temp) / "experiment" + sources = [ + { + "sample_id": f"sample-{i}", + "source": "ruler", + "task": "qa", + "context": "Document.", + "instruction": "Answer the question.", + } + for i in range(100) + ] + FakeServer.instances = [] + options = replace( + self.options, + output_dir=root, + lengths=(2048,), + concurrencies=(1, 4), + samples=4, + cooldown_seconds=0, + **changes, + ) + original = copy.deepcopy(self.config) + with ExitStack() as stack: + stack.enter_context(patch(f"{MODULE}.load_sources", return_value=({}, sources, {}))) + stack.enter_context(patch(f"{MODULE}.assert_idle")) + stack.enter_context(patch(f"{MODULE}.capture_environment")) + stack.enter_context( + patch(f"{MODULE}.load_pinned_tokenizer", return_value=CharTokenizer()) + ) + stack.enter_context(patch(f"{MODULE}.DockerEngineServer", FakeServer)) + stack.enter_context(patch(f"{MODULE}.TelemetrySession")) + stack.enter_context(patch(f"{MODULE}.write_metrics_diff")) + mock_client = stack.enter_context( + patch(f"{MODULE}.run_benchmark_client", side_effect=client) + ) + result = run_context_scaling(self.config, options) + self.assertEqual(original, self.config) + return root, result, mock_client + + def mocked_resume(self, root, client=fake_client): + sources = [ + { + "sample_id": f"sample-{i}", + "source": "ruler", + "task": "qa", + "context": "Document.", + "instruction": "Answer the question.", + } + for i in range(100) + ] + options = replace( + self.options, + output_dir=root, + lengths=(2048,), + concurrencies=(1, 4), + samples=4, + cooldown_seconds=0, + resume=True, + ) + FakeServer.instances = [] + with ExitStack() as stack: + stack.enter_context(patch(f"{MODULE}.load_sources", return_value=({}, sources, {}))) + stack.enter_context(patch(f"{MODULE}.assert_idle")) + stack.enter_context( + patch(f"{MODULE}.load_pinned_tokenizer", return_value=CharTokenizer()) + ) + stack.enter_context(patch(f"{MODULE}.DockerEngineServer", FakeServer)) + stack.enter_context(patch(f"{MODULE}.TelemetrySession")) + stack.enter_context(patch(f"{MODULE}.write_metrics_diff")) + mock_client = stack.enter_context( + patch(f"{MODULE}.run_benchmark_client", side_effect=client) + ) + result = run_context_scaling(self.config, options) + return result, mock_client + + def test_end_to_end_excludes_warmup_and_preserves_existing_artifacts(self): + with tempfile.TemporaryDirectory() as temp: + sentinel = Path(temp) / "original-results.json" + sentinel.write_text("untouched") + root, result, client = self.mocked_run(temp) + self.assertEqual(result["accepted_runs"], 2) + self.assertEqual(client.call_count, 6) # two waves + measurement per cell + self.assertEqual(sentinel.read_text(), "untouched") + self.assertNotIn(b"\r\n", (root / "context_summary.csv").read_bytes()) + for c in (1, 4): + directory = root / f"input_2048/c{c}/run_01" + metadata = load_json(directory / "context_metadata.json") + self.assertEqual(metadata["warmup_client_peak_concurrency"], [c, c]) + self.assertEqual( + load_json(directory / "client_results.json")["successful_requests"], 4 + ) + self.assertTrue(load_json(root / "context_provenance.json")["artifact_sha256"]) + owned = [ + s.kwargs["config"]["engines"]["tensorrt_llm"]["container_name"] + for s in FakeServer.instances + if "image" != Path(s.kwargs["run_dir"]).name + ] + self.assertEqual(len(set(owned)), 2) + self.assertTrue(all(name.startswith("llmbench-context-") for name in owned)) + self.assertTrue(all(not s.started for s in FakeServer.instances)) + + def test_resume_revalidates_and_skips_every_accepted_cell(self): + with tempfile.TemporaryDirectory() as temp: + root, _, _ = self.mocked_run(temp) + before = { + path: path.read_bytes() + for path in root.glob("input_*/c*/run_*/client_results.json") + } + result, client = self.mocked_resume(root) + self.assertEqual(result["accepted_runs"], 2) + self.assertEqual(result["skipped_accepted_runs"], 2) + self.assertTrue(result["resumed"]) + client.assert_not_called() + self.assertEqual(before, {path: path.read_bytes() for path in before}) + + def test_resume_archives_only_incomplete_cell_and_reruns_it(self): + with tempfile.TemporaryDirectory() as temp: + root, _, _ = self.mocked_run(temp) + cells = sorted(root.glob("input_*/c*/run_*/context_metadata.json")) + interrupted = cells[0] + metadata = load_json(interrupted) + metadata["status"] = "starting" + interrupted.write_text(json.dumps(metadata)) + accepted_result = cells[1].parent / "client_results.json" + accepted_before = accepted_result.read_bytes() + + result, client = self.mocked_resume(root) + + self.assertEqual(result["accepted_runs"], 2) + self.assertEqual(result["skipped_accepted_runs"], 1) + self.assertEqual(client.call_count, 3) + self.assertEqual(accepted_result.read_bytes(), accepted_before) + archives = list(root.glob("interrupted/input_*/c*/run_*/attempt_*")) + self.assertEqual(len(archives), 1) + self.assertTrue((archives[0] / "context_metadata.json").is_file()) + + def test_resume_rejects_changed_experiment_without_modifying_cells(self): + with tempfile.TemporaryDirectory() as temp: + root, _, _ = self.mocked_run(temp) + sentinel = root / "input_2048/c1/run_01/client_results.json" + before = sentinel.read_bytes() + sources = [ + { + "sample_id": f"sample-{i}", + "source": "ruler", + "task": "qa", + "context": "Document.", + "instruction": "Answer the question.", + } + for i in range(100) + ] + options = replace( + self.options, + output_dir=root, + lengths=(2048,), + concurrencies=(1, 4), + samples=5, + cooldown_seconds=0, + resume=True, + ) + with patch(f"{MODULE}.load_sources", return_value=({}, sources, {})): + with self.assertRaisesRegex(BenchmarkError, "option samples"): + run_context_scaling(self.config, options) + self.assertEqual(sentinel.read_bytes(), before) + + def test_resume_rejects_corrupt_accepted_cell_without_archiving_it(self): + with tempfile.TemporaryDirectory() as temp: + root, _, _ = self.mocked_run(temp) + result_path = root / "input_2048/c1/run_01/client_results.json" + result = load_json(result_path) + result["server_reported_cached_prompt_tokens_total"] = 1 + result_path.write_text(json.dumps(result)) + + with self.assertRaisesRegex(BenchmarkError, "cache reuse"): + self.mocked_resume(root) + + self.assertTrue(result_path.is_file()) + self.assertFalse((root / "interrupted/input_2048/c1/run_01").exists()) + + def test_warmup_failure_stops_before_measurement_and_retains_status(self): + with tempfile.TemporaryDirectory() as temp: + + def fail(**kwargs): + raise BenchmarkError("warmup failed") + + with self.assertRaisesRegex(BenchmarkError, "warmup failed"): + self.mocked_run(temp, client=fail) + root = Path(temp) / "experiment" + status = load_json(root / "context_status.json") + self.assertEqual(status["accepted_runs"], 0) + self.assertTrue((root / "context_failure.json").exists()) + self.assertTrue(all(not s.started for s in FakeServer.instances)) + + def test_measurement_rejection_marks_client_invalid(self): + with tempfile.TemporaryDirectory() as temp: + + def fail(**kwargs): + result = fake_client(**kwargs) + if "warmup" not in Path(kwargs["run_dir"]).parts: + result["server_reported_cached_prompt_tokens_total"] = 32 + return result + + with self.assertRaisesRegex(BenchmarkError, "cache reuse"): + self.mocked_run(temp, client=fail) + results = list((Path(temp) / "experiment").glob("input_*/c*/run_*/client_results.json")) + self.assertEqual(len(results), 1) + self.assertFalse(load_json(results[0])["valid"]) + + def test_insufficient_warmup_concurrency_is_rejected(self): + with tempfile.TemporaryDirectory() as temp: + + def sequential(**kwargs): + result = fake_client(**kwargs) + if kwargs["options"].concurrency == 4: + write_jsonl( + Path(kwargs["run_dir"]) / "request_timings.jsonl", + [ + {"request_start_offset_seconds": i, "request_end_offset_seconds": i + 1} + for i in range(4) + ], + ) + return result + + with self.assertRaisesRegex(BenchmarkError, "Warm-up did not exercise"): + self.mocked_run(temp, client=sequential) + self.assertTrue(all(not server.started for server in FakeServer.instances)) + + def test_profile_validation_failure_is_not_accepted(self): + with ( + tempfile.TemporaryDirectory() as temp, + patch.object( + FakeServer, "validate_profile_artifacts", side_effect=BenchmarkError("missing CUDA") + ), + ): + with self.assertRaisesRegex(BenchmarkError, "missing CUDA"): + self.mocked_run(temp, profile_nsys=True) + status = load_json(Path(temp) / "experiment/context_status.json") + self.assertEqual(status["accepted_runs"], 0) + + def test_source_checksum_mismatch_is_rejected(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + (root / "canonical").mkdir() + (root / "lock.json").write_text("{}") + (root / "canonical/manifest.jsonl").write_text("{}\n") + (root / "canonical/manifest_metadata.json").write_text("{}") + self.config["paths"]["data_dir"] = str(root) + self.config["paths"]["lock_file"] = str(root / "lock.json") + with ( + patch(f"{MODULE}._validate_lock"), + patch(f"{MODULE}._validate_lock_against_config"), + patch( + f"{MODULE}._canonical_manifest_reuse_error", return_value="checksum mismatch" + ), + ): + with self.assertRaisesRegex(BenchmarkError, "checksum mismatch"): + load_sources(self.config) + + def test_missing_runs_are_not_reported_as_accepted(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + result = write_context_report(root, [ContextCell(8000, 1, 1)], False) + self.assertEqual(result["accepted_runs"], 0) + self.assertIn("not_run", (root / "context_report.md").read_text()) + + +if __name__ == "__main__": + unittest.main()