diff --git a/.gitignore b/.gitignore index eb73d40..3fe736e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ .venv/ .env *.egg-info/ +build/ +dist/ __pycache__/ *.py[cod] .pytest_cache/ @@ -17,6 +19,8 @@ results/* !results/README.md !results/summaries/ !results/summaries/*.csv +!results/summaries/*.json +!results/summaries/*.md !results/sample/ !results/sample/*.json !results/raw/ diff --git a/PROJECT_MANIFEST.sha256 b/PROJECT_MANIFEST.sha256 index a20d5d0..c0711eb 100644 --- a/PROJECT_MANIFEST.sha256 +++ b/PROJECT_MANIFEST.sha256 @@ -1,78 +1,87 @@ -fc9737e71d1258113190b602d769a91537979af56cefe3b6bf1d763b08cece97 ./.env.example -7f1426736ecf644826fa45b6b9755be1fa0174509c0781beaa40aee0af7dff69 ./.github/workflows/ci.yml -e97c6a9ce5b0f089cda834cdf00bfefbed1114caf0a05c68ad4056ada195ccef ./.gitignore -f65bd5f8df765c5247a2808ab465c8f7cb12381c9789949f19b462e8ee6a1125 ./CITATION.cff -1126322e2cc8d165adc4c792eeb195717de2bcc7b39be1ce77959d78e87ef685 ./LICENSE -73e8272c4f26ffd0f31b808df3d769d06cd80e40b23ae934a3e782be970655c1 ./README.md -ccb0caa1942e9ca329541dd7d00eeb357a44d7403dbcfab75478006d3b47a314 ./THIRD_PARTY.md 088a8d2b69557af4fe0739d82decdbd1a41e35c7c1baa4f3a95ed1b01f55e04a ./assets/charts/01_warm_shared_ttft.png 9f240bbada771e83b1832e033e283127f51882a3129caeb6eb74fded219cc181 ./assets/charts/02_warm_shared_tpot.png b3529b640c94cb84164b12f0e99f14186607da117fd8221ea1a2b5296605b9f4 ./assets/charts/03_warm_shared_e2e.png 1803b26cfcf40f66bcb5cec92fb7d50dd67ab9a59e47c3e795736c4642da6c27 ./assets/charts/04_warm_shared_request_throughput.png ff8244411528abdfea62a3cd39037a61b8700e5f8224a2ba5cd4f9c7f4f96576 ./assets/charts/06_tensorrt_cache_ttft_reduction.png -f3f411f55724db267ab04afbe64b03240582eb6f7047067bce4976467eb7ad73 ./assets/charts/README.md dffd18405dcd54cd4d64e98eaf169b1673be051013a9ed1fe248ca06d29c785a ./assets/charts/cold-warm-benefit.svg 96dfc91cb85dc510b4511f342b9a7cfe53a9b1c48df5bc8c1a044ee892672558 ./assets/charts/dashboard.svg 3712998c9b2010b7b5a24dae4e36a124d230b027f6960c4d5ba3506cca5c7226 ./assets/charts/measured-ttft-throughput-operating-points.svg 701ff94a5b3f8e91f1a4586735dbbb221254dbfebd0b989cfe65f90c21b30d1f ./assets/charts/prefix-reuse.svg c8310b14d9f550d25422f688c7c8dc1307f44dd4abc0bc86e47881554a11cd34 ./assets/charts/provenance.json +f3f411f55724db267ab04afbe64b03240582eb6f7047067bce4976467eb7ad73 ./assets/charts/README.md f8a340a47e632624e7f1821c726adc046822c69398a5b2e98c8adef217f84940 ./assets/charts/scaling-efficiency.svg 25c390b21128e570e3cb485ebff31be57b6f8e18fde899458f5f1d317b5c540a ./assets/charts/tensorrt_cache_benefit_data.csv e4e7fe0fb913eda0e53509083b9dc25680cc8e5e68ef5c22a60543ddc7c5a79d ./assets/charts/warm_shared_chart_data.csv 8f6a3e74cbf0a32e99c6949275912d074816523e8db79e76db557008c57ed18e ./bench +f65bd5f8df765c5247a2808ab465c8f7cb12381c9789949f19b462e8ee6a1125 ./CITATION.cff 7ddc4d0bcf64d5f8bc42be909b7a1a1a959b02004106e33f82e1b9ad85b1771e ./config/default.yaml +1b4ab1268e0c5f4e5c6948067944d4b7506e40617bad1aceff9b6f1339f5b174 ./config/tensorrt-llm-profile-c4.yaml 9828c4c66605cc2c93859ffa7484c472d69587c6be94acd250748dd1f7cf6afa ./config/tensorrt-llm-smoke.yaml e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./data/.gitkeep -67dab2a1559389f73148d1055fc20c2de0eae79c625985c011fca438d9b7140a ./docs/DESIGN_MAPPING.md -2380f29068fe378b7063b427ec509b7b595e52b200a37ec1b80070e85cd36d8a ./docs/RESULT_SCHEMA.md 72784da5ab0d762248ed8526fe3284e32c15a15eb1e9c2e99ed5b801bfed4176 ./docs/architecture.md -2630941f3ca98ff29aec515caeb697d84b695b98612e3205b356080854c89420 ./docs/fairness-and-limitations.md +67dab2a1559389f73148d1055fc20c2de0eae79c625985c011fca438d9b7140a ./docs/DESIGN_MAPPING.md +cb7cbbbf69a14ccced146130f9735ce76dc72f4d77c349a42889954767e07b82 ./docs/fairness-and-limitations.md 181ed639e1a1553745d78d9ff99219f4b73a86be2b0b48601cefd0671024a0db ./docs/methodology.md 8b70253f53bb0c3416effd53cc007e07202044f62bc671ff3e02b03a0eb9b6e1 ./docs/paper-outline.md -1e2b482bd8d7be45f56123717711c7728dc55b416b5861061959156fa87e2d76 ./docs/production-recommendations.md -4963b40c6e810cac22eca9d1b53451daa12f3dcb3d09e3c72420d7a6854dd589 ./docs/profiling.md +184273349322917465a85d0435c82b3366790f4732535bc06308db537b25e959 ./docs/prefill-budget-case-study.md +7556bf36a4e274352c74a2da94f6829096d6c3953217c2b4e84fbec3e462a82a ./docs/production-recommendations.md +a5bf4371c82ee51db5185e0025a921e75b429104796ca7a30ec9e2da593a4bb5 ./docs/profiling.md 670ddfa929e2c624621ac3ce87da5fe9f2e1c5d826ea55bb343142c75e03a83c ./docs/reproducibility.md -f8b0d0cd879a33214b01201426f09ec0820ba2c377dcaabc95c472e2dbc85b72 ./docs/results.md +2380f29068fe378b7063b427ec509b7b595e52b200a37ec1b80070e85cd36d8a ./docs/RESULT_SCHEMA.md +65e531518357fa8a58b8aa97cdabb309137362a80d7cf78ee366eb154edd73e4 ./docs/results.md +fc9737e71d1258113190b602d769a91537979af56cefe3b6bf1d763b08cece97 ./.env.example +7f1426736ecf644826fa45b6b9755be1fa0174509c0781beaa40aee0af7dff69 ./.github/workflows/ci.yml +9a76f67fdf6e34a5a296fc0c6dc8790f68c980da882fe7dfcfa7c239181fa602 ./.gitignore +1126322e2cc8d165adc4c792eeb195717de2bcc7b39be1ce77959d78e87ef685 ./LICENSE c6ce66613fe24e44b86db05bb0ff42734f3109cff378eea1f33a5738463667d3 ./pyproject.toml +c9410f42241ee823291f7d4a46f314f70b163541a9879b32d018686558d7869a ./README.md f9d4e391eee30f9d6cb74404521826859c0aabe7a88708899ecf51c1da090626 ./reports/benchmark-report.md b8b508ae02706f1f807ef74add54aefe1f4cd488f45684e215a0241c891c269a ./reports/executive-summary.md a3eb564b35671d3757bc5cc5387f8eeca05f865ecc991fb5eaed003528bf6d11 ./requirements.lock 0cac0e472eba3359aa79e9674ff11a5fd0484b9c465fc1cb774c30938edcc5d7 ./requirements.txt e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./results/.gitkeep -7e0846d1c6654978825b9accd0500e1bc0e7701b7ba7768c1fdd121e12a4373a ./results/README.md +00e195fa5e86a63699b91131aec90b1928b68854ff6c5a5e6a60efcd27288232 ./results/README.md ed35c0aa5fe3ed6293c83ea5197af79add6837f187f0cb7ee9a715e45909e636 ./results/sample/example-run-metadata.json a35a62233b000188b3f22a1acfcf6a2f2cccdb9dfe7324a7d5870f0b8eea36f2 ./results/summaries/combined-summary.csv 0a3c4d3e8efbdd878c7303e07516a815c187cd717066aea55043ac251e0396c4 ./results/summaries/sglang-summary.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 +133169aa89cce5d0d3a9b5b900d76fc94838274113bf6d179ae7429cae42af23 ./results/summaries/tensorrt-llm-prefill-budget-validation.csv f7de43402a7474aa39f3e4bac55e59933ac930577e34f94405ad165446f717b6 ./results/summaries/tensorrt-llm-summary.csv b23f3b977e56f77d35b562b226ec112d2cebd11fccedddd81e60650ca5846fa3 ./results/summaries/vllm-summary.csv +e35723c2ebd5531edd871209fe43a4c9e1f2d2c20b4de2f217e920800af2206b ./scripts/analyze_prefill_budget.py 1f4a4309a8f5a9909dae41b5ce7738968848f967f74e8c04a2e5e8a155ee1876 ./scripts/full_benchmark.sh 9380bbc0f80642d14cefa04c5cd8fb8c166b3b5d117cada91b8bf1e1fff39ffd ./scripts/generate_charts.py 52cd89acdd68d2dae50a3ad3ffcf90e1fe32eb3fe01a896dcdda5759dd6cb33f ./scripts/smoke_test.sh -7a58a1faa8e502ada9ddf2adde31e35a40e8cdcbef4431f3bb38a14a7268de6d ./src/llm_engine_benchmark/__init__.py -7eaaa810e1759ee4c36603fe348ea84cdac7e6b7f0fad0bfc6df67afaf65f480 ./src/llm_engine_benchmark/cli.py 756e6fc00c6421d48cf0fa4ab1590548e7a751f2a9dcb0e5323c5c8a72f2a154 ./src/llm_engine_benchmark/client.py +86cd60b59ac2cc3687a764d66ae7d5eec573a100c617c1269ba19d0a6bcac5a3 ./src/llm_engine_benchmark/cli.py 844b2c190ebf00118095ce5c92723081e065e3eb0f0599102b5c09d6594e4bc3 ./src/llm_engine_benchmark/config.py e43a14a1019d648bdca921c9cd966996319a0817b047b7f093485887806af1d3 ./src/llm_engine_benchmark/datasets.py 7ddc4d0bcf64d5f8bc42be909b7a1a1a959b02004106e33f82e1b9ad85b1771e ./src/llm_engine_benchmark/default.yaml 1db5a9299c1ea0c77660af3f63783919ae14c7ee78c6e49cd5825a7dd8ff1692 ./src/llm_engine_benchmark/environment.py +7a58a1faa8e502ada9ddf2adde31e35a40e8cdcbef4431f3bb38a14a7268de6d ./src/llm_engine_benchmark/__init__.py 4b4d00a6cec6f07bb8d9b66ea3440444682b2b8e53e0082145f3a78b9481b363 ./src/llm_engine_benchmark/locking.py 39c69e8f9ba6f0cf63434dd707c4e2c4fa32252261bc3350ebc9a28045d33bce ./src/llm_engine_benchmark/metrics.py 3524a1e1ff67821c97adfcdf5d27ee1432dfb7b7ca221ec2c4b17a04bd8384ce ./src/llm_engine_benchmark/normalize.py -87e24b52123790ab838679cc20afcf833c29003bd576a62506c51ae0d26bb897 ./src/llm_engine_benchmark/orchestrator.py +acf9c658181d63171c6a406b9334b99fb1ad960e4cc4beebdfe04490e3dc4363 ./src/llm_engine_benchmark/orchestrator.py +fb5f87e0b594d0cf107f1f7daf2b9071a041ab43ea79cc2ac0e030ed19c960a4 ./src/llm_engine_benchmark/prefill_analysis.py 683efbecaaf3f046364c0fdb13e894327c9dcf9ee5f6107ebe52a864a5a54708 ./src/llm_engine_benchmark/report.py 6a796ec8f46984d2ce8a638bdbfbf257dc24225259efb3146eeeacd50e54273c ./src/llm_engine_benchmark/ruler.py -91354620c19514a6489cb2b75a0df3625f23aabe4899cad2cd8e237ed1002701 ./src/llm_engine_benchmark/server.py +e456acd2248fddc306464828644e0cf19ac61961c1be8ecc5829f81297e07ffc ./src/llm_engine_benchmark/server.py cd242ca1da0bec94de9b15093feeaac8279ebc72c3d379630c771190140122fa ./src/llm_engine_benchmark/telemetry.py 45ab67f4aed6a1e104cefb45231645dd24481f8618b906ae75ab90d3dd29a1da ./src/llm_engine_benchmark/util.py 01511b0dc3ada8d1bc99dc489c55ca957f5a155d8307d3e69a0290e3c7fc07f0 ./src/llm_engine_benchmark/validate.py -59f26bf1d17ba3200c883740a998e947b3fa31e274fdd4e4c6d26d95b8d385e4 ./tests/test_cli.py 89c8fe02dba6b2f3fccd9dd2bb32933cd2c612c251dc10ebea5dfcab10c58b17 ./tests/test_client.py +e18e27d122413b27b246e6fa4d5e27e05893b592ee0acb920793ce55eff1c187 ./tests/test_cli.py 3b74c7b4d48d9be2c383cd03c2d6779da495b6beb8b258253e06e5a9306ece24 ./tests/test_config.py 49b879b257a013957a5a90bda9ae0812fad67cb7d19a40d3965448ba0ea1b367 ./tests/test_datasets.py 3f856fa35069b6b359ac0454eeb91d9206f57fa620d26cf7fb4fade2b589ae38 ./tests/test_locking.py 092803291540aa802307989209272861c4888a9a5b55c4bf9144d6e6ce6d7717 ./tests/test_normalize.py dda11cd56fb8d3fd5df784fa9a71fd937d228cd088509dbed9840d58471515af ./tests/test_orchestrator.py +2a340bdf3e1553a7076c2adf19118d0c020013d689492f650e9ef52eacfac395 ./tests/test_prefill_analysis.py 5a94e2982151154b7b77d11683801d88e745020aaa1bfb9686b05e5f59b1de8f ./tests/test_report.py 3e71e6162974119dca02f705097b70547ce510742f99e4f9f76830420f0741c6 ./tests/test_ruler.py -d45119c2b0ad3276a0d364c601c8efdb3b4f241b3ac7db3c839ba94b7e2a0b96 ./tests/test_server.py +ea05e20f7365695cbaf5fc85ad5dcb91fb2ef72efe3195346b05e815d8ca13bb ./tests/test_server.py 489e34e4b5807e58baefd7835d9f26fa79472a48ba77b12dc0990770403c59da ./tests/test_util.py +ccb0caa1942e9ca329541dd7d00eeb357a44d7403dbcfab75478006d3b47a314 ./THIRD_PARTY.md diff --git a/README.md b/README.md index bdf2b50..9814b53 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ A reproducible, neutral benchmark for choosing a long-context serving stack on N ![Decision dashboard](assets/charts/measured-ttft-throughput-operating-points.svg) -> The checked-in cross-engine values are preliminary one-repetition evidence. They are useful for portfolio review and experiment planning, but are not a final universal ranking. Run the three-repetition matrix before making production decisions. +> The checked-in cross-engine values are preliminary one-repetition evidence. They are useful for portfolio review and experiment planning, but are not a final universal ranking. Run the three-repetition matrix before making production decisions. The separate TensorRT-LLM prefill-budget study uses three 100-request repetitions and profiler-backed evidence. ## What this project demonstrates @@ -18,7 +18,9 @@ A reproducible, neutral benchmark for choosing a long-context serving stack on N ## Preliminary headline findings -For the supplied warm shared-prefix comparison at C1/C2/C4, TensorRT-LLM has the lowest reported TTFT and E2E latency and the highest reported request throughput. The supplied data uses one repetition per configuration; the cold C4 TensorRT-LLM ITL P95 anomaly is retained as a profiling target rather than explained causally. +For the supplied warm shared-prefix comparison at C1/C2/C4, TensorRT-LLM has the lowest reported TTFT and E2E latency and the highest reported request throughput. The supplied cross-engine data uses one repetition per configuration. + +The TensorRT-LLM cold-C4 anomaly has now been isolated separately. Across three 100-request repetitions, reducing the prefill budget from 8192 to 2048 improved P95 TTFT by 26.9% and P95 ITL by 42.1%, with a 2.1% output-throughput reduction. Nsight traces showed the longest attention kernel falling from 474.804 ms to 126.315 ms and the longest CUDA synchronization wait falling from 5.792 s to 1.485 s. See the [prefill-budget case study](docs/prefill-budget-case-study.md). See [results analysis](docs/results.md), [limitations](docs/fairness-and-limitations.md), and the compact [summary artifacts](results/README.md) for the evidence status and units. @@ -59,6 +61,16 @@ Run the full three-engine matrix: --concurrency 1,2,4 --repetitions 3 ``` +Capture an Nsight Systems trace for the TensorRT-LLM cold-C4 investigation: + +```bash +./bench run --config config/tensorrt-llm-profile-c4.yaml \ + --profile-nsys --overwrite +``` + +See the [profiling runbook](docs/profiling.md) for the baseline-first workflow, generated +artifacts, and the questions the trace must answer. + The smoke and full commands perform real inference and require Docker, NVIDIA Container Toolkit, model/data access, and sufficient disk. Ordinary CI runs tests, dry-run orchestration, package checks, and manifest verification only; it does not run GPU inference. ## Reports, charts, and provenance @@ -88,6 +100,7 @@ accepted run JSON + request timings - [Architecture](docs/architecture.md) - [Results and analysis](docs/results.md) - [Profiling plan](docs/profiling.md) +- [Prefill-budget case study](docs/prefill-budget-case-study.md) - [Fairness and limitations](docs/fairness-and-limitations.md) - [Production recommendations](docs/production-recommendations.md) - [Reproducibility and implementation details](docs/reproducibility.md) @@ -111,7 +124,8 @@ The repository excludes model weights, Hugging Face caches, TensorRT engines, se - [x] Cache evidence and result provenance - [x] CI and packaging validation - [ ] Three repetitions per matrix cell -- [ ] Nsight Systems profiling +- [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 - [ ] SLA-constrained throughput diff --git a/config/tensorrt-llm-profile-c4.yaml b/config/tensorrt-llm-profile-c4.yaml new file mode 100644 index 0000000..c7c42f4 --- /dev/null +++ b/config/tensorrt-llm-profile-c4.yaml @@ -0,0 +1,10 @@ +project: + engines: [tensorrt_llm] + cache_modes: [cold] + concurrency: [4] + repetitions: 1 + samples: 20 + cooldown_seconds: 5 + +paths: + results_dir: results/profiling/tensorrt-llm-cold-c4-trace diff --git a/docs/fairness-and-limitations.md b/docs/fairness-and-limitations.md index dee76cd..629a104 100644 --- a/docs/fairness-and-limitations.md +++ b/docs/fairness-and-limitations.md @@ -10,5 +10,9 @@ Current evidence has important limits: - The TensorRT-LLM release candidate may change before final validation. - Prefix-cache metrics can differ in precision and coverage across engines. - Results apply to the tested workload and should not be generalized to all inference workloads. +- The prefill-budget study is statistically repeated but covers TensorRT-LLM cold C4 only. It is a + scheduler-operating-point study, not a replacement for the neutral cross-engine matrix. +- Validation budgets were executed sequentially on one GB10, so run-order, thermal, and machine + effects cannot be completely excluded. Replication on the second DGX Spark is planned. The repository distinguishes observations, hypotheses, and profiler-backed conclusions. Raw logs, model weights, TensorRT engines, and large telemetry are intentionally excluded from source control. diff --git a/docs/prefill-budget-case-study.md b/docs/prefill-budget-case-study.md new file mode 100644 index 0000000..d829131 --- /dev/null +++ b/docs/prefill-budget-case-study.md @@ -0,0 +1,76 @@ +# TensorRT-LLM Long-Context Prefill-Budget Case Study + +## Problem + +TensorRT-LLM cold-prefix serving at concurrency four showed multi-second inter-token-latency +spikes for 120,000-token prompts. Multiple requests paused at the same time, pointing to shared +GPU or scheduler interference rather than an individual client or network delay. + +## Method + +The investigation used GPT-OSS-20B with 120,000 input tokens, 512 output tokens, FP8 KV cache, +continuous batching, and chunked prefill on one NVIDIA GB10. The exploratory sweep tested token +budgets 8192, 4096, 2048, and 1024. The final validation retained 8192, 4096, and 2048 and ran +three repetitions of 100 requests for each setting: 900 accepted requests with zero failures. + +The 8192 and 2048 settings were also captured with Nsight Systems' software CUDA collector. The +client metrics and profiler traces are separate evidence: client results quantify user-visible +behavior, while CUDA runtime and kernel records explain the execution mechanism. + +## Repeated validation + +Values are mean ± sample standard deviation across three accepted repetitions. + +| Budget | P95 TTFT | P95 ITL | Mean TPOT | P95 E2E | Output tok/s | +| ---: | ---: | ---: | ---: | ---: | ---: | +| 8192 | 87.162 ± 2.802 s | 2.216 ± 0.010 s | 0.288 ± 0.001 s | 229.749 ± 3.802 s | 9.226 ± 0.105 | +| 4096 | 70.404 ± 0.477 s | 1.986 ± 0.023 s | 0.304 ± 0.004 s | 224.406 ± 2.139 s | 9.314 ± 0.080 | +| 2048 | 63.749 ± 2.145 s | 1.284 ± 0.032 s | 0.323 ± 0.006 s | 229.986 ± 5.594 s | 9.029 ± 0.202 | + +Relative to 8192, the 2048 budget reduced P95 TTFT by 26.9% and P95 ITL by 42.1%, while output +throughput decreased by 2.1%. The 4096 budget produced the highest measured throughput and lowest +P95 E2E, making it the balanced operating point for this workload. + +## Profiler evidence + +| Budget | Profiled P95 ITL | Longest `cudaEventSynchronize` | Longest GPU kernel | +| ---: | ---: | ---: | ---: | +| 8192 | 1.961 s | 5.792 s | 474.804 ms | +| 2048 | 1.262 s | 1.485 s | 126.315 ms | + +The longest kernels in both traces were long-context paged-KV FlashAttention kernels. Reducing the +budget by four times shortened the longest kernel by 73.4% and the longest synchronization wait by +74.4%. `cudaEventSynchronize` is the host-side observation point, not the root cause: the host was +waiting for the preceding GPU work. + +The evidence supports this causal chain: + +```text +larger prefill budget + -> larger long-context prefill chunks + -> longer attention and model-execution windows + -> fewer opportunities to schedule active decode work + -> higher inter-token latency +``` + +## Decision + +- Use a 2048-token budget for latency-sensitive long-context traffic. +- Use a 4096-token budget when balancing streaming latency, completion latency, and throughput. +- Do not treat one budget as a universal default; select it from workload distributions and SLOs. +- Keep the neutral cross-engine comparison at the same matched-intent budget and report this + TensorRT-LLM tuning experiment separately. + +## Reproduction + +Generate the compact evidence directly from the accepted validation runs and Nsight SQLite files: + +```bash +python3 scripts/analyze_prefill_budget.py \ + --profile 8192=results/profiling/tensorrt-llm-cold-c4-cuda-sw-trace/tensorrt_llm/cold/c4/run_01 \ + --profile 2048=results/profiling/tensorrt-llm-cold-c4-budget-2048-confirmation/tensorrt_llm/cold/c4/run_01 +``` + +Raw request logs, telemetry, and profiler reports remain outside Git. Publish them as a separately +checksummed evidence bundle with the benchmark commit, model revision, image digest, and environment +metadata. diff --git a/docs/production-recommendations.md b/docs/production-recommendations.md index 2ea625f..b6230aa 100644 --- a/docs/production-recommendations.md +++ b/docs/production-recommendations.md @@ -8,5 +8,12 @@ | Flexible cache-aware serving | SGLang | Consistently competitive in the supplied comparison; validate on target traffic | | NVIDIA-optimized production stack | TensorRT-LLM + Triton | Optimized runtime plus production serving and observability; Triton comparison is planned | | Fast experimentation and broad compatibility | vLLM | Strong ecosystem and simpler model enablement | +| Latency-sensitive TensorRT-LLM 120K cold C4 | 2048-token prefill budget | Lowest validated P95 TTFT and P95 ITL among the repeated 8192/4096/2048 study | +| Balanced TensorRT-LLM 120K cold C4 | 4096-token prefill budget | Highest validated output throughput and lowest P95 E2E in the repeated study | These are workload-specific recommendations, not universal engine rankings. + +The prefill-budget recommendations come from three 100-request repetitions per setting. The +cross-engine recommendations remain preliminary until the complete three-repetition engine matrix +is available. Keep engine comparison controls matched by intent; do not compare a tuned +TensorRT-LLM result against untuned competing engines as if it were neutral evidence. diff --git a/docs/profiling.md b/docs/profiling.md index 7e73b69..4fb5920 100644 --- a/docs/profiling.md +++ b/docs/profiling.md @@ -1,11 +1,95 @@ -# Profiling Plan +# Nsight Systems Profiling Runbook Profiling is an evidence-gathering phase, not a substitute for the neutral benchmark. -1. Repeat the cold C4 configuration and confirm the ITL P95 outlier. -2. Capture Nsight Systems traces for representative C1 and C4 cold/warm runs. -3. Correlate request timestamps with scheduler batches, GPU kernels, KV-cache allocation, and queueing. -4. Compare prefill/decode overlap and kernel launch behavior across engines. -5. Record profiler version, capture command, image digest, driver, and CUDA versions beside the trace. +## First investigation: TensorRT-LLM cold C4 + +The checked-in preliminary results contain a cold C4 ITL P95 outlier. Investigate it in +two phases so profiler overhead is not confused with normal serving performance. + +### Phase A: confirm the symptom without a profiler + +Run three repetitions using the full 100-request population: + +```bash +./bench run \ + --config config/tensorrt-llm-profile-c4.yaml \ + --results-dir results/profiling/tensorrt-llm-cold-c4-baseline \ + --samples 100 \ + --repetitions 3 \ + --overwrite +``` + +Confirm whether ITL P95 is consistently elevated and identify the affected requests in +`request_results.jsonl`. Do not profile until the symptom is reproducible. + +### Phase B: capture a representative trace + +Start with 20 requests to keep the trace manageable: + +```bash +./bench run \ + --config config/tensorrt-llm-profile-c4.yaml \ + --profile-nsys \ + --overwrite +``` + +If the outlier does not occur in the 20-request trace, repeat with `--samples 100`. + +The harness profiles the inference server inside its GPU container. On DGX Spark/GB10 it uses +Nsight's software CUDA collector (`cuda-sw`) because the default hardware collector can create a +report without CUDA activities. The profiling container receives `SYS_PTRACE`; ordinary benchmark +runs do not. The harness performs a fail-fast check for `nsys`, records the profiler version, sends +`SIGINT` during shutdown so Nsight can export cleanly, and rejects the run unless the report contains +both CUDA API and GPU-kernel summaries. + +Each run directory retains: + +| Artifact | Purpose | +| --- | --- | +| `profiling/server.nsys-rep` | Nsight Systems timeline | +| `profiling/nsys_version.txt` | Profiler version | +| `profiling/profile_manifest.json` | Capture completeness and trace domains | +| `profiling/cuda_summary.txt` | CUDA API and GPU-kernel summaries generated with the collector image | +| `profiling/cuda_trace_validation.json` | Machine-readable CUDA trace validation result | +| `server_command.txt` | Exact container and profiler command | +| `request_results.jsonl` | Per-request TTFT, ITL, and E2E evidence | +| `telemetry/` and `metrics_diff.json` | GPU/host and engine metrics | +| `environment/` | Driver, CUDA, image, and benchmark provenance | + +The first trace includes server startup and model initialization as well as the measured +workload. Use the request results and timestamped server log to locate the measured interval; +do not interpret initialization kernels as request-serving behavior. + +Open the trace in Nsight Systems UI, or generate the standard command-line summaries: + +```bash +nsys stats \ + --report cuda_gpu_kern_sum,cuda_api_sum,osrt_sum \ + results/profiling/tensorrt-llm-cold-c4-trace/tensorrt_llm/cold/c4/run_01/profiling/server.nsys-rep +``` + +## Analysis questions + +1. Does the outlier align with a long GPU kernel, a gap between launches, or scheduler queueing? +2. Are decode iterations interrupted while another request performs prefill work? +3. Does batch composition or active-sequence count change immediately before the ITL spike? +4. Is GPU compute saturated, or are there CPU/runtime launch gaps? +5. Do KV-cache allocation, eviction, or memory-pressure metrics change at the same time? + +After cold C4 is explained, capture matched cold C1 and warm C4 controls and compare prefill/decode +overlap, launch behavior, and memory pressure across engines. Do not turn an observed correlation into a root-cause claim until the trace supports it. + +## Completed cold-C4 finding + +The investigation found a prefill/decode interference mechanism. At an 8192-token budget, the +longest long-context attention kernel was 474.804 milliseconds and the longest host-side CUDA +synchronization wait was 5.792 seconds. With a 2048-token budget, these fell to 126.315 milliseconds +and 1.485 seconds. The corresponding profiled P95 ITL fell from 1.961 seconds to 1.262 seconds. + +The causal claim is supported by both a controlled configuration change and the expected change in +GPU execution duration. See [the prefill-budget case study](prefill-budget-case-study.md). Cold-C1 +and warm-C4 traces remain useful controls but are no longer required to establish this particular +mechanism. diff --git a/docs/results.md b/docs/results.md index 0c6a76f..b454f8f 100644 --- a/docs/results.md +++ b/docs/results.md @@ -22,4 +22,18 @@ TensorRT-LLM also leads the supplied preliminary request-throughput table at C1/ - Evidence required: Nsight Systems traces, runtime metrics, kernel timing, queueing data, and batch formation. - Conclusion: TensorRT-LLM is the measured leader for this workload; the experiment does not isolate the causal mechanism. -The cold C4 TensorRT-LLM ITL P95 anomaly of approximately 2.15 seconds is retained as a profiling target. It should be investigated for prefill/decode interference, scheduler contention, KV-cache pressure, queueing, and request-level outliers. +## TensorRT-LLM cold-C4 prefill-budget study + +The cold-C4 anomaly was reproduced, profiled, and tested with a causal intervention. Across three +100-request repetitions, reducing the token budget from 8192 to 2048 reduced P95 TTFT from +87.162 seconds to 63.749 seconds and P95 ITL from 2.216 seconds to 1.284 seconds. Output throughput +changed from 9.226 to 9.029 tokens per second. A 4096-token budget produced the highest measured +output throughput, 9.314 tokens per second, and the lowest measured P95 E2E, 224.406 seconds. + +Nsight evidence explains the latency change. The longest long-context attention kernel fell from +474.804 milliseconds at budget 8192 to 126.315 milliseconds at budget 2048. The longest +`cudaEventSynchronize` wait fell from 5.792 seconds to 1.485 seconds. The synchronization call is +where the host waited for GPU completion; the long prefill execution window is the bottleneck. + +See the [complete case study](prefill-budget-case-study.md) for repeated-run variation, limitations, +operating-point recommendations, and the reproduction command. diff --git a/results/README.md b/results/README.md index db9251a..b74abc6 100644 --- a/results/README.md +++ b/results/README.md @@ -2,4 +2,4 @@ Tracked artifacts are compact and reviewable: summary CSVs, representative metadata, and report outputs. Raw request logs, server logs, telemetry, model weights, Hugging Face caches, and TensorRT engines are ignored. -The `summaries/` files are preliminary portfolio evidence and must not be confused with a completed three-repetition matrix. Full artifacts can be attached to a GitHub Release with the matching lock file, image digest, environment manifest, and benchmark commit. +The cross-engine `summaries/` files are preliminary portfolio evidence and must not be confused with a completed three-repetition matrix. The TensorRT-LLM prefill-budget summary is generated separately from its three-repetition validation and paired Nsight profiles. Full artifacts can be attached to a GitHub Release with the matching lock file, image digest, environment manifest, and benchmark commit. diff --git a/results/summaries/tensorrt-llm-prefill-budget-analysis.md b/results/summaries/tensorrt-llm-prefill-budget-analysis.md new file mode 100644 index 0000000..32473ec --- /dev/null +++ b/results/summaries/tensorrt-llm-prefill-budget-analysis.md @@ -0,0 +1,24 @@ +# TensorRT-LLM Prefill-Budget Analysis + +## Repeated validation + +| Budget | Valid runs | Requests | TTFT P95 | ITL P95 | TPOT mean | E2E P95 | Output tok/s | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 8192 | 3 | 300 | 87.162 ± 2.802 s | 2.216 ± 0.010 s | 0.288 ± 0.001 s | 229.749 ± 3.802 s | 9.226 ± 0.105 | +| 4096 | 3 | 300 | 70.404 ± 0.477 s | 1.986 ± 0.023 s | 0.304 ± 0.004 s | 224.406 ± 2.139 s | 9.314 ± 0.080 | +| 2048 | 3 | 300 | 63.749 ± 2.145 s | 1.284 ± 0.032 s | 0.323 ± 0.006 s | 229.986 ± 5.594 s | 9.029 ± 0.202 | + +## Profiler evidence + +| Budget | Client ITL P95 | Longest CUDA synchronization | Longest GPU kernel | +| ---: | ---: | ---: | ---: | +| 8192 | 1.961 s | 5.792 s | 474.804 ms | +| 2048 | 1.262 s | 1.485 s | 126.315 ms | + +## Decision + +- Latency-oriented operating point: **2048 tokens**. +- Balanced operating point: **4096 tokens**. +- Relative to 8192, the latency-oriented setting changed P95 ITL by -42.0% and output throughput by -2.1%. +- `cudaEventSynchronize` records where the host waited; the preceding GPU work is the causal bottleneck. +- Conclusions are workload-specific and do not establish a universal engine default. diff --git a/results/summaries/tensorrt-llm-prefill-budget-profiling.csv b/results/summaries/tensorrt-llm-prefill-budget-profiling.csv new file mode 100644 index 0000000..98ecf1e --- /dev/null +++ b/results/summaries/tensorrt-llm-prefill-budget-profiling.csv @@ -0,0 +1,3 @@ +budget,client_itl_p95_seconds,longest_cuda_event_synchronize_seconds,longest_gpu_kernel_milliseconds,longest_gpu_kernel_name +8192,1.9610234934058075,5.7918336,474.803584,fmha_v2_flash_attention_e4m3_fp32_128_128_S_q_paged_kv_64_causal_output_bf16_sm120_kernel_nl +2048,1.2623814903956372,1.484918592,126.3152,fmha_v2_flash_attention_e4m3_fp32_128_128_S_q_paged_kv_64_causal_output_bf16_sm120_kernel_nl diff --git a/results/summaries/tensorrt-llm-prefill-budget-provenance.json b/results/summaries/tensorrt-llm-prefill-budget-provenance.json new file mode 100644 index 0000000..a71a52d --- /dev/null +++ b/results/summaries/tensorrt-llm-prefill-budget-provenance.json @@ -0,0 +1,30 @@ +{ + "benchmark_commit": "2e7675424864d58ba2dedc6e4339fb98e06eeaf2", + "budgets": [ + 8192, + 4096, + 2048 + ], + "generated_at": "2026-09-04T21:22:35.314642+00:00", + "generated_by": "llm_engine_benchmark.prefill_analysis", + "profile_runs": { + "2048": "results/profiling/tensorrt-llm-cold-c4-budget-2048-confirmation/tensorrt_llm/cold/c4/run_01", + "8192": "results/profiling/tensorrt-llm-cold-c4-cuda-sw-trace/tensorrt_llm/cold/c4/run_01" + }, + "source_sha256": { + "results/profiling/tensorrt-llm-cold-c4-budget-2048-confirmation/tensorrt_llm/cold/c4/run_01/client_results.json": "ef8b5586497a7beaf6f1208657909fb5a2b3d3203d1bdb8b52a754ff4770fec7", + "results/profiling/tensorrt-llm-cold-c4-budget-2048-confirmation/tensorrt_llm/cold/c4/run_01/profiling/server.sqlite": "2ddf89853b8f7a924171fc48cec4a165aa045c9f56869f85d8cbd293eadbf0f7", + "results/profiling/tensorrt-llm-cold-c4-cuda-sw-trace/tensorrt_llm/cold/c4/run_01/client_results.json": "02b2f5d72d0c64bf365956fe4c67060571e1df6376e5fe1f194580d671ff4f3f", + "results/profiling/tensorrt-llm-cold-c4-cuda-sw-trace/tensorrt_llm/cold/c4/run_01/profiling/server.sqlite": "61d20ad9c1612eb0e85a3e448543ad9790c689e2aa59074a23cc0ca902d20e1b", + "results/validation/tensorrt-llm-cold-c4-budget-2048/tensorrt_llm/cold/c4/run_01/client_results.json": "0f4ee69eef4452374224b2f519f23b21ef8f04e26f9e291f528664081749a457", + "results/validation/tensorrt-llm-cold-c4-budget-2048/tensorrt_llm/cold/c4/run_02/client_results.json": "d4750897dd0c4e80b132cf727c90a6ad2d488f80c87599d6917a3d7376b93f4e", + "results/validation/tensorrt-llm-cold-c4-budget-2048/tensorrt_llm/cold/c4/run_03/client_results.json": "78a1d1f9771c32e71f08870c14d5172c976224319b003b6136232f7aed349847", + "results/validation/tensorrt-llm-cold-c4-budget-4096/tensorrt_llm/cold/c4/run_01/client_results.json": "9dc614cbc9b1ba21cf3ff3ff99228951756d036704dc82e20ace3621dcd5c34a", + "results/validation/tensorrt-llm-cold-c4-budget-4096/tensorrt_llm/cold/c4/run_02/client_results.json": "ace460ff451bac50a0a5e1e1a8b8fc91c63073e8d3bcd4972cd459da763db5b2", + "results/validation/tensorrt-llm-cold-c4-budget-4096/tensorrt_llm/cold/c4/run_03/client_results.json": "65776d6ba421bb4f184a893ab7dff2c067c1537770953b024a649de6c4cb0b33", + "results/validation/tensorrt-llm-cold-c4-budget-8192/tensorrt_llm/cold/c4/run_01/client_results.json": "09d0a23e2a91fd99d46d777640edfa8feecc5a893d606845f3e16d543606e4d4", + "results/validation/tensorrt-llm-cold-c4-budget-8192/tensorrt_llm/cold/c4/run_02/client_results.json": "531c0fdf8aa131593e6da6869e323d1714f50e254b25cb4b30a9c61aa0d20037", + "results/validation/tensorrt-llm-cold-c4-budget-8192/tensorrt_llm/cold/c4/run_03/client_results.json": "3a3a7a26cb8b1bdf7fd19007da1f9e98b5f767f1dbb34c0dd8193c1a6f43645b" + }, + "validation_root": "results/validation" +} diff --git a/results/summaries/tensorrt-llm-prefill-budget-validation.csv b/results/summaries/tensorrt-llm-prefill-budget-validation.csv new file mode 100644 index 0000000..25f02e7 --- /dev/null +++ b/results/summaries/tensorrt-llm-prefill-budget-validation.csv @@ -0,0 +1,4 @@ +budget,valid_repetitions,successful_requests,ttft_p95_seconds_mean,ttft_p95_seconds_sample_stdev,itl_p95_seconds_mean,itl_p95_seconds_sample_stdev,tpot_mean_seconds_mean,tpot_mean_seconds_sample_stdev,e2e_p95_seconds_mean,e2e_p95_seconds_sample_stdev,output_throughput_tokens_per_second_mean,output_throughput_tokens_per_second_sample_stdev +8192,3,300,87.16179139365,2.8023830367062343,2.2160303817979483,0.010201356953621446,0.2879500029700708,0.0012250505294536364,229.7491008348484,3.8018432469258965,9.2263305454893,0.10521176924221654 +4096,3,300,70.40381983356565,0.4765942418087328,1.986369879886721,0.022541982605652194,0.303541531748537,0.0035461050239294235,224.40588026678742,2.138886458942664,9.313522050899044,0.08040485233846667 +2048,3,300,63.74949379723306,2.145473568672258,1.28425742136266,0.03210503998552844,0.322855432581839,0.006250171407721364,229.9857185234917,5.593634450146551,9.028506742886726,0.20165657857863417 diff --git a/scripts/analyze_prefill_budget.py b/scripts/analyze_prefill_budget.py new file mode 100755 index 0000000..16f8789 --- /dev/null +++ b/scripts/analyze_prefill_budget.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Generate compact validation and Nsight evidence for the prefill-budget study.""" + +from llm_engine_benchmark.prefill_analysis import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/llm_engine_benchmark/cli.py b/src/llm_engine_benchmark/cli.py index f1efbe9..b356336 100644 --- a/src/llm_engine_benchmark/cli.py +++ b/src/llm_engine_benchmark/cli.py @@ -88,6 +88,11 @@ def build_parser() -> argparse.ArgumentParser: run.add_argument("--overwrite", action="store_true") run.add_argument("--keep-going", action="store_true") run.add_argument("--dry-run", action="store_true") + run.add_argument( + "--profile-nsys", + action="store_true", + help="Profile each inference server with Nsight Systems and retain a .nsys-rep trace", + ) report = subparsers.add_parser("report", help="Aggregate completed run artifacts") _add_common_config_flags(report) @@ -345,6 +350,7 @@ def main(argv: Sequence[str] | None = None) -> int: overwrite=args.overwrite, keep_going=args.keep_going, dry_run=args.dry_run, + profile_nsys=args.profile_nsys, ) summary = run_experiment(config, lock, options=options) print(json.dumps(summary, indent=2, sort_keys=True)) diff --git a/src/llm_engine_benchmark/orchestrator.py b/src/llm_engine_benchmark/orchestrator.py index 1aabb54..119364f 100644 --- a/src/llm_engine_benchmark/orchestrator.py +++ b/src/llm_engine_benchmark/orchestrator.py @@ -50,6 +50,7 @@ class RunOptions: overwrite: bool = False keep_going: bool = False dry_run: bool = False + profile_nsys: bool = False @dataclass(frozen=True) @@ -137,6 +138,7 @@ def run_experiment( "sample_limit": options.sample_limit, "run_order": options.run_order, "dry_run": options.dry_run, + "profile_nsys": options.profile_nsys, }, "runs": [spec.__dict__ for spec in plan], "preparation_signature": preparation_signature(config, lock), @@ -144,7 +146,13 @@ def run_experiment( atomic_write_json(results_dir / "run_plan.json", plan_payload) if options.dry_run: - _print_dry_run(config, lock, plan, results_dir) + _print_dry_run( + config, + lock, + plan, + results_dir, + profile_nsys=options.profile_nsys, + ) return {"dry_run": True, "planned_runs": len(plan), "plan": str(results_dir / "run_plan.json")} for mode in options.modes: @@ -187,7 +195,14 @@ def run_experiment( f"Requested {options.sample_limit} samples but {records_path} contains only " f"{len(selected_records)}" ) - run_signature = _run_signature(config, lock, spec, selected_records, image_digests[spec.engine]) + run_signature = _run_signature( + config, + lock, + spec, + selected_records, + image_digests[spec.engine], + profile_nsys=options.profile_nsys, + ) action = _prepare_run_directory( run_dir, signature=run_signature, @@ -332,6 +347,7 @@ def _execute_one_run( "first-request long-context compilation is included in measured behavior." ), "design_compliant_full_run": _is_full_design(config, options), + "profile_nsys": options.profile_nsys, "status": "starting", } atomic_write_json(run_dir / "run_metadata.json", metadata) @@ -344,6 +360,7 @@ def _execute_one_run( lock=lock, run_dir=run_dir, skip_image_pull=True, + profile_nsys=options.profile_nsys, ) server.image_digest = image_digest telemetry_cfg = dict(config.get("telemetry", {})) @@ -496,6 +513,22 @@ def _execute_one_run( except Exception: pass server.stop() + if options.profile_nsys: + try: + server.validate_profile_artifacts() + except BenchmarkError as exc: + result["valid"] = False + validation_errors = list(result.get("validation_errors", [])) + validation_errors.append(str(exc)) + result["validation_errors"] = validation_errors + atomic_write_json(run_dir / "client_results.json", result) + metadata["status"] = "rejected" + metadata["client_valid"] = False + metadata["validation_errors"] = validation_errors + atomic_write_json(run_dir / "run_metadata.json", metadata) + raise + metadata["nsys_report"] = "profiling/server.nsys-rep" + atomic_write_json(run_dir / "run_metadata.json", metadata) def _build_runtime_warmup_prompt(tokenizer) -> str: @@ -534,7 +567,12 @@ def _prepare_images( def _print_dry_run( - config: Mapping[str, Any], lock: Mapping[str, Any], plan: Sequence[RunSpec], results_dir: Path + config: Mapping[str, Any], + lock: Mapping[str, Any], + plan: Sequence[RunSpec], + results_dir: Path, + *, + profile_nsys: bool = False, ) -> None: print(f"Dry-run plan: {len(plan)} sequential server configurations") for spec in plan: @@ -545,8 +583,11 @@ def _print_dry_run( lock=lock, run_dir=run_dir, skip_image_pull=True, + profile_nsys=profile_nsys, ) - args = server._build_server_args() # Render only; no Docker operation. + args = server._build_profiled_server_args( + server._build_server_args() + ) # Render only; no Docker operation. command = server._build_docker_command(args) print( f"{spec.order_index:02d}. {spec.engine} {spec.mode} c{spec.concurrency} " @@ -629,6 +670,8 @@ def _run_signature( spec: RunSpec, records: Sequence[Mapping[str, Any]], image_digest: str, + *, + profile_nsys: bool = False, ) -> str: material = { "preparation_signature": preparation_signature(config, lock), @@ -638,6 +681,7 @@ def _run_signature( "prompt_hashes": [record.get("metadata", {}).get("prompt_sha256") for record in records], "image_digest": image_digest, "engine_config": config["engines"][spec.engine], + "profile_nsys": profile_nsys, } return sha256_text(json.dumps(material, sort_keys=True, separators=(",", ":"))) @@ -659,6 +703,7 @@ def _experiment_scope_signature( "sample_limit": options.sample_limit, "run_order": options.run_order, "telemetry_enabled": options.telemetry_enabled, + "profile_nsys": options.profile_nsys, "require_server_token_usage": bool(config["project"].get("require_server_token_usage", True)), "cooldown_seconds": options.cooldown_seconds, "engine_configs": { diff --git a/src/llm_engine_benchmark/prefill_analysis.py b/src/llm_engine_benchmark/prefill_analysis.py new file mode 100644 index 0000000..de3191c --- /dev/null +++ b/src/llm_engine_benchmark/prefill_analysis.py @@ -0,0 +1,361 @@ +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import sqlite3 +import statistics +import subprocess +from collections.abc import Callable, Sequence +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path + +from .util import BenchmarkError + + +@dataclass(frozen=True) +class MetricSummary: + mean: float + sample_stdev: float + values: tuple[float, ...] + + +@dataclass(frozen=True) +class BudgetSummary: + budget: int + valid_repetitions: int + successful_requests: int + ttft_p95_seconds: MetricSummary + itl_p95_seconds: MetricSummary + tpot_mean_seconds: MetricSummary + e2e_p95_seconds: MetricSummary + output_throughput_tokens_per_second: MetricSummary + + +@dataclass(frozen=True) +class ProfileSummary: + budget: int + client_itl_p95_seconds: float + longest_cuda_event_synchronize_seconds: float + longest_gpu_kernel_milliseconds: float + longest_gpu_kernel_name: str + + +METRICS: dict[str, Callable[[dict], float]] = { + "ttft_p95_seconds": lambda result: float(result["ttft_seconds"]["p95"]), + "itl_p95_seconds": lambda result: float(result["itl_seconds"]["p95"]), + "tpot_mean_seconds": lambda result: float(result["tpot_seconds"]["mean"]), + "e2e_p95_seconds": lambda result: float(result["e2e_seconds"]["p95"]), + "output_throughput_tokens_per_second": lambda result: float( + result["output_throughput_tokens_per_second"] + ), +} + + +def _metric(values: list[float]) -> MetricSummary: + return MetricSummary( + mean=statistics.mean(values), + sample_stdev=statistics.stdev(values) if len(values) > 1 else 0.0, + values=tuple(values), + ) + + +def summarize_budget(validation_root: Path, budget: int) -> BudgetSummary: + run_root = ( + validation_root + / f"tensorrt-llm-cold-c4-budget-{budget}" + / "tensorrt_llm/cold/c4" + ) + result_paths = sorted(run_root.glob("run_[0-9][0-9]/client_results.json")) + if not result_paths: + raise BenchmarkError(f"No validation results found for budget {budget}: {run_root}") + + collected = {name: [] for name in METRICS} + successful_requests = 0 + for path in result_paths: + result = json.loads(path.read_text(encoding="utf-8")) + if result.get("valid") is not True: + raise BenchmarkError(f"Validation result is not accepted: {path}") + successful_requests += int(result["successful_requests"]) + for name, getter in METRICS.items(): + collected[name].append(getter(result)) + + metrics = {name: _metric(values) for name, values in collected.items()} + return BudgetSummary( + budget=budget, + valid_repetitions=len(result_paths), + successful_requests=successful_requests, + ttft_p95_seconds=metrics["ttft_p95_seconds"], + itl_p95_seconds=metrics["itl_p95_seconds"], + tpot_mean_seconds=metrics["tpot_mean_seconds"], + e2e_p95_seconds=metrics["e2e_p95_seconds"], + output_throughput_tokens_per_second=metrics[ + "output_throughput_tokens_per_second" + ], + ) + + +def summarize_profile(run_dir: Path, budget: int) -> ProfileSummary: + result_path = run_dir / "client_results.json" + database_path = run_dir / "profiling/server.sqlite" + if not result_path.exists() or not database_path.exists(): + raise BenchmarkError( + f"Profile {budget} requires client_results.json and profiling/server.sqlite: {run_dir}" + ) + + result = json.loads(result_path.read_text(encoding="utf-8")) + if result.get("valid") is not True: + raise BenchmarkError(f"Profile result is not accepted: {result_path}") + + connection = sqlite3.connect(database_path) + try: + sync_row = connection.execute( + """ + SELECT MAX(runtime.end - runtime.start) / 1000000000.0 + FROM CUPTI_ACTIVITY_KIND_RUNTIME AS runtime + JOIN StringIds AS strings ON runtime.nameId = strings.id + WHERE strings.value LIKE 'cudaEventSynchronize%' + """ + ).fetchone() + kernel_row = connection.execute( + """ + SELECT + (kernel.end - kernel.start) / 1000000.0, + strings.value + FROM CUPTI_ACTIVITY_KIND_KERNEL AS kernel + JOIN StringIds AS strings ON kernel.demangledName = strings.id + ORDER BY kernel.end - kernel.start DESC + LIMIT 1 + """ + ).fetchone() + finally: + connection.close() + + if not sync_row or sync_row[0] is None or not kernel_row: + raise BenchmarkError(f"CUDA runtime or kernel evidence is missing: {database_path}") + + return ProfileSummary( + budget=budget, + client_itl_p95_seconds=float(result["itl_seconds"]["p95"]), + longest_cuda_event_synchronize_seconds=float(sync_row[0]), + longest_gpu_kernel_milliseconds=float(kernel_row[0]), + longest_gpu_kernel_name=str(kernel_row[1]), + ) + + +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 _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 _write_validation_csv(path: Path, summaries: list[BudgetSummary]) -> None: + fields = ["budget", "valid_repetitions", "successful_requests"] + for metric in METRICS: + fields.extend((f"{metric}_mean", f"{metric}_sample_stdev")) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + for summary in summaries: + row: dict[str, object] = { + "budget": summary.budget, + "valid_repetitions": summary.valid_repetitions, + "successful_requests": summary.successful_requests, + } + for metric in METRICS: + value = getattr(summary, metric) + row[f"{metric}_mean"] = value.mean + row[f"{metric}_sample_stdev"] = value.sample_stdev + writer.writerow(row) + + +def _write_profile_csv(path: Path, profiles: list[ProfileSummary]) -> None: + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(asdict(profiles[0]))) + writer.writeheader() + for profile in profiles: + writer.writerow(asdict(profile)) + + +def _percent_change(candidate: float, control: float) -> float: + return ((candidate / control) - 1.0) * 100.0 + + +def _write_markdown( + path: Path, summaries: list[BudgetSummary], profiles: list[ProfileSummary] +) -> None: + control = max(summaries, key=lambda row: row.budget) + latency = min(summaries, key=lambda row: row.itl_p95_seconds.mean) + balanced = max(summaries, key=lambda row: row.output_throughput_tokens_per_second.mean) + itl_change = _percent_change( + latency.itl_p95_seconds.mean, control.itl_p95_seconds.mean + ) + throughput_change = _percent_change( + latency.output_throughput_tokens_per_second.mean, + control.output_throughput_tokens_per_second.mean, + ) + lines = [ + "# TensorRT-LLM Prefill-Budget Analysis", + "", + "## Repeated validation", + "", + ( + "| Budget | Valid runs | Requests | TTFT P95 | ITL P95 | TPOT mean | " + "E2E P95 | Output tok/s |" + ), + "| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |", + ] + for row in sorted(summaries, key=lambda value: value.budget, reverse=True): + lines.append( + f"| {row.budget} | {row.valid_repetitions} | {row.successful_requests} | " + f"{row.ttft_p95_seconds.mean:.3f} ± {row.ttft_p95_seconds.sample_stdev:.3f} s | " + f"{row.itl_p95_seconds.mean:.3f} ± {row.itl_p95_seconds.sample_stdev:.3f} s | " + f"{row.tpot_mean_seconds.mean:.3f} ± {row.tpot_mean_seconds.sample_stdev:.3f} s | " + f"{row.e2e_p95_seconds.mean:.3f} ± {row.e2e_p95_seconds.sample_stdev:.3f} s | " + f"{row.output_throughput_tokens_per_second.mean:.3f} ± " + f"{row.output_throughput_tokens_per_second.sample_stdev:.3f} |" + ) + + lines.extend( + [ + "", + "## Profiler evidence", + "", + "| Budget | Client ITL P95 | Longest CUDA synchronization | Longest GPU kernel |", + "| ---: | ---: | ---: | ---: |", + ] + ) + for row in sorted(profiles, key=lambda value: value.budget, reverse=True): + lines.append( + f"| {row.budget} | {row.client_itl_p95_seconds:.3f} s | " + f"{row.longest_cuda_event_synchronize_seconds:.3f} s | " + f"{row.longest_gpu_kernel_milliseconds:.3f} ms |" + ) + + lines.extend( + [ + "", + "## Decision", + "", + f"- Latency-oriented operating point: **{latency.budget} tokens**.", + f"- Balanced operating point: **{balanced.budget} tokens**.", + f"- Relative to {control.budget}, the latency-oriented setting changed P95 ITL by " + f"{itl_change:.1f}% and output throughput by {throughput_change:.1f}%.", + ( + "- `cudaEventSynchronize` records where the host waited; the preceding GPU " + "work is the causal bottleneck." + ), + "- Conclusions are workload-specific and do not establish a universal engine default.", + "", + ] + ) + path.write_text("\n".join(lines), encoding="utf-8") + + +def generate_prefill_analysis( + *, + validation_root: Path, + budgets: Sequence[int], + profile_runs: dict[int, Path], + output_dir: Path, +) -> dict[str, Path]: + summaries = [summarize_budget(validation_root, budget) for budget in budgets] + if any(summary.valid_repetitions < 3 for summary in summaries): + raise BenchmarkError("Each budget requires at least three accepted validation repetitions") + profiles = [summarize_profile(path, budget) for budget, path in profile_runs.items()] + if not profiles: + raise BenchmarkError("At least one --profile BUDGET=RUN_DIR is required") + + output_dir.mkdir(parents=True, exist_ok=True) + outputs = { + "validation": output_dir / "tensorrt-llm-prefill-budget-validation.csv", + "profiles": output_dir / "tensorrt-llm-prefill-budget-profiling.csv", + "report": output_dir / "tensorrt-llm-prefill-budget-analysis.md", + "provenance": output_dir / "tensorrt-llm-prefill-budget-provenance.json", + } + _write_validation_csv(outputs["validation"], summaries) + _write_profile_csv(outputs["profiles"], profiles) + _write_markdown(outputs["report"], summaries, profiles) + validation_inputs = sorted( + path + for budget in budgets + for path in ( + validation_root + / f"tensorrt-llm-cold-c4-budget-{budget}" + / "tensorrt_llm/cold/c4" + ).glob("run_[0-9][0-9]/client_results.json") + ) + profile_inputs = sorted( + path + for run_dir in profile_runs.values() + for path in (run_dir / "client_results.json", run_dir / "profiling/server.sqlite") + ) + source_hashes = { + str(path): _sha256(path) for path in [*validation_inputs, *profile_inputs] + } + outputs["provenance"].write_text( + json.dumps( + { + "generated_at": datetime.now(timezone.utc).isoformat(), + "generated_by": "llm_engine_benchmark.prefill_analysis", + "benchmark_commit": _git_commit(), + "validation_root": str(validation_root), + "budgets": list(budgets), + "profile_runs": {str(key): str(value) for key, value in profile_runs.items()}, + "source_sha256": source_hashes, + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + return outputs + + +def _parse_profile(value: str) -> tuple[int, Path]: + try: + budget_text, path_text = value.split("=", 1) + return int(budget_text), Path(path_text) + except (ValueError, TypeError) as exc: + raise argparse.ArgumentTypeError("expected BUDGET=RUN_DIR") from exc + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Analyze TensorRT-LLM prefill-budget evidence") + parser.add_argument("--validation-root", type=Path, default=Path("results/validation")) + parser.add_argument("--budgets", default="8192,4096,2048") + parser.add_argument("--profile", action="append", type=_parse_profile, required=True) + parser.add_argument("--output-dir", type=Path, default=Path("results/summaries")) + args = parser.parse_args(argv) + + try: + budgets = tuple(int(value) for value in args.budgets.split(",")) + outputs = generate_prefill_analysis( + validation_root=args.validation_root, + budgets=budgets, + profile_runs=dict(args.profile), + output_dir=args.output_dir, + ) + except (BenchmarkError, ValueError) 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/server.py b/src/llm_engine_benchmark/server.py index 0241894..3675495 100644 --- a/src/llm_engine_benchmark/server.py +++ b/src/llm_engine_benchmark/server.py @@ -32,6 +32,7 @@ def __init__( lock: Mapping[str, Any], run_dir: str | Path, skip_image_pull: bool = False, + profile_nsys: bool = False, ) -> None: if engine not in SUPPORTED_ENGINES: raise BenchmarkError(f"Unsupported engine: {engine}") @@ -41,6 +42,8 @@ def __init__( self.engine_config = config["engines"][engine] self.run_dir = ensure_dir(run_dir) self.skip_image_pull = skip_image_pull + self.profile_nsys = profile_nsys + self.profile_dir = self.run_dir / "profiling" base_name = str(self.engine_config.get("container_name", f"llmbench-{engine}")) # A stable project-specific name lets a new invocation remove a stale # benchmark container left behind by a host reboot or hard interruption. @@ -111,8 +114,12 @@ def start(self) -> None: if self.image_digest is None: self.prepare_image() + if self.profile_nsys: + self._verify_nsys() + self.server_args = self._build_server_args() - command = self._build_docker_command(self.server_args) + launched_args = self._build_profiled_server_args(self.server_args) + command = self._build_docker_command(launched_args) self.run_command = command atomic_write_text(self.run_dir / "server_command.txt", command_text(command) + "\n") atomic_write_text(self.run_dir / "image_digest.txt", (self.image_digest or "unknown") + "\n") @@ -290,11 +297,21 @@ def stop(self) -> None: self.capture_inspect() self.capture_logs() subprocess.run( - ["docker", "stop", "--time", "30", self.container_name], + [ + "docker", + "stop", + "--time", + "120" if self.profile_nsys else "30", + self.container_name, + ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, ) + # The profiler prints export status during shutdown, so capture logs + # again while the stopped container still exists. + if self.profile_nsys: + self.capture_logs() subprocess.run( ["docker", "rm", "-f", self.container_name], stdout=subprocess.DEVNULL, @@ -302,6 +319,8 @@ def stop(self) -> None: check=False, ) self.started = False + if self.profile_nsys: + self._write_profile_manifest() def _assert_port_available(self) -> None: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: @@ -348,6 +367,17 @@ def _build_docker_command(self, server_args: Sequence[str]) -> list[str]: "-v", f"{paths['hf_cache_dir']}:/root/.cache/huggingface", ] + if self.profile_nsys: + ensure_dir(self.profile_dir) + command.extend( + [ + "--init", + "--stop-signal=SIGINT", + "--cap-add=SYS_PTRACE", + "-v", + f"{self.profile_dir.resolve()}:/benchmark-profile", + ] + ) if os.getenv("HF_TOKEN"): # Pass by name so the rendered command never contains the credential. command.extend(["-e", "HF_TOKEN"]) @@ -375,6 +405,138 @@ def _build_docker_command(self, server_args: Sequence[str]) -> list[str]: command.extend(server_args) return command + def _build_profiled_server_args(self, server_args: Sequence[str]) -> list[str]: + if not self.profile_nsys: + return list(server_args) + return [ + "nsys", + "profile", + # GB10's default hardware CUDA trace can produce a valid-looking + # report with no CUDA activities. The software collector is + # slower, but it reliably captures CUDA APIs and kernels. + "--trace=cuda-sw,nvtx,osrt", + "--sample=none", + "--cpuctxsw=none", + "--force-overwrite=true", + "--output=/benchmark-profile/server", + *server_args, + ] + + def _verify_nsys(self) -> None: + """Fail before model startup if the runtime image lacks Nsight Systems.""" + completed = subprocess.run( + [ + "docker", + "run", + "--rm", + "--entrypoint", + "/bin/sh", + self._runtime_image_reference(), + "-lc", + "command -v nsys >/dev/null 2>&1 && nsys --version", + ], + text=True, + capture_output=True, + check=False, + timeout=60, + ) + if completed.returncode != 0: + raise BenchmarkError( + "--profile-nsys was requested, but nsys is unavailable in the runtime image " + f"{self.image}. Use an image containing Nsight Systems CLI." + ) + ensure_dir(self.profile_dir) + atomic_write_text(self.profile_dir / "nsys_version.txt", completed.stdout.strip() + "\n") + + def _write_profile_manifest(self) -> None: + artifacts = sorted( + path.name + for path in self.profile_dir.glob("*") + if path.is_file() and path.name != "profile_manifest.json" + ) + reports = [name for name in artifacts if name.endswith(".nsys-rep")] + validation_path = self.profile_dir / "cuda_trace_validation.json" + cuda_trace_valid = None + if validation_path.exists(): + try: + cuda_trace_valid = bool(json.loads(validation_path.read_text())["valid"]) + except (json.JSONDecodeError, KeyError, TypeError): + cuda_trace_valid = False + atomic_write_json( + self.profile_dir / "profile_manifest.json", + { + "profiler": "NVIDIA Nsight Systems", + "trace_domains": ["cuda-sw", "nvtx", "osrt"], + "server_lifecycle_profiled": True, + "expected_report": "server.nsys-rep", + "report_complete": bool(reports), + "cuda_trace_valid": cuda_trace_valid, + "artifacts": artifacts, + "captured_at": utc_now(), + }, + ) + + def validate_profile_artifacts(self) -> None: + if not self.profile_nsys: + return + reports = sorted(self.profile_dir.glob("*.nsys-rep")) + if not reports: + raise BenchmarkError( + "Nsight Systems did not produce a .nsys-rep file. Inspect profiling/" + "profile_manifest.json and server.log." + ) + report = self.profile_dir / "server.nsys-rep" + if not report.is_file(): + report = reports[0] + self._validate_nsys_cuda_trace(report) + + def _validate_nsys_cuda_trace(self, report: Path) -> None: + """Analyze with the collector image and reject CPU-only Nsight reports.""" + completed = subprocess.run( + [ + "docker", + "run", + "--rm", + "-v", + f"{self.profile_dir.resolve()}:/benchmark-profile", + "--entrypoint", + "/bin/sh", + self._runtime_image_reference(), + "-lc", + "nsys stats --force-export=true " + "--report cuda_gpu_kern_sum,cuda_api_sum " + f"/benchmark-profile/{report.name}", + ], + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=False, + timeout=600, + ) + summary = completed.stdout or "" + atomic_write_text(self.profile_dir / "cuda_summary.txt", summary) + valid = ( + completed.returncode == 0 + and "CUDA GPU Kernel Summary" in summary + and "CUDA API Summary" in summary + ) + atomic_write_json( + self.profile_dir / "cuda_trace_validation.json", + { + "valid": valid, + "report": report.name, + "returncode": completed.returncode, + "required_summaries": ["CUDA GPU Kernel Summary", "CUDA API Summary"], + "validated_at": utc_now(), + }, + ) + self._write_profile_manifest() + if not valid: + raise BenchmarkError( + "Nsight Systems produced a report without CUDA API and kernel data. " + "Inspect profiling/cuda_summary.txt and cuda_trace_validation.json." + ) + def _runtime_image_reference(self) -> str: """Run the exact image ID resolved before the experiment, not a mutable tag.""" if self.image_digest: diff --git a/tests/test_cli.py b/tests/test_cli.py index e82d85e..c4945e7 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2,7 +2,7 @@ import unittest -from llm_engine_benchmark.cli import _build_dry_run_lock, _parse_engines +from llm_engine_benchmark.cli import _build_dry_run_lock, _parse_engines, build_parser class CliTests(unittest.TestCase): @@ -21,6 +21,10 @@ def test_dry_run_lock_is_network_independent(self) -> None: self.assertEqual(lock["model"]["commit_sha"], "dry-run") self.assertEqual(lock["model"]["tokenizer_commit_sha"], "dry-run") + def test_run_accepts_nsys_profile_flag(self) -> None: + args = build_parser().parse_args(["run", "--profile-nsys", "--dry-run"]) + self.assertTrue(args.profile_nsys) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_prefill_analysis.py b/tests/test_prefill_analysis.py new file mode 100644 index 0000000..0ff80b2 --- /dev/null +++ b/tests/test_prefill_analysis.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +import json +import sqlite3 +import tempfile +import unittest +from pathlib import Path + +from llm_engine_benchmark.prefill_analysis import ( + generate_prefill_analysis, + summarize_budget, + summarize_profile, +) + + +class PrefillAnalysisTests(unittest.TestCase): + def _write_validation(self, root: Path, budget: int) -> None: + for repetition, value in enumerate((1.0, 2.0, 3.0), start=1): + run = ( + root + / f"tensorrt-llm-cold-c4-budget-{budget}" + / "tensorrt_llm/cold/c4" + / f"run_{repetition:02d}" + ) + run.mkdir(parents=True) + result = { + "valid": True, + "successful_requests": 100, + "ttft_seconds": {"p95": value}, + "itl_seconds": {"p95": value / 10}, + "tpot_seconds": {"mean": value / 100}, + "e2e_seconds": {"p95": value * 2}, + "output_throughput_tokens_per_second": 10 - value, + } + (run / "client_results.json").write_text(json.dumps(result), encoding="utf-8") + + def _write_profile(self, root: Path, budget: int) -> Path: + run = root / f"profile-{budget}" + (run / "profiling").mkdir(parents=True) + (run / "client_results.json").write_text( + json.dumps({"valid": True, "itl_seconds": {"p95": 1.25}}), + encoding="utf-8", + ) + connection = sqlite3.connect(run / "profiling/server.sqlite") + connection.executescript( + """ + CREATE TABLE StringIds (id INTEGER, value TEXT); + CREATE TABLE CUPTI_ACTIVITY_KIND_RUNTIME (start INTEGER, end INTEGER, nameId INTEGER); + CREATE TABLE CUPTI_ACTIVITY_KIND_KERNEL ( + start INTEGER, end INTEGER, demangledName INTEGER + ); + INSERT INTO StringIds VALUES (1, 'cudaEventSynchronize_v3020'); + INSERT INTO StringIds VALUES (2, 'flash_attention_kernel'); + INSERT INTO CUPTI_ACTIVITY_KIND_RUNTIME VALUES (0, 1500000000, 1); + INSERT INTO CUPTI_ACTIVITY_KIND_KERNEL VALUES (0, 125000000, 2); + """ + ) + connection.commit() + connection.close() + return run + + def test_summarizes_repeated_validation(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + self._write_validation(root, 2048) + summary = summarize_budget(root, 2048) + self.assertEqual(summary.valid_repetitions, 3) + self.assertEqual(summary.successful_requests, 300) + self.assertEqual(summary.ttft_p95_seconds.mean, 2.0) + self.assertEqual(summary.ttft_p95_seconds.sample_stdev, 1.0) + + def test_reads_cuda_profile_and_writes_outputs(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + validation = root / "validation" + self._write_validation(validation, 2048) + profile = self._write_profile(root, 2048) + evidence = summarize_profile(profile, 2048) + self.assertEqual(evidence.longest_cuda_event_synchronize_seconds, 1.5) + self.assertEqual(evidence.longest_gpu_kernel_milliseconds, 125.0) + + outputs = generate_prefill_analysis( + validation_root=validation, + budgets=(2048,), + profile_runs={2048: profile}, + output_dir=root / "output", + ) + self.assertTrue(all(path.exists() for path in outputs.values())) + report = outputs["report"].read_text(encoding="utf-8") + self.assertIn("Latency-oriented operating point: **2048 tokens**", report) + provenance = json.loads(outputs["provenance"].read_text(encoding="utf-8")) + self.assertEqual(len(provenance["source_sha256"]), 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_server.py b/tests/test_server.py index 458ded5..6b60444 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -220,6 +220,93 @@ def test_tensorrt_llm_uses_pinned_openai_server(self) -> None: self.assertIn("--max_seq_len", args) self.assertIn("--enable_chunked_prefill", args) + def test_nsys_profile_wraps_server_and_mounts_output(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + revision = "a" * 40 + server = DockerEngineServer( + engine="tensorrt_llm", + config=self._config(root), + lock={"model": {"commit_sha": revision, "tokenizer_commit_sha": revision}}, + run_dir=root / "run", + skip_image_pull=True, + profile_nsys=True, + ) + args = server._build_profiled_server_args(server._build_server_args()) + command = server._build_docker_command(args) + + self.assertEqual(args[:2], ["nsys", "profile"]) + self.assertIn("--trace=cuda-sw,nvtx,osrt", args) + self.assertIn("--output=/benchmark-profile/server", args) + self.assertIn("--stop-signal=SIGINT", command) + self.assertIn("--cap-add=SYS_PTRACE", command) + self.assertIn( + f"{(root / 'run' / 'profiling').resolve()}:/benchmark-profile", + command, + ) + self.assertLess(command.index("nsys"), command.index("trtllm-serve")) + + def test_nsys_profile_manifest_detects_report(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + revision = "a" * 40 + server = DockerEngineServer( + engine="tensorrt_llm", + config=self._config(root), + lock={"model": {"commit_sha": revision, "tokenizer_commit_sha": revision}}, + run_dir=root / "run", + skip_image_pull=True, + profile_nsys=True, + ) + server.profile_dir.mkdir(parents=True) + (server.profile_dir / "server.nsys-rep").touch() + completed = subprocess.CompletedProcess( + args=[], + returncode=0, + stdout=( + "** CUDA GPU Kernel Summary (cuda_gpu_kern_sum):\n" + "** CUDA API Summary (cuda_api_sum):\n" + ), + ) + with mock.patch("subprocess.run", return_value=completed): + server._write_profile_manifest() + server.validate_profile_artifacts() + + manifest = json.loads( + (server.profile_dir / "profile_manifest.json").read_text() + ) + self.assertTrue(manifest["report_complete"]) + self.assertTrue(manifest["cuda_trace_valid"]) + self.assertIn("server.nsys-rep", manifest["artifacts"]) + + def test_nsys_profile_rejects_report_without_cuda_data(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + revision = "a" * 40 + server = DockerEngineServer( + engine="tensorrt_llm", + config=self._config(root), + lock={"model": {"commit_sha": revision, "tokenizer_commit_sha": revision}}, + run_dir=root / "run", + skip_image_pull=True, + profile_nsys=True, + ) + server.profile_dir.mkdir(parents=True) + (server.profile_dir / "server.nsys-rep").touch() + completed = subprocess.CompletedProcess( + args=[], + returncode=0, + stdout="SKIPPED: report does not contain CUDA trace data.\n", + ) + with mock.patch("subprocess.run", return_value=completed): + with self.assertRaisesRegex(BenchmarkError, "without CUDA API and kernel data"): + server.validate_profile_artifacts() + + validation = json.loads( + (server.profile_dir / "cuda_trace_validation.json").read_text() + ) + self.assertFalse(validation["valid"]) + def test_tensorrt_llm_rejects_unsupported_kv_cache_dtype(self) -> None: with tempfile.TemporaryDirectory() as temp: root = Path(temp)