{"name": "vllm", "version": "0.1.0", "hash": "sha256:130d177cc98ffc8ebc9bb1cb49110e28032d34a6eda21b9f459805cb5dae15f0", "files": {"ABSORB_REPORT.md": "# Absorb report: vllm\n\n- **Source:** https://github.com/vllm-project/vllm at `20da5d1983b6`\n- **Licence:** Apache-2.0\n- **Project names searched for:** vllm\n\n## What was absorbed\n\n| Piece | Kind | Class | Project names | Project paths |\n|---|---|---|---|---|\n| add-cli-arg | skill | mixed | vllm ×7 | vllm/engine/arg_utils.py, vllm/config, vllm/entrypoints/common/cli_args.py, rust/AGENTS.md, tests/engine/test_arg_utils.py |\n| check-api-compat | skill | mixed | vllm ×22 | vllm/entrypoints/openai/chat_completion, vllm/entrypoints/openai/completion, vllm/entrypoints/openai/responses, vllm/entrypoints/pooling/embed, vllm/entrypoints/serve/engine/protocol.py, vllm/entrypoints/anthropic, vllm/entrypoints/speech_to_text |\n| ci-fails-buildkite | skill | mixed | vllm ×4 | .buildkite/scripts/ci-fetch-log.sh, .buildkite/scripts/ci-clean-log.sh, docs/contributing/ci/failures.md |\n| debug-ima | skill | mixed | vllm ×6 |  |\n| kernel-microbenchmark | skill | mixed | vllm ×11 |  |\n| model-microbenchmark | skill | mixed | vllm ×12 | vllm/models |\n| model-recipes | skill | mixed | vllm ×23 | recipes/models, recipes/README.md |\n| pr-checklist | skill | mixed | vllm ×26 | vllm/v1/worker, vllm/v1/core/sched, vllm/v1/core, tests/AGENTS.md, csrc/AGENTS.md, .github/PULL_REQUEST_TEMPLATE.md, vllm/distributed/kv_transfer/kv_connector/v1/nixl, examples, csrc |\n| review-vllm-security | skill | mixed | vllm ×48 |  |\n| transformers-upgrade | skill | mixed | vllm ×62 | requirements/common.txt, requirements/test, tests/models/registry.py, vllm/transformers_utils/configs/__init__.py, vllm/transformers_utils/config.py, vllm/transformers_utils/processors/__init__.py, tests/transformers_utils, tests/config, tests/tokenizers_, tests/models/multimodal/processing/test_common.py, tests/models/test_initialization.py, vllm/models |\n| triton-kernel-writing | skill | mixed | vllm ×4 |  |\n\n## Needs review before sharing\n\nThese pieces mention the project by name or lean on its files. Move those facts into configuration, or keep the piece out of a shared starter.\n\n- **add-cli-arg** (skill): names vllm; paths vllm/engine/arg_utils.py, vllm/config, vllm/entrypoints/common/cli_args.py, rust/AGENTS.md, tests/engine/test_arg_utils.py\n- **check-api-compat** (skill): names vllm; paths vllm/entrypoints/openai/chat_completion, vllm/entrypoints/openai/completion, vllm/entrypoints/openai/responses, vllm/entrypoints/pooling/embed, vllm/entrypoints/serve/engine/protocol.py, vllm/entrypoints/anthropic, vllm/entrypoints/speech_to_text\n- **ci-fails-buildkite** (skill): names vllm; paths .buildkite/scripts/ci-fetch-log.sh, .buildkite/scripts/ci-clean-log.sh, docs/contributing/ci/failures.md\n- **debug-ima** (skill): names vllm\n- **kernel-microbenchmark** (skill): names vllm\n- **model-microbenchmark** (skill): names vllm; paths vllm/models\n- **model-recipes** (skill): names vllm; paths recipes/models, recipes/README.md\n- **pr-checklist** (skill): names vllm; paths vllm/v1/worker, vllm/v1/core/sched, vllm/v1/core, tests/AGENTS.md, csrc/AGENTS.md, .github/PULL_REQUEST_TEMPLATE.md, vllm/distributed/kv_transfer/kv_connector/v1/nixl, examples, csrc\n- **review-vllm-security** (skill): names vllm\n- **transformers-upgrade** (skill): names vllm; paths requirements/common.txt, requirements/test, tests/models/registry.py, vllm/transformers_utils/configs/__init__.py, vllm/transformers_utils/config.py, vllm/transformers_utils/processors/__init__.py, tests/transformers_utils, tests/config, tests/tokenizers_, tests/models/multimodal/processing/test_common.py, tests/models/test_initialization.py, vllm/models\n- **triton-kernel-writing** (skill): names vllm\n\n## Not absorbed\n\n- instruction files (AGENTS.md): they describe the project, so they stay with it. Pass --with-instructions to absorb them for review\n\n## Self-test\n\nNo case could be generated.\n", "ATTRIBUTION.md": "# Attribution: vllm\n\nThis harness was absorbed from https://github.com/vllm-project/vllm at commit `20da5d1983b671300cdd53a17621f24236313bdb` on 2026-11-27 with `baudrier absorb`.\n\n- **Licence:** Apache-2.0. Licence and notice files kept unchanged in this folder: `LICENSE`.\n- **Credit:** every file listed below is the work of the source repository's authors. Files were copied unchanged, except that hook commands name their folder as `${HARNESS_HOOKS}` and slash commands were wrapped as skills.\n\n## Absorbed files\n\n- `skills/add-cli-arg/SKILL.md` (skill)\n- `skills/check-api-compat/SKILL.md` (skill)\n- `skills/check-api-compat/agents/openai.yaml` (skill)\n- `skills/ci-fails-buildkite/SKILL.md` (skill)\n- `skills/debug-ima/SKILL.md` (skill)\n- `skills/debug-ima/agents/openai.yaml` (skill)\n- `skills/kernel-microbenchmark/SKILL.md` (skill)\n- `skills/kernel-microbenchmark/agents/openai.yaml` (skill)\n- `skills/kernel-microbenchmark/benchmarks/cupti_microbenchmark.py` (skill)\n- `skills/kernel-microbenchmark/benchmarks/graph_replay_benchmark.py` (skill)\n- `skills/kernel-microbenchmark/benchmarks/multi_gpu_gemm_rs.py` (skill)\n- `skills/model-microbenchmark/SKILL.md` (skill)\n- `skills/model-recipes/SKILL.md` (skill)\n- `skills/model-recipes/agents/openai.yaml` (skill)\n- `skills/model-recipes/scripts/read_recipe.sh` (skill)\n- `skills/pr-checklist/SKILL.md` (skill)\n- `skills/review-vllm-security/SKILL.md` (skill)\n- `skills/review-vllm-security/references/checks-by-change.md` (skill)\n- `skills/review-vllm-security/references/failure-modes/artifact-trust.md` (skill)\n- `skills/review-vllm-security/references/failure-modes/authorization.md` (skill)\n- `skills/review-vllm-security/references/failure-modes/cache-and-request-ownership.md` (skill)\n- `skills/review-vllm-security/references/failure-modes/fetch-and-decoder-policy.md` (skill)\n- `skills/review-vllm-security/references/failure-modes/input-invariants.md` (skill)\n- `skills/review-vllm-security/references/failure-modes/parser-and-rendering.md` (skill)\n- `skills/review-vllm-security/references/failure-modes/resource-budgets.md` (skill)\n- `skills/review-vllm-security/references/failure-modes/sensitive-output.md` (skill)\n- `skills/transformers-upgrade/SKILL.md` (skill)\n- `skills/transformers-upgrade/agents/openai.yaml` (skill)\n- `skills/transformers-upgrade/scripts/diff_dumps.py` (skill)\n- `skills/transformers-upgrade/scripts/dump_configs.py` (skill)\n- `skills/transformers-upgrade/scripts/dump_model.py` (skill)\n- `skills/transformers-upgrade/scripts/find_upstreamed.py` (skill)\n- `skills/triton-kernel-writing/SKILL.md` (skill)\n- `skills/triton-kernel-writing/agents/openai.yaml` (skill)\n", "LICENSE": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n", "harness.yaml": "$schema: https://harnessprotocol.io/schema/v1/harness.schema.json\nversion: '1'\nkind: profile\nmetadata:\n  name: vllm\n  description: 'The vLLM repository''s agent skills: CLI arguments, API compatibility, CI failures, benchmarks and security review.'\n  version: 0.1.0\n  license: Apache-2.0\nskills:\n- name: add-cli-arg\n  source: ./skills/add-cli-arg\n- name: check-api-compat\n  source: ./skills/check-api-compat\n- name: ci-fails-buildkite\n  source: ./skills/ci-fails-buildkite\n- name: debug-ima\n  source: ./skills/debug-ima\n- name: kernel-microbenchmark\n  source: ./skills/kernel-microbenchmark\n- name: model-microbenchmark\n  source: ./skills/model-microbenchmark\n- name: model-recipes\n  source: ./skills/model-recipes\n- name: pr-checklist\n  source: ./skills/pr-checklist\n- name: review-vllm-security\n  source: ./skills/review-vllm-security\n- name: transformers-upgrade\n  source: ./skills/transformers-upgrade\n- name: triton-kernel-writing\n  source: ./skills/triton-kernel-writing\nx-origin:\n  repository: https://github.com/vllm-project/vllm\n  commit: 20da5d1983b671300cdd53a17621f24236313bdb\n  license: Apache-2.0\n  license_basis: detected\n  license_files:\n  - LICENSE\n  absorbed_at: '2026-11-27'\n", "skills/add-cli-arg/SKILL.md": "---\nname: add-cli-arg\ndescription: \"Recipe for adding or changing a `vllm serve` / `vllm` CLI argument. Use when adding a flag to `EngineArgs` in `vllm/engine/arg_utils.py` or to the frontend args classes (`FrontendArgs`, `BaseFrontendArgs`, `BatchFrontendArgs`), exposing a config field on the command line, or changing an existing arg's type, default, or help text.\"\n---\n\n# Adding a CLI Argument\n\nEvery CLI arg is a field on a dataclass. The dataclass owns the type, default,\nhelp text, and validation. `get_kwargs(cls)` in `arg_utils.py` derives the\nargparse kwargs (type, choices, `BooleanOptionalAction`, JSON parsing, help)\nfrom the field's annotation and attribute docstring, so a correct field\nproduces a correct flag with no extra code.\n\nPick the **owner** first; it decides the recipe:\n\n| The arg configures | Owner | Recipe |\n| ------------------ | ----- | ------ |\n| The engine (model, cache, parallelism, scheduling, kernels, ...) | A config class in `vllm/config/` | [Engine args](#engine-args) |\n| The API server only (HTTP, chat templates, tool parsers, LoRA modules, ...) | `BaseFrontendArgs` (shared) or `FrontendArgs` (server only) in `vllm/entrypoints/common/cli_args.py` | [Frontend args](#frontend-args) |\n| `vllm run-batch` only | `BatchFrontendArgs` (search for `class BatchFrontendArgs`) | [Frontend args](#frontend-args) |\n\n## Decide whether a flag is needed\n\nPrefer automatic selection or a better default. If users must control it,\nwrite down why existing controls are not enough (the `pr-checklist` skill asks\nfor this).\n\n## Write the field\n\nSame for every owner:\n\n```python\nfoo_bar: int | None = Field(default=None, ge=0)\n\"\"\"What it does, how to enable it, and the default behaviour.\nThis docstring is the `--help` text and the rendered CLI reference.\"\"\"\n```\n\n- The owning classes are pydantic dataclasses, so validation lives on the\n  field and applies to the Python API as well as the CLI. Express bounds and\n  lengths as `pydantic.Field` constraints (`ge`, `gt`, `le`, `min_length`);\n  use a validator or `__post_init__` only for rules that span fields.\n- Mutable defaults use `Field(default_factory=...)`.\n- When the generated kwargs don't fit (wrong parser, missing choices), fix the\n  annotation, or extend `_compute_kwargs` in `arg_utils.py` so every class\n  gets the fix.\n\n## Engine args\n\nFields of a config exposed through a JSON arg (search `add_cli_args` for\n`--compilation-config`, `--attention-config`, `--kernel-config` and the other\n`--*-config` args) are already settable as `--x-config.field value`. Adding\nthe field to that config class is the whole change. Give such a field its own\nflag only when most users will set it, as `--attention-backend` does for\n`AttentionConfig.backend`; the steps below then apply as for any other field.\n\nOtherwise `EngineArgs` **mirrors** the config field, in three places in\n`arg_utils.py`:\n\n1. **`EngineArgs` field**: the config's annotation verbatim, and the default\n   read from the config class, never a literal, so the two cannot drift.\n\n   ```python\n   foo_bar: int | None = XConfig.foo_bar\n   foo_list: list[str] = get_field(XConfig, \"foo_list\")  # default_factory\n   ```\n\n2. **`add_cli_args`**: in the existing argument group for that config, pass\n   the `get_kwargs` output through untouched.\n\n   ```python\n   x_group.add_argument(\"--foo-bar\", **x_kwargs[\"foo_bar\"])\n   ```\n\n   The flag is the field name with dashes. When the field name is generic,\n   prefix both the flag and the `EngineArgs` field with the config's area\n   (`MambaConfig.backend` is `--mamba-backend` / `mamba_backend`).\n\n3. **Config construction**: add `foo_bar=self.foo_bar` to the `XConfig(...)`\n   call in `create_engine_config` or the matching `create_x_config` method.\n\n## Frontend args\n\nThe field is the whole change: `BaseFrontendArgs.add_cli_args` registers every\nfield of the class as `--field-name`. Read the value from the parsed `args`\nwhere the server is built.\n\n- Kwargs that `get_kwargs` cannot express go in the class's\n  `_customize_cli_kwargs` override, which calls `super()` first.\n- The Rust frontend serves the same flags. A flag it does not implement must\n  fail at startup or be a documented no-op; see `rust/AGENTS.md`.\n\n## Check it\n\n```bash\nvllm serve --help=foo-bar     # flag, default, and help text render\n.venv/bin/python -m pytest tests/engine/test_arg_utils.py -v\n```\n\nAdd a test to `tests/engine/test_arg_utils.py` only for behaviour beyond the\nfield itself (custom parsing, aliases, cross-field validation). A plain field\nis covered by the `get_kwargs` tests and needs none.\n\n## Changing an existing arg\n\nChange the owning field (type, default, docstring) and let the CLI follow.\nRenames and removals keep the old flag working with a deprecation warning\nthat names the removal version; search `arg_utils.py` for\n`DEPRECATION_MESSAGE` for the existing pattern.\n", "skills/check-api-compat/SKILL.md": "---\nname: check-api-compat\ndescription: Determine the correct behavior of vLLM's OpenAI-compatible or Anthropic-compatible API by checking the official upstream spec, instead of guessing from vLLM's own code. Use for any bug, issue, PR, review, or question touching /v1/chat/completions, /v1/completions, /v1/responses, /v1/embeddings, /v1/messages, or their request/response models — including \"is this a bug or intended\", \"what should this field default to\", \"does upstream allow this\", and any change that adds, removes, or renames a field on those models. Do not use for vLLM-internal APIs (engine, scheduler, LLM class) or for endpoints with no upstream counterpart.\n---\n\n# Checking vLLM API compatibility against the upstream spec\n\nvLLM's OpenAI and Anthropic server surfaces are *reimplementations* of someone\nelse's spec. vLLM's own code, tests, and docstrings are not evidence of correct\nbehavior — they are the thing under test. Establish what upstream says first,\nthen compare.\n\nNever answer \"what should this field do\" from memory. Field names, types, and\nespecially defaults drift between spec versions.\n\n## 1. Pin down the question\n\nName three things before looking anything up:\n\n- **Which surface** — OpenAI-compatible or Anthropic-compatible. They are separate\n  code paths in vLLM and separate specs.\n- **Which endpoint**, by path.\n- **Which field or behavior** — a request field, a response field, a streaming\n  event shape, an error code, or a status code.\n\n## 2. Read vLLM's implementation\n\nIn a vLLM checkout, the request/response models live beside each endpoint:\n\n| surface | path |\n| --- | --- |\n| OpenAI chat | `vllm/entrypoints/openai/chat_completion/` |\n| OpenAI completions | `vllm/entrypoints/openai/completion/` |\n| OpenAI responses | `vllm/entrypoints/openai/responses/` |\n| OpenAI embeddings | `vllm/entrypoints/pooling/embed/` |\n| OpenAI shared base models, errors, usage | `vllm/entrypoints/serve/engine/protocol.py` |\n| Anthropic messages | `vllm/entrypoints/anthropic/` |\n| audio | `vllm/entrypoints/speech_to_text/*/protocol.py` |\n\nEach directory holds `protocol.py` (the Pydantic models), `serving.py` (behavior),\nand `api_router.py` (routing and status codes). Read the field declaration *and*\nthe code that consumes it — a field can be declared faithfully and then ignored,\nwhich is still an incompatibility.\n\n## 3. Fetch the upstream spec\n\nPrefer a source that can actually be read as text, in this order.\n\n### OpenAI\n\n1. The OpenAPI spec — authoritative, machine-readable, and fetches cleanly:\n   `https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml`\n2. The installed `openai` Python SDK's typed params, which track the spec closely.\n   Locate them with `python -c \"import openai,os;print(os.path.dirname(openai.__file__))\"`,\n   then read e.g. `types/chat/completion_create_params.py`,\n   `types/chat/chat_completion.py`, `types/chat/chat_completion_chunk.py`,\n   `types/responses/`. Note the SDK version — an old SDK is an old spec.\n3. The prose reference at `https://platform.openai.com/docs/api-reference/...`\n   for semantics the types do not carry. It is script-heavy and often fetches\n   poorly; treat a failed fetch as a fetch failure, not as absence of a field.\n\n### Anthropic\n\n1. `https://docs.claude.com/en/api/messages` and\n   `https://docs.claude.com/en/api/messages-streaming` — these render as clean\n   text and are the primary source for both fields and streaming event order.\n2. The installed `anthropic` SDK's `types/message_create_params.py`,\n   `types/message.py`, `types/raw_message_stream_event.py`.\n\nSay which source and which version answered the question, so the finding can be\nre-checked later.\n\n## 4. Compare on all four axes\n\nA field is compatible only when **name**, **type**, **default**, and **semantics**\nall match. Most real bugs hide in the last two: a field that exists with the right\ntype but the wrong default, or one that is accepted and silently dropped.\n\nAlso check, when relevant:\n\n- **Streaming** — chunk shape, the order of events, and the terminal event\n  (`data: [DONE]` for Chat Completions and Completions; `response.completed`,\n  `response.failed`, or `response.incomplete` with no `[DONE]` for Responses;\n  `message_stop` for Anthropic).\n- **Errors** — HTTP status *and* the error body's `type`/`code` strings.\n- **Omitted vs null** — upstream often distinguishes an absent field from an\n  explicit `null`. Pydantic defaults erase that distinction unless the model is\n  written to preserve it.\n\n## 5. Classify before calling it a bug\n\nThree outcomes, and they are not the same:\n\n- **Matches upstream** — no action.\n- **vLLM extension** — a field upstream has no name for at all (`vllm_xargs`,\n  `chat_template_kwargs`, sampling knobs like `min_p`). These are intentional and\n  allowed. Do not report them as violations. Check per surface: `top_k` is an\n  extension on OpenAI but a real upstream field on Anthropic Messages.\n- **Incompatibility** — a field that *shares a name with upstream* but differs in\n  type, default, or behavior, or an upstream field that is missing, ignored, or\n  malformed. This is the reportable case.\n\nAn unsupported-but-declared field is its own subcase: decide whether vLLM rejects\nit explicitly or accepts and ignores it, and report which, since silently ignoring\na documented field is the more damaging failure.\n\n## 6. Report\n\nState: the endpoint and field, what upstream specifies (with the source), what\nvLLM does (with `file:line`), which of the three outcomes it is, and the smallest\nfix. When behavior turns on a spec detail that is easy to disbelieve, quote the\nupstream line rather than paraphrasing it.\n", "skills/check-api-compat/agents/openai.yaml": "interface:\n  display_name: \"Check API Compat\"\n  short_description: \"Check vLLM's OpenAI/Anthropic-compatible API against the upstream spec.\"\n  default_prompt: \"Use the vLLM API compatibility skill to check this endpoint or field against the upstream OpenAI or Anthropic spec.\"\n", "skills/ci-fails-buildkite/SKILL.md": "---\nname: ci-fails-buildkite\ndescription: Fetch and diagnose vLLM Buildkite CI failure logs. Use when investigating failing CI jobs on a PR or build, when the user pastes a buildkite.com URL, or asks to fetch/diagnose CI logs.\n---\n\n# Diagnosing vLLM Buildkite CI Failures\n\nBuildkite logs are public; no login needed.\n\n`.buildkite/scripts/ci-fetch-log.sh` saves each log as `ci-<build>-<job-name>.log`, stripped of timestamps and ANSI codes. Existing files are kept; set `CI_FETCH_LOG_FORCE=1` to refetch.\n\n## Fetching logs\n\n```bash\n# All failed jobs in a PR's latest build (current branch's PR if omitted):\n.buildkite/scripts/ci-fetch-log.sh --pr <PR>\n\n# All failed jobs in a build (--soft also includes soft-failed jobs;\n# --all fetches every finished job):\n.buildkite/scripts/ci-fetch-log.sh \"https://buildkite.com/vllm/ci/builds/<N>\"\n\n# One job — `gh pr checks` URLs (#<job_uuid>) and web UI URLs (?sid=) both\n# work; pass \"-\" as a second argument to stream to stdout:\n.buildkite/scripts/ci-fetch-log.sh \"https://buildkite.com/vllm/ci/builds/<N>#<job_uuid>\"\n```\n\nTo clean an already-downloaded log with `.buildkite/scripts/ci-clean-log.sh`:\n\n```bash\n./ci-clean-log.sh ci.log\n```\n\n## Reference\n\nSee [docs/contributing/ci/failures.md](../../../docs/contributing/ci/failures.md) for the full guide: filing CI failure issues, investigating/bisecting, reproducing flaky tests, and daily triage.\n", "skills/debug-ima/SKILL.md": "---\nname: debug-ima\ndescription: Debug CUDA illegal memory access (IMA) errors in vLLM with CUDA core dumps and cuda-gdb. Use when a vLLM run crashes or hangs with a CUDA illegal memory access, device-side assert, or other asynchronous CUDA error and the faulting kernel needs to be located.\n---\n\n# Debug IMA\n\nFollow the vLLM guide\n[CUDA Core Dump: An Effective Tool to Debug Memory Access Issues and Beyond](https://vllm.ai/blog/2025-08-11-cuda-debugging).\n", "skills/debug-ima/agents/openai.yaml": "interface:\n  display_name: \"Debug IMA\"\n  short_description: \"Debug CUDA illegal memory access errors in vLLM.\"\n  default_prompt: \"Use the vLLM CUDA core-dump guide to debug this illegal memory access error.\"\n", "skills/kernel-microbenchmark/SKILL.md": "---\nname: kernel-microbenchmark\ndescription: Build, debug, and interpret vLLM GPU kernel microbenchmarks for CUDA, ROCm/HIP, Triton, and CuteDSL, including CUPTI timing, correctness checks, generated-code inspection, multi-GPU measurements, and SOL sanity checks. Use when measuring or comparing the performance of a single GPU kernel or op, validating a claimed kernel speedup, or investigating a noisy or surprising benchmark result.\n---\n\n# Kernel Microbenchmark\n\n## Workflow\n\n1. Create an isolated repro or benchmark when the existing harness is noisy.\n2. Check correctness before timing. Keep tolerances explicit.\n3. Time only the operation under study. Exclude allocation, compilation, random\n   input generation, logging, and host-device transfers unless those are the\n   target.\n4. Compare against a baseline and report enough metadata to reproduce the\n   result: GPU, dtype, shape, command, branch/commit, and relevant env vars.\n5. Treat explanations as hypotheses until backed by an artifact: ablation,\n   generated PTX/SASS or AMD ISA, profiler output, or controlled benchmark.\n6. If the result changes the conclusion, preserve the compact lesson in a note,\n   comment, benchmark table, or final summary. For experiments, a short\n   `Question / Change / Correctness / Result / Observation / Next` note is\n   usually enough.\n\n## Benchmark Defaults\n\n- Use FlashInfer CUPTI timing by default, with CUDA graph and cold L2 cache:\n  `from flashinfer.testing import bench_gpu_time_with_cupti`.\n- ROCm: CUPTI and FlashInfer do not exist. Use HIP graph replay over rotating\n  buffers whose total footprint exceeds the last-level cache (e.g. 256 MB on\n  MI355X), so every call reads cold from HBM, timed with HIP events — see\n  [benchmarks/graph_replay_benchmark.py](benchmarks/graph_replay_benchmark.py)\n  (platform-agnostic). Prefer this over `do_bench`, whose per-rep\n  launch/event overhead inflates small/decode-size kernels.\n- For compute-heavy kernels, report TFLOPS with the FLOP formula in the\n  benchmark. For memory-heavy kernels, report estimated bytes moved and GB/s.\n  For mixed kernels, report the most honest metric available and call out the\n  caveats. TFLOPS and memory bandwidth should be computed from the theoretical\n  best for the operation, not from a particular kernel implementation. For\n  example, memory bandwidth should assume all data is read exactly once from\n  global memory.\n- When comparing across shapes, prefer throughput metrics such as TFLOPS or\n  GB/s as the primary table columns; keep latency for absolute cost.\n- If a result exceeds expected peak/SOL, first inspect units, FLOP/byte\n  formulas, skipped work, sparsity, caching, and whether the baseline is doing\n  the same operation.\n- Force compilation/autotuning before measuring compiled kernels.\n- Tune every arm of a comparison before trusting it. A variant's default or\n  inherited config can be far from its optimum, so conclusions drawn from\n  untuned variants — especially negative ones — are unreliable. A coarse\n  sweep of the cheap knobs at a couple of representative shapes is enough;\n  report the winning config with the numbers.\n- Seed inputs when correctness comparisons matter.\n- Keep metadata setup, plan construction, allocation, random input generation,\n  and logging outside the timed region unless that overhead is the experiment.\n\n## Sanity-Check Reference Numbers\n\nUse these as rough reference points for large, well-shaped workloads, not as\ngold standards, guaranteed peaks, or hard limits. Hardware SKU, clocks, shape,\nprecision conventions, and the FLOP/byte accounting can move the result. A\nlarge gap is a prompt to investigate, not proof that a kernel is poor.\n\n| Kernel regime | Hardware | Rough reference |\n| --- | --- | ---: |\n| Memory-bound, large batch | Blackwell | 6 TB/s |\n| BF16 GEMM | Blackwell | 2 PFLOP/s |\n| BF16 attention | B200 | 1.6 PFLOP/s |\n| FP8 GEMM | Blackwell | 4 PFLOP/s |\n| FP8 attention | B300 | 2.8 PFLOP/s |\n\nThe BF16 attention reference is approximately the 1613 TFLOP/s result reported\nby the FlashAttention-4 paper. Compare kernels only with matching workload and\nthroughput conventions.\n\n## Multi-GPU Benchmarks\n\n- State whether the run is local or multi-node and report the GPU topology,\n  world size, GPUs per node, collective backend, and relevant library versions.\n- Compare like-for-like TP configurations. Report both per-rank and global\n  dimensions, and do not compare results from different TP sizes without an\n  explicit normalization or scaling question.\n- Define the timed operation boundary before benchmarking. If the production\n  wrapper performs input staging, flag resets, generation barriers, padding,\n  or output copies, keep them in the timed region for an end-to-end comparison.\n  Use a separate, clearly labeled ablation for kernel-only timing.\n- Check distributed correctness before timing. Seed each rank deliberately,\n  form the reference with the same collective semantics, and synchronize before\n  reading or comparing outputs.\n- Use a device-side barrier immediately before each measured replay. Keep this\n  common synchronization outside the timed interval, but keep barriers required\n  by the candidate implementation inside it.\n- With CUDA graphs, warm up before capture, coordinate capture across ranks,\n  rotate pointer-distinct graphs when cache reuse matters, and ensure every\n  collective is issued in the same order on every rank.\n- Measure every rank and reduce each sample with `MAX`; report the median of\n  those per-sample maxima. A rank-local event time is not a distributed latency.\n- Reset reusable symmetric-memory flags before each invocation and establish a\n  device-side generation barrier before peers may signal them. Otherwise a fast\n  rank can signal before a slow rank resets its flags, causing a lost arrival\n  and intermittent deadlock.\n- Preserve symmetric-memory handles, CUDA graphs, streams, and graph outputs for\n  the full measurement lifetime. Allocate and rendezvous symmetric buffers in\n  identical order and with identical shapes on all ranks.\n- Treat hangs and isolated millisecond outliers as synchronization bugs or rank\n  skew until disproven. Add stage markers, bounded synchronization checks, and\n  per-rank diagnostics before blaming compilation or kernel performance.\n- For multi-node runs, record the scheduler allocation and verify the fabric\n  supports the required multicast or NVLink-domain assumptions. Do not describe\n  a two-node TP run as equivalent to a local NVLink-domain run without checking.\n- Stabilize GPU clocks or run enough untimed work to reach a steady state.\n  Alternate candidate order so clock, thermal, and rank-skew effects are shared.\n- ROCm: capturing ProcessGroupNCCL collectives in HIP graphs trips the NCCL\n  watchdog (HIP forbids querying an event recorded in a capturing stream;\n  the watchdog aborts the process). `TORCH_NCCL_BLOCKING_WAIT=1` before\n  `import torch` disables the watchdog — benchmark-only knob. Ask for backend\n  `\"nccl\"`; torch routes it to RCCL automatically (there is no `\"rccl\"`\n  backend string).\n\n## Included Examples\n\n- Use [benchmarks/cupti_microbenchmark.py](benchmarks/cupti_microbenchmark.py)\n  as a minimal single-GPU FlashInfer CUPTI timing pattern.\n- Use\n  [benchmarks/graph_replay_benchmark.py](benchmarks/graph_replay_benchmark.py)\n  as a graph-replay timing pattern over rotating buffers sized past the\n  last-level cache — the ROCm/HIP default, also usable on CUDA.\n- Use\n  [benchmarks/multi_gpu_gemm_rs.py](benchmarks/multi_gpu_gemm_rs.py) as a\n  minimal distributed CUDA-graph timing pattern.\n\nAdapt the operation, cases, work formula, and correctness tolerances rather\nthan copying either example unchanged.\n", "skills/kernel-microbenchmark/agents/openai.yaml": "interface:\n  display_name: \"Kernel Microbenchmark\"\n  short_description: \"Build and debug reliable GPU kernel microbenchmarks.\"\n  default_prompt: \"Use the kernel microbenchmark workflow to build or debug a vLLM GPU kernel benchmark.\"\n", "skills/kernel-microbenchmark/benchmarks/cupti_microbenchmark.py": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\n\"\"\"FlashInfer CUPTI microbenchmark template with throughput metrics.\"\"\"\n\nimport statistics\n\nimport pandas as pd\nimport torch\nfrom flashinfer.testing import bench_gpu_time_with_cupti\n\nWARMUP = 25\nMATMUL_CASES = [\n    (\"compute-bound\", 4096, 4096, 4096),\n    (\"small-M\", 16, 16384, 8192),\n]\n\n\ndef bench_us(fn):\n    for _ in range(WARMUP):\n        fn()\n    torch.accelerator.synchronize()\n    return statistics.median(bench_gpu_time_with_cupti(fn)) * 1e3\n\n\ndef main() -> None:\n    if not torch.accelerator.is_available() or torch.version.cuda is None:\n        raise RuntimeError(\"CUDA is required for CUPTI kernel timing.\")\n\n    torch.set_default_device(\"cuda\")\n    torch.manual_seed(0)\n\n    rows = []\n    for name, m, n, k in MATMUL_CASES:\n        a = torch.randn(m, k, dtype=torch.bfloat16)\n        b = torch.randn(k, n, dtype=torch.bfloat16)\n        out = torch.empty(m, n, dtype=torch.bfloat16)\n\n        def run_matmul(a=a, b=b, out=out):\n            torch.mm(a, b, out=out)\n\n        run_matmul()\n        ref = torch.mm(a, b)\n        torch.accelerator.synchronize()\n        torch.testing.assert_close(out, ref, atol=1e-1, rtol=1e-1)\n\n        us = bench_us(run_matmul)\n        rows.append(\n            {\n                \"case\": name,\n                \"shape\": f\"{m}x{n}x{k}\",\n                \"us\": us,\n                \"tflops\": 2 * m * n * k / (us * 1e6),\n                \"gbps\": 2 * (m * k + k * n + m * n) / (us * 1e3),\n            }\n        )\n\n    df = pd.DataFrame(rows)\n    print(df.to_string(index=False, float_format=lambda x: f\"{x:.3f}\"))\n\n\nif __name__ == \"__main__\":\n    main()\n", "skills/kernel-microbenchmark/benchmarks/graph_replay_benchmark.py": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\n\"\"\"Graph-replay microbenchmark with rotating weight buffers (CUDA and ROCm).\n\nPlatform-agnostic: HIP implements the torch.cuda.* API, including CUDAGraph.\nPattern: capture one graph (HIP graph on ROCm) containing R*INNER calls\ncycling over R rotating weight buffers, then time replays with CUDA/HIP\nevents. The rotating buffers keep the captured footprint above the GPU's\nlast-level cache, so every call reads weights cold from HBM. Prefer this over\ndo_bench on ROCm: do_bench's per-rep launch/event overhead inflates\nsmall/decode-size kernels, and its default flush buffer is only as large as\nthe LLC — on a 256 MB LLC that evicts marginally and leaves the cache full of\ndirty flush-buffer lines. The same pattern extends to multi-GPU benchmarks\n(capture per rank, collectives in identical order every replay); see the\nMulti-GPU section of SKILL.md.\n\"\"\"\n\nimport statistics\n\nimport pandas as pd\nimport torch\n\nLLC_TARGET_BYTES = 400 * 1024**2  # above 256 MB MI355X LLC and B200 L2 (126 MB)\nINNER = 2  # repeat slots within one graph to amortize per-replay overhead\nREPLAYS = 10  # replays per round: makes each measurement large vs overhead\nROUNDS = 5  # median across rounds: replay time is not always stable\nWARMUP = 5  # warmup replays to reach steady clocks before timing\nMATMUL_CASES = [\n    (\"compute-bound\", 4096, 4096, 4096),\n    (\"decode-GEMM\", 16, 16384, 8192),\n]\n\n\ndef timeit_graph(calls, inner=INNER, replays=REPLAYS, rounds=ROUNDS):\n    \"\"\"Time a list of per-slot callables as one graph (zero launch overhead);\n    weights rotate across slots so they stay HBM-cold. Returns the median over\n    rounds of per-round means, ms per call.\"\"\"\n    for c in calls:\n        c()\n    torch.accelerator.synchronize()\n    g = torch.cuda.CUDAGraph()\n    with torch.cuda.graph(g):  # capture runs on a side stream\n        for i in range(len(calls) * inner):\n            calls[i % len(calls)]()\n    torch.accelerator.synchronize()\n    events = [(torch.cuda.Event(True), torch.cuda.Event(True)) for _ in range(rounds)]\n    for _ in range(WARMUP):\n        g.replay()\n    # No sync between warmup and the first round: queued replays keep the GPU\n    # busy, so each round's launch latency stays outside its event window.\n    for s, e in events:\n        s.record()\n        for _ in range(replays):\n            g.replay()\n        e.record()\n    torch.accelerator.synchronize()\n    samples = [s.elapsed_time(e) / (replays * len(calls) * inner) for s, e in events]\n    return statistics.median(samples)  # ms per call\n\n\ndef main() -> None:\n    if not torch.accelerator.is_available():\n        raise RuntimeError(\"No GPU visible (torch.accelerator covers HIP on ROCm).\")\n\n    torch.set_default_device(\"cuda\")\n    torch.manual_seed(0)\n\n    rows = []\n    for name, m, n, k in MATMUL_CASES:\n        a = torch.randn(m, k, dtype=torch.bfloat16)  # shared: producer-warm\n        out = torch.empty(m, n, dtype=torch.bfloat16)\n        b_bytes = k * n * 2\n        r = max(2, -(-LLC_TARGET_BYTES // b_bytes))  # ceil\n        bs = [torch.randn(k, n, dtype=torch.bfloat16) for _ in range(r)]\n\n        def make_call(i, a=a, bs=bs, out=out):\n            def call():\n                torch.mm(a, bs[i], out=out)\n\n            return call\n\n        # correctness before timing, per slot (the graph would freeze a wrong\n        # result into every replay)\n        for i in range(r):\n            make_call(i)()\n            torch.accelerator.synchronize()\n            torch.testing.assert_close(out, torch.mm(a, bs[i]), atol=1e-1, rtol=1e-1)\n\n        us = timeit_graph([make_call(i) for i in range(r)]) * 1e3\n        rows.append(\n            {\n                \"case\": name,\n                \"shape\": f\"{m}x{n}x{k}\",\n                \"slots\": r,\n                \"us\": us,\n                \"tflops\": 2 * m * n * k / (us * 1e6),\n                \"gbps\": 2 * (m * k + k * n + m * n) / (us * 1e3),\n            }\n        )\n\n    df = pd.DataFrame(rows)\n    print(df.to_string(index=False, float_format=lambda x: f\"{x:.3f}\"))\n\n\nif __name__ == \"__main__\":\n    main()\n", "skills/kernel-microbenchmark/benchmarks/multi_gpu_gemm_rs.py": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\n\"\"\"Minimal multi-GPU GEMM + reduce-scatter microbenchmark.\n\nRun on one node with, for example:\n\n    torchrun --standalone --nproc-per-node=8 \\\n        .agents/skills/kernel-microbenchmark/benchmarks/multi_gpu_gemm_rs.py\n\"\"\"\n\nimport argparse\nimport os\nimport statistics\nfrom collections.abc import Callable\n\nimport pandas as pd\nimport torch\nimport torch.distributed as dist\nimport torch.distributed._symmetric_memory as symm_mem\n\nfrom vllm.config import VllmConfig, set_current_vllm_config\nfrom vllm.distributed import cleanup_dist_env_and_memory\nfrom vllm.distributed.parallel_state import (\n    get_tp_group,\n    init_distributed_environment,\n    initialize_model_parallel,\n)\n\n\ndef parse_args() -> argparse.Namespace:\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--m\", type=int, nargs=\"+\", default=[128, 512, 2048])\n    parser.add_argument(\"--n\", type=int, default=4096)\n    parser.add_argument(\n        \"--k\",\n        type=int,\n        nargs=\"+\",\n        default=[4096],\n        help=\"Per-rank K values\",\n    )\n    parser.add_argument(\"--num-workspaces\", type=int, default=10)\n    parser.add_argument(\"--warmup-replays\", type=int, default=5)\n    parser.add_argument(\"--samples\", type=int, default=20)\n    return parser.parse_args()\n\n\ndef make_gemm_rs(\n    x: torch.Tensor,\n    weight: torch.Tensor,\n    partial: torch.Tensor,\n    output: torch.Tensor,\n    rows: int,\n    device_group: dist.ProcessGroup,\n) -> Callable[[], None]:\n    def run() -> None:\n        torch.mm(x, weight.T, out=partial[:rows])\n        dist.reduce_scatter_single(output, partial, group=device_group)\n\n    return run\n\n\ndef check_correctness(\n    runs: dict[str, Callable[[], None]],\n    outputs: dict[str, torch.Tensor],\n    x: torch.Tensor,\n    weight: torch.Tensor,\n    padded_rows: int,\n    rank: int,\n    device_group: dist.ProcessGroup,\n) -> None:\n    expected_full = torch.zeros(\n        (padded_rows, weight.shape[0]),\n        dtype=x.dtype,\n        device=x.device,\n    )\n    torch.mm(x, weight.T, out=expected_full[: x.shape[0]])\n    dist.all_reduce(expected_full, group=device_group)\n    expected = expected_full.chunk(dist.get_world_size(device_group))[rank]\n    for name, run in runs.items():\n        run()\n        torch.accelerator.synchronize()\n        torch.testing.assert_close(\n            outputs[name],\n            expected,\n            rtol=5e-2,\n            atol=4.0,\n        )\n\n\ndef capture_graph(\n    run: Callable[[], None],\n    cpu_group: dist.ProcessGroup,\n) -> tuple[torch.cuda.CUDAGraph, torch.cuda.Stream]:\n    stream = torch.cuda.Stream()\n    stream.wait_stream(torch.cuda.current_stream())\n    dist.barrier(group=cpu_group)\n    with torch.cuda.stream(stream):\n        for _ in range(3):\n            run()\n    stream.synchronize()\n    dist.barrier(group=cpu_group)\n\n    graph = torch.cuda.CUDAGraph()\n    with torch.cuda.graph(graph, stream=stream):\n        run()\n    torch.cuda.current_stream().wait_stream(stream)\n    dist.barrier(group=cpu_group)\n    return graph, stream\n\n\ndef benchmark_graphs(\n    candidate_graphs: dict[str, list[torch.cuda.CUDAGraph]],\n    warmup_replays: int,\n    samples: int,\n    device_group: dist.ProcessGroup,\n    device_barrier: Callable[[], None],\n) -> dict[str, float]:\n    candidate_names = list(candidate_graphs)\n    for round_index in range(warmup_replays):\n        for candidate_index in range(len(candidate_names)):\n            candidate_id = (round_index + candidate_index) % len(candidate_names)\n            name = candidate_names[candidate_id]\n            graphs = candidate_graphs[name]\n            device_barrier()\n            graphs[round_index % len(graphs)].replay()\n    torch.accelerator.synchronize()\n\n    timings: dict[str, list[float]] = {name: [] for name in candidate_names}\n    start = torch.cuda.Event(enable_timing=True)\n    end = torch.cuda.Event(enable_timing=True)\n    for sample_index in range(samples):\n        for candidate_index in range(len(candidate_names)):\n            candidate_id = (sample_index + candidate_index) % len(candidate_names)\n            name = candidate_names[candidate_id]\n            graphs = candidate_graphs[name]\n            device_barrier()\n            start.record()\n            graphs[sample_index % len(graphs)].replay()\n            end.record()\n            end.synchronize()\n\n            elapsed_us = torch.tensor(\n                start.elapsed_time(end) * 1000,\n                dtype=torch.float64,\n                device=torch.accelerator.current_device_index(),\n            )\n            dist.all_reduce(elapsed_us, op=dist.ReduceOp.MAX, group=device_group)\n            timings[name].append(elapsed_us.item())\n    return {name: statistics.median(values) for name, values in timings.items()}\n\n\ndef benchmark_shape(\n    m: int,\n    n: int,\n    k: int,\n    num_workspaces: int,\n    warmup_replays: int,\n    samples: int,\n    device: torch.device,\n    rank: int,\n    world_size: int,\n    device_group: dist.ProcessGroup,\n    cpu_group: dist.ProcessGroup,\n    device_barrier: Callable[[], None],\n) -> dict[str, float | int]:\n    padded_m = (m + world_size - 1) // world_size * world_size\n    local_m = padded_m // world_size\n\n    torch.manual_seed(1000 + rank * 10 + m + k)\n    inputs = []\n    weights = []\n    for _ in range(num_workspaces):\n        inputs.append(torch.randn(m, k, dtype=torch.bfloat16, device=device))\n        weights.append(torch.randn(n, k, dtype=torch.bfloat16, device=device))\n\n    ring_partial = torch.empty(padded_m, n, dtype=torch.bfloat16, device=device)\n    ldmc_partial = symm_mem.empty(\n        (padded_m, n),\n        dtype=torch.bfloat16,\n        device=device,\n    )\n    ldmc_handle = symm_mem.rendezvous(ldmc_partial, device_group)\n    ring_output = torch.empty(local_m, n, dtype=torch.bfloat16, device=device)\n    ldmc_output = torch.empty_like(ring_output)\n    if padded_m > m:\n        ring_partial[m:].zero_()\n        ldmc_partial[m:].zero_()\n\n    candidate_runs = {\n        \"ring_ll_us\": [\n            make_gemm_rs(\n                x,\n                weight,\n                ring_partial,\n                ring_output,\n                m,\n                device_group,\n            )\n            for x, weight in zip(inputs, weights)\n        ],\n        \"ldmc_us\": [\n            make_gemm_rs(\n                x,\n                weight,\n                ldmc_partial,\n                ldmc_output,\n                m,\n                device_group,\n            )\n            for x, weight in zip(inputs, weights)\n        ],\n    }\n    x = inputs[0]\n    weight = weights[0]\n    check_correctness(\n        {name: runs[0] for name, runs in candidate_runs.items()},\n        {\"ring_ll_us\": ring_output, \"ldmc_us\": ldmc_output},\n        x,\n        weight,\n        padded_m,\n        rank,\n        device_group,\n    )\n\n    candidate_graphs = {}\n    graph_keepalive: list[object] = [ldmc_handle]\n    for name, runs in candidate_runs.items():\n        bundles = [capture_graph(run, cpu_group) for run in runs]\n        candidate_graphs[name] = [graph for graph, _ in bundles]\n        graph_keepalive.extend(bundles)\n\n    times = benchmark_graphs(\n        candidate_graphs,\n        warmup_replays,\n        samples,\n        device_group,\n        device_barrier,\n    )\n    global_flops = 2 * m * n * k * world_size\n    return {\n        \"M\": m,\n        \"N\": n,\n        \"K_per_rank\": k,\n        \"K_global\": k * world_size,\n        **times,\n        \"ring_ll_tflops\": global_flops / (times[\"ring_ll_us\"] * 1e6),\n        \"ldmc_tflops\": global_flops / (times[\"ldmc_us\"] * 1e6),\n        \"ldmc_speedup\": times[\"ring_ll_us\"] / times[\"ldmc_us\"],\n    }\n\n\ndef main() -> None:\n    args = parse_args()\n    assert args.m and min(args.m) > 0\n    assert args.k and min(args.k) > 0\n    assert min(args.n, args.num_workspaces, args.samples) > 0\n    assert args.warmup_replays >= 0\n    local_rank = int(os.environ[\"LOCAL_RANK\"])\n    local_world_size = int(os.environ[\"LOCAL_WORLD_SIZE\"])\n    torch.accelerator.set_device_index(local_rank)\n    init_distributed_environment()\n    world_size = dist.get_world_size()\n    os.environ[\"VLLM_ALLREDUCE_USE_SYMM_MEM\"] = \"0\"\n    symm_mem.set_backend(\"NCCL\")\n    with set_current_vllm_config(VllmConfig()):\n        initialize_model_parallel(tensor_model_parallel_size=world_size)\n\n    tp_group = get_tp_group()\n    device_group = tp_group.device_group\n    cpu_group = tp_group.cpu_group\n    rank = tp_group.rank_in_group\n    device = torch.device(\"cuda\", local_rank)\n    group_warmup = torch.zeros(1, device=device)\n    dist.all_reduce(group_warmup, group=device_group)\n    pynccl_comm = tp_group.device_communicator.pynccl_comm\n    assert pynccl_comm is not None\n    sync_input = torch.zeros(1, device=device)\n    sync_output = torch.empty_like(sync_input)\n\n    def device_barrier() -> None:\n        # Order the timed launch after a device-side rank rendezvous without\n        # including the rendezvous itself in the measured event interval.\n        pynccl_comm.all_reduce(sync_input, sync_output)\n\n    results = [\n        benchmark_shape(\n            m,\n            args.n,\n            k,\n            args.num_workspaces,\n            args.warmup_replays,\n            args.samples,\n            device,\n            rank,\n            world_size,\n            device_group,\n            cpu_group,\n            device_barrier,\n        )\n        for k in args.k\n        for m in args.m\n    ]\n\n    if rank == 0:\n        metadata = {\n            \"world_size\": world_size,\n            \"local_world_size\": local_world_size,\n            \"num_nodes\": world_size // local_world_size,\n            \"backend\": dist.get_backend(device_group),\n            \"gpu\": torch.cuda.get_device_name(local_rank),\n            \"torch\": torch.__version__,\n            \"cuda\": torch.version.cuda,\n        }\n        print(pd.Series(metadata, name=\"value\").to_string())\n        df = pd.DataFrame(results)\n        print(df.to_string(index=False, float_format=lambda x: f\"{x:.3f}\"))\n\n    dist.barrier(group=cpu_group)\n    cleanup_dist_env_and_memory()\n\n\nif __name__ == \"__main__\":\n    main()\n", "skills/model-microbenchmark/SKILL.md": "---\nname: model-microbenchmark\ndescription: Time a vLLM model's forward pass on exact batch shapes (decode, prefill, chunked prefill, prefix hit, spec-decode verify, or mixes) with `vllm bench forward`, single-GPU or DP/TP/EP across nodes. Use for per-step model latency, layout/parallelism comparisons, and checking a model-level optimization. Not for single kernels (use kernel-microbenchmark) or end-to-end serving (use `vllm bench serve`).\n---\n\n# Model Microbenchmark (`vllm bench forward`)\n\nBuilds the batch without the scheduler, runs it through MRV2's real\n`execute_model`, and times the forward as a one-shot CUDA graph (prefill\nincluded). Target sampling (rejection sampling for verify rows) and the\nconfigured drafter are included by default; `--exclude-sampler` and\n`--exclude-drafter` drop them (both for forward-only timing). The drafter\nassumes all draft tokens are accepted. Requests use the model's\n`generation_config.json` sampling defaults (else temperature 1.0, no\ntop-p/top-k); override with `--override-generation-config` (e.g.\n`'{\"temperature\": 0}'` for greedy target sampling). The drafter samples\ngreedily unless `draft_sample_method` is `probabilistic`. CPU step overhead\nis excluded.\n\n## Usage\n\n```bash\nvllm bench forward --model deepseek-ai/DeepSeek-V4-Flash \\\n  --case decode=64*1@8192 --case prefill=8192 --case mix=4096,32*1@8192\n\n# DP/TP/EP: one process per GPU (multi-node: add --nnodes/--node-rank/--master-addr)\ntorchrun --nproc-per-node=4 -m vllm.entrypoints.cli.main bench forward \\\n  --model ... -dp 4 --enable-expert-parallel --case decode=128*1@100000\n```\n\nRequests: `[N*]Q[@K][c][:D]`, comma-separated, per DP rank.\n\n| Form | Meaning |\n| --- | --- |\n| `8192` | fresh prefill, 8192 tokens |\n| `32*1@8192` | 32 decodes, KV length 8192 (KV length **includes** the query) |\n| `4@4096:3` | spec-decode verify, 3 draft tokens |\n| `2048@10240` | prefill after an 8192-token prefix-cache hit |\n| `2048@10240c` | chunked prefill: the prefix came from earlier chunks |\n\nVerify cases require `--speculative-config` with `num_speculative_tokens`\nat least as large as the case's draft count; insufficient capacity is rejected.\n\nHit vs chunk only differs on models with SWA bounded replay (DSV4.1): a hit\nalso recomputes the last window (128 tokens) of the prefix.\n\nOr `--shapes file.json|yaml`:\n`{\"cases\": [{\"name\": ..., \"requests\": [{\"query_len\", \"kv_len\", \"num_draft_tokens\", \"chunked\", \"count\"}]}]}`.\n\nKey flags (plus all `EngineArgs`):\n\n- `--kv-len-jitter 0.5` (default): prefixes drawn within ±50%, same on every\n  DP rank, capped at `max_model_len`. Use `0` for exact lengths.\n- `--routing auto|real|balanced|zipf`: `auto` = Zipf with dummy weights;\n  `zipf` uses fixed alpha=1.25 skew (target only, no PCP or grouped top-k).\n- `--iters 20 --samples 5`, `--output-json out.json` (per-rank latency stats,\n  `samples_us`, graph-vs-eager check).\n- Defaults: `--load-format dummy`, prefix caching off, no torch.compile.\n\nRead `median_us` (each replay is already the max over ranks).\n\n## Kernel breakdown\n\nAdd `--profile-dir DIR` to see where the time goes. After timing, each case is\nreplayed 3 more times under `torch.profiler`; every rank writes\n`DIR/<case>.rank<r>.kernels.json` (GPU time per kernel per forward, sorted)\nand `DIR/<case>.rank<r>.trace.json.gz` (open in Perfetto). Rank 0's top\nkernels are printed and included in `--output-json`.\n\n```bash\npython -m vllm.benchmarks.forward.profile DIR/decode.rank0.kernels.json\n# Before/after a change, same case: per-kernel deltas, largest first.\npython -m vllm.benchmarks.forward.profile base/decode.rank0.kernels.json new/decode.rank0.kernels.json\n```\n\n- Kernels are grouped by name without template or function arguments; the\n  JSON keeps one full name per group in `example`.\n- Only the timed forward is included: the in-graph KV restore and rank\n  rendezvous are excluded (`pre_forward_us`). `span_us` (first to last\n  forward kernel) should be close to `median_us`, a bit higher from profiler\n  overhead; `busy_us` can exceed it when streams overlap.\n- Compare the same rank across runs: under EP, ranks differ (e.g. collective\n  wait time shows up inside communication kernels).\n\nFor Nsight Systems (NVTX, NCCL, CPU side, GPU metrics), skip `--profile-dir`:\nthe two can't share CUPTI. Each case's 3 profiled replays run between\n`cudaProfilerStart`/`Stop` in an NVTX range `forward/<case>`, so a capture range\nrecords only them, one report per case (and rank):\n\n```bash\nnsys profile --capture-range=cudaProfilerApi --capture-range-end=repeat \\\n  --cuda-graph-trace=node -o prof vllm bench forward ...       # prof.1, prof.2, ...\ntorchrun --nproc-per-node=4 --no-python nsys profile ... -o prof_rank%q{RANK} \\\n  python -m vllm.entrypoints.cli.main bench forward ...\nnsys stats --report cuda_gpu_kern_sum --format csv -o kern prof.1.nsys-rep\n```\n\nKeep `--capture-range-end=repeat`: nsys's default stops after the first case\nand leaves the bench hanging. `nsys stats` also counts the KV restore copies\nthat the JSON summary excludes.\n\n## Caveats\n\n- **Dummy weights lie for data-dependent kernels.** Dummy gates route every\n  token to the same experts (hence synthetic routing). Cross-check suspicious\n  kernels with real weights.\n- **torch.compile models (e.g. Qwen3/3.5) look slow**: no compile here. Use\n  them for correctness only; trust perf for models under `vllm/models/`.\n- `sample spread > 0.5%` warns of unstable timing. DSV4.1 DEP prefill is\n  inherently ~0.5–1% (MegaMoE cross-rank sync, host engram reads).\n- `graph_vs_eager` may be nonzero for small batches where models branch on\n  `is_current_stream_capturing()`; that's expected, not a bug.\n- KV cache is zero-initialized (`--kv-init zeros`); random KV was within 3%.\n- Uniform DP only: every rank gets the same case; no idle ranks.\n- CUDA only: it hangs on ROCm (untested cause: likely the in-graph timing\n  events).\n- Large prefills/prefix hits need room: raise `--max-num-batched-tokens` /\n  `--max-model-len` / `--gpu-memory-utilization` if build fails on KV blocks.\n- Startup cost is JIT/autotune, not the bench: install FlashInfer jit-cache\n  and cubin; DeepGEMM warmup is skipped (each case's eager pass compiles its\n  own shapes).\n- To compare against serving decode: `vllm bench latency` with 65- vs\n  1-token outputs, divided by 64, with a FULL decode graph.\n", "skills/model-recipes/SKILL.md": "---\nname: model-recipes\ndescription: Find vLLM deployment recipes and configs for LLMs and Hugging Face models by model and hardware. Use for recipe lookup, creation, and updates.\n---\n\n# Model Recipes\n\nModel serving recipes are maintained in this repository's\n[recipes/models/ directory](../../../recipes/models). Omni (image, video,\naudio) recipes live in vllm-project/vllm-omni, and Ascend NPU content lives in\nvllm-project/vllm-ascend as overlays merged into these recipes. The published\ncatalog, rendered by\n[vllm-project/recipes](https://github.com/vllm-project/recipes), is at\n[recipes.vllm.ai](https://recipes.vllm.ai).\n\n## Usage notes\n\n1. Recipe lookup returns commands and deployment guidance without launching\n   `vllm serve`.\n2. Use published configurations or the recipes repository's command generator\n   for supported selections. Return commands as published, including their\n   flags and parallelism settings.\n3. Recipes are starting points for deployment and may not be tuned for your\n   workload. Check each recipe for its verified configurations, and use\n   benchmarks of your workload to guide further tuning.\n4. To create or update a recipe, follow the\n   [authoring workflow below](#create-or-update-a-recipe).\n\n## Find a recipe\n\nRead recipes from the published JSON on recipes.vllm.ai. It is generated from\nthe source YAML with variant, hardware, and strategy settings already\nresolved; the YAML contains comments and conditional overrides, so do not use\nit for lookup. When presenting results, link the website page. Read the source\nYAML only when creating or updating a recipe.\n\nEach recipe has a page at `https://recipes.vllm.ai/<org>/<repo>` and JSON at\nthe same path plus `.json`. Paths use the full Hugging Face ID, preserving\ncase; do not substitute `meta.slug` or a display title. For example,\n`Qwen/Qwen3.8-27B` maps to\n[recipes.vllm.ai/Qwen/Qwen3.8-27B](https://recipes.vllm.ai/Qwen/Qwen3.8-27B).\n\nRecipe JSON is often over 20 KB, mostly the `guide`. Instead of printing it,\nread only what the request needs: each step below returns the paths for the\nnext, so stop once the request is answered. Commands need `curl` and `jq`.\n[scripts/read_recipe.sh](scripts/read_recipe.sh) is in this skill's directory;\nthe examples use its path from the vLLM repository root.\n\n### Search the catalog\n\nSkip this step if the exact HF ID is known. Otherwise search by model ID,\nfamily, or provider using case-insensitive keywords. Each\nwhitespace-separated word must occur in the ID, title, or provider:\n\n```bash\ncurl -fsSL https://recipes.vllm.ai/models.json |\n  jq --arg q 'qwen 27b' '\n    ($q | ascii_downcase | [scan(\"\\\\S+\")]) as $words | .[] |\n    ([.hf_id, .title, .provider] | join(\" \") | ascii_downcase) as $text |\n    select(all($words[]; . as $word | $text | contains($word))) |\n    {hf_id, json, url, derived_from}'\n```\n\n`json` is the recipe data path; `url` is its page path. Prefix both with\n`https://recipes.vllm.ai`. A `derived_from` entry is a variant of a parent\nrecipe: fetch its own `json` to get that checkpoint's command. Its page may\nbelong to the parent, so link the returned `url` rather than assuming every\ncheckpoint has a separate page.\n\nIf there is no exact match, search the family and inspect `variants` before\nconcluding the recipe is missing.\n\n### Summarize the recipe\n\nSave the recipe JSON to a file and summarize it:\n\n```bash\nread_recipe=.agents/skills/model-recipes/scripts/read_recipe.sh\nrecipe=$(mktemp)\ncurl -fsSL https://recipes.vllm.ai/Qwen/Qwen3.8-27B.json -o \"$recipe\"\n\"$read_recipe\" \"$recipe\"\n```\n\n`default` is the recommended hardware, strategy, and variant; `hardware` maps\neach hardware ID to its command path; `recipe_verified_hardware` lists hardware\nwhere the recipe as a whole was verified end to end. For capability\nrequirements, such as tool calling or text-to-video, check `features` and\n`omni_tasks`, then confirm in the guide.\nSome recipes, including Omni, lack `hardware`; skip hardware selection and\nuse the guide's launch and task-specific sections.\n\n### Select hardware and strategy\n\nMatch a hardware ID to the user's GPU and fetch its path from `hardware`,\nprefixed with `https://recipes.vllm.ai`, rather than constructing a URL. That\nresponse is the command object itself: single-node objects carry `command`,\nand multi-node objects carry `head_command` and `worker_commands` instead, so\nlist its keys before selecting fields.\nCheck `hardware_profile` to confirm that the selected configuration matches\nthe user's GPU model and specifications. Its `gpu_count` describes the profile,\nnot necessarily the number of GPUs used by the command. Check the command's\nparallelism settings, `node_count`, and all `worker_commands` against the\nuser's available topology, and compare the variant's `vram_minimum_gb`, an\nestimate, with the total memory of the GPUs the command uses; a configuration\nbelow that minimum is not a working option unless the guide says it was\ntested. Ask when the user's hardware is unclear. If no\npublished command or guide command fits, report the mismatch and return the\nclosest one unchanged; list any adjustments the user's setup would need\nseparately and mark them unverified instead of editing the command.\n\nFor another strategy, follow `alternatives` in the same response. These are\nstatic files; query parameters do not change their configuration. For other\nfeature/topology selections, use the recipes repository's command synthesis.\n\n### Read deployment guidance\n\nRead the guide sections that apply to the selection, such as prerequisites,\nlaunch notes for the selected hardware or variant, troubleshooting, and known\nlimitations. Pass entries from `guide_sections` or prefixes of their text.\nThe script prints every matching section with its subsections and fails when\na section matches nothing:\n\n```bash\n\"$read_recipe\" \"$recipe\" prerequisites troubleshooting\n```\n\nQuery other fields with `jq` on the saved file, such as `features.<name>`,\n`hardware_overrides`, or `omni.tasks` for request examples.\n\n### Return the result\n\nReturn the website link, selected checkpoint and hardware, the requested\ncommand, and relevant prerequisites and caveats from the guide. Pick one\ncommand and copy it, including its Docker form, exactly as the command object\nor guide section gives it; do not combine commands from different sections or\nadd, drop, or reorder flags. List optional changes separately.\n\nFor each command, state its source, either a generated hardware or strategy\nconfiguration or a named guide section, and whether that source says it was\ntested. A `recipe_verified_hardware` entry covers the recipe on that\nhardware, not every variant, strategy, or guide command, so it does not make a\ncommand verified. Generated configurations are not automatically verified.\n\n## Create or update a recipe\n\nRecipes cover official or widely used checkpoints, with configurations verified\nend to end on real hardware. Do not add recipes for arbitrary community\nuploads, untested hardware claims, or non-standard flags that only work for one\nsetup. Before opening a pull request, confirm that the user ran the\nconfiguration and can share the results.\n\nEdit the YAML under [recipes/models/](../../../recipes/models) in this\nrepository, following the recipes repository's\n[add-recipe skill](https://github.com/vllm-project/recipes/blob/main/.agents/skills/add-recipe/SKILL.md)\nfor the schema. Validate and preview it from a checkout of\n`vllm-project/recipes` pointed at this directory, as\n[recipes/README.md](../../../recipes/README.md) describes.\n", "skills/model-recipes/agents/openai.yaml": "interface:\n  display_name: \"Model Recipes\"\n  short_description: \"Find vLLM deployment recipes and configs for LLMs and Hugging Face models by model and hardware.\"\n  default_prompt: \"Use $model-recipes to find a recipe for my model and hardware, and return its commands and deployment caveats.\"\n", "skills/model-recipes/scripts/read_recipe.sh": "#!/bin/bash\n# Usage: read_recipe.sh <recipe.json> [guide-section...]\n# Without sections, print a compact summary of a recipes.vllm.ai recipe JSON.\n# With sections, print each guide section whose heading starts with one of\n# them (case-insensitive), including its subsections.\n\nset -euo pipefail\n\nif [ $# -lt 1 ]; then\n    echo \"Usage: $0 <recipe.json> [guide-section...]\" >&2\n    exit 1\nfi\n\n# Print \"<level>\\t<heading text>\\t<line>\" for guide lines, marking headings\n# outside code fences with their level and other lines with 0.\nguide_lines() {\n    jq -r '.guide // \"\"' \"$1\" | awk '\n        /^[[:space:]]*(```|~~~)/ { fence = !fence }\n        !fence && match($0, /^#+ /) {\n            print RLENGTH - 1 \"\\t\" substr($0, RLENGTH + 1) \"\\t\" $0\n            next\n        }\n        { print \"0\\t\\t\" $0 }'\n}\n\nif [ $# -gt 1 ]; then\n    recipe=$1\n    shift\n    status=0\n    for section in \"$@\"; do\n        guide_lines \"$recipe\" | awk -F '\\t' -v h=\"$section\" '\n            BEGIN { h = tolower(h); sub(/^#+[[:space:]]*/, \"\", h) }\n            $1 > 0 && lvl && $1 <= lvl { lvl = 0 }\n            $1 > 1 && !lvl && index(tolower($2), h) == 1 { lvl = $1; found = 1 }\n            lvl { sub(/^[^\\t]*\\t[^\\t]*\\t/, \"\"); print }\n            END {\n                if (!found) {\n                    print \"No guide section starts with: \" h > \"/dev/stderr\"\n                    exit 1\n                }\n            }' || status=1\n    done\n    exit $status\nfi\n\nsections=$(guide_lines \"$1\" | awk -F '\\t' '$1 == 2 || $1 == 3 { print $3 }' |\n    jq -R . | jq -s .)\n\njq --argjson sections \"$sections\" '{\n    hf_id,\n    title: .meta.title,\n    tasks: .meta.tasks,\n    recipe_verified_hardware: .meta.hardware,\n    omni_tasks: (.omni.tasks // null |\n        if . then map(objects |= {id, label, endpoint, model_id, description})\n        else null end),\n    variants: (.variants // {} | map_values(\n        {model_id, precision, vram_minimum_gb, supported_hardware} |\n        with_entries(select(.value != null)))),\n    features: (.features // {} | keys),\n    opt_in_features,\n    default: (.recommended_command // null |\n        if . then {hardware, strategy, variant} else null end),\n    hardware: .recommended_command.by_hardware,\n    guide_sections: $sections\n} | with_entries(select(.value != null))' \"$1\"\n", "skills/pr-checklist/SKILL.md": "---\nname: pr-checklist\ndescription: Prepare a vLLM change for human PR review or re-review, or analyze an open pull request. Use before opening a PR, drafts included (e.g. `gh pr create`), or pushing review fixes, to check design fit, behavioral coverage, performance evidence, diff quality, and closure of previous feedback.\n---\n\n# PR Checklist\n\nThis SKILL is designed to help systematically enforce vLLM's code quality and contribution standards during the pull request process,\nand to reduce the burden of manual code review on maintainers.\n\n## Usage\n\nThe following checklist can be used to polish a change in preparation for a vLLM pull request, analyze an open pull request (either as the author or as a reviewer), or ensure that all contribution standards are met before requesting maintainer attention. To use this checklist effectively, go through each item and verify that it has been addressed in the diff / pull request.\n\nThis is intended to be used with a human in the loop: when running programmatically, prepare notes on every section to ensure a thorough report, with a clear header summarizing the findings and areas needing attention. When running interactively, present this report to the user with a clear list of actionable follow-up tasks and design decisions to make, then iterate.\n\n### Re-Review\n\nTo update a PR following a review, read all comments and threads on the PR. For each concrete concern, work with your human operator to decide on a plan of action to address each either by a direct reply or by updating the change and acknowledging with a comment. Ensure the PR description remains fresh and all relevant documentation (including comments) in the change is up-to-date.\n\n`gh pr view --comments` does not include inline review comments. Set `pr` to the PR number, then fetch all pages of conversation comments, review submissions, and inline comments (including replies):\n\n```bash\ngh api --paginate \"repos/vllm-project/vllm/issues/$pr/comments\"\ngh api --paginate \"repos/vllm-project/vllm/pulls/$pr/reviews\"\ngh api --paginate \"repos/vllm-project/vllm/pulls/$pr/comments\"\n```\n\nUse `in_reply_to_id` to group inline replies with their parent comments. Use GraphQL `reviewThreads` when resolved or outdated thread status is needed.\n\n## Sections\n\n### 1. Design Fit\n\nDoes the change align with the overall design and architecture of vLLM? Does it introduce any design inconsistencies or anti-patterns? Are there any potential long-term maintenance concerns related to this change?\n\n#### 1.1: Impact on Core Components\n\nvLLM's core components are shared across many different deployments. Changes to these files have high risk and changes should be structured in order to be easily maintainable and minimally invasive.\n\nSuch components include:\n\n- The Model Runner (`vllm/v1/worker/*/model_runner.py`)\n- The Scheduler (`vllm/v1/core/sched/*`)\n- Core infrastructure (`vllm/v1/core/*`, including KV cache managers and utilities)\n\netc.\n\nChanges should be structured to minimize complexity added to these files. Consider refactoring or isolating new functionality to reduce the impact on core components, both in terms of code maintainability and potential for introducing bugs.\n\nNontrivial logic associated with non-standard/non-default functionality should not be added to core/common code paths and files.\n\n#### 1.2: Replication\n\nSome changes may duplicate code that already exists elsewhere in the codebase. Does the change introduce unnecessary replication, or could existing functionality be reused instead? Consider refactoring to reduce duplication and improve maintainability.\n\nConsult the affected area's agent instructions and contribution guides for its reuse conventions. See the [model implementation guide](../../../docs/contributing/model/basic.md) for model code and the [MRV2 development guidance](../../../docs/design/model_runner_v2.md#development-philosophy). Justify any duplication needed to isolate functionality and limit its impact on existing workflows.\n\n#### 1.3: Complexity\n\nChanges which increase the complexity of the codebase should be carefully scrutinized. Specifically those which add new abstractions, dependencies, or branching cases to existing components should be evaluated for their necessity and potential impact on maintainability. Keep the diff focused and small, including tests.\n\nConsider whether the added complexity could be mitigated through refactoring, modularization, or other design improvements. Aim to keep the codebase as simple and understandable as possible while still achieving the desired functionality.\n\nPrefer defaults or automatic selection based on existing hardware and model. Before adding an environment variable, config field, or CLI flag, explain why existing controls or automatic selection are insufficient. Validate correctness, compatibility, and performance across affected configurations before choosing the default; an opt-in switch does not replace this assessment.\n\nAs a rule of thumb, the complexity of a change can be estimated by the number of new lines of code added to the main codebase:\n\n- Low complexity: < 50 lines. Generally easy to review and unlikely to introduce significant complexity.\n- Medium complexity: 50-250 lines. Requires careful review and consideration of potential impact on maintainability.\n- High complexity: > 250 lines. May introduce significant complexity and requires thorough review and justification.\n\nYou may exclude test cases and documentation updates from this line count, as they typically do not contribute significantly to the complexity of the main change. Note that line count is only a coarse indicator, meant to guide and flag possible overly-complex contributions. Use judgement when assessing the true semantic complexity and implied review burden.\n\nBug fixes should aim to remain below the \"High complexity\" bar. Those which exceed this threshold often warrant additional scrutiny and justification. Redesigning core components, modifying core interfaces, or otherwise introducing significant complexity in order to patch a bug is very often discouraged and should be carefully justified.\n\nA PR that adds significant complexity or a substantial amount of new code must be well justified. A new feature should be relevant to, or requested by, enough users to warrant its size and complexity. A performance optimization should deliver end-to-end improvements on workloads that matter, and those gains should be large enough to outweigh the complexity it adds.\n\n#### 1.4: Correctness and Compatibility\n\nEnsure that all changes to vLLM are sound and do not violate existing contracts. Specifically, verify that all affected deployments which share an execution pathway with the changed code will remain correct. Trace related implementations, alternative backends sharing the same flow, and affected call sites of modified functions.\n\nUse the [vLLM security review skill](../review-vllm-security/SKILL.md) when a change affects how vLLM handles untrusted input, how callers can consume shared resources, or who can access data or privileged actions. Verify the relevant safeguards on each affected entry point and backend.\n\nWhen adding features or changing contracts, ensure that relevant feature compatibility is assessed. Identify any potential incompatibilities or breaking changes and justify them explicitly in the PR notes.\n\nWhen adding functionality, consider parallels with existing designs and identify opportunities to simplify and unify them rather than adding a separate implementation alongside them.\n\n#### 1.5: Tradeoffs\n\nWhen making a design change, adding a feature, or contributing a performance improvement, assess the tradeoffs and potential downsides. When changing a default backend to improve performance as measured on one configuration, could this cause a decrease in performance for another configuration? Could a new architecture change accelerate one workload but cause a feature incompatibility or performance regression in another? Ensure tradeoffs are clearly noted and validation is sufficient to catch potential lurking regressions or drawbacks.\n\nCheck that the change does not introduce CPU/GPU synchronization on the main model execution thread during steady-state inference. Inspect explicit synchronization, host reads of GPU tensors, boolean tensors as indices, and transfers that can block the host. Run the affected configuration with `VLLM_GPU_SYNC_CHECK=error` to confirm a concern; passing CI is insufficient when CI does not exercise that configuration. See the [MRV2 async execution design](../../../docs/design/model_runner_v2.md#2-async-first) for examples.\n\n#### 1.6: Model Runner V1 Deprecation\n\nAccount for Model Runner V1 (MRV1) deprecation when reviewing model-runner changes. Target new GPU model-runner features at Model Runner V2 (MRV2) and follow its [design and development guidance](../../../docs/design/model_runner_v2.md#development-philosophy). For fixes needed by deployments still using MRV1, explain why the legacy path needs the change and check whether MRV2 is also affected.\n\n### 2. Testing and Validation\n\nAll serving-engine changes contributed to vLLM must be _validated_: bug fixes must be tested on a reproducer, and new features or performance optimizations must be run locally and/or benchmarked to ensure correctness and effectiveness. It is unacceptable, for example, to contribute a bugfix patch without running vLLM end-to-end and verifying that it resolves the issue as intended.\n\nBeyond _validation_, many (but not all) changes to vLLM should be _tested_: this includes writing new tests, updating existing tests, and ensuring that the test suite continues to provide reliable coverage of the affected functionality.\n\n#### 2.1: Test Coverage and Effectiveness\n\nWhen adding or modifying tests, consider both the coverage and the effectiveness of the test suite. Coverage refers to the extent to which the codebase is exercised by tests, while effectiveness refers to the ability of the tests to catch regressions and ensure correctness.\n\nAssess whether the included test cases are meaningful, concise, and maintainable. Testing should not be exhaustive: local validation is typically sufficient to ensure a baseline correctness of the change. Contributed tests should focus exclusively on areas that are deemed prone to errors, regressions, or complex interactions within the codebase. Recommend deletion of redundant, trivial, or otherwise unnecessary tests: this is one of the most common complaints raised during code reviews.\n\nCheck added and changed tests against [`tests/AGENTS.md`](../../../tests/AGENTS.md). For reproducible bugs, the PR must show the new test failing without the fix and passing with it.\n\nVerify that testing actually exercises the new path, rather than passing through an unchanged path or fallback. Ensure added speculative decoding correctness tests assert nonzero acceptance rate, selection tests identify the desired backend, etc.\n\nAim to write tests that are meaningful, targeted, and maintainable. Avoid redundant or trivial tests that do not contribute to the overall reliability of the test suite. Avoid using mock objects, especially when highly coupled with internal logic.\n\n#### 2.2: Test Reliability and Robustness\n\nSome tests are considered \"flaky\": they may pass or fail intermittently without any changes to the codebase. Flaky tests can undermine confidence in the test suite and block successful CI runs. Analyze the added tests for potential flakiness and ensure they are reliable and robust.\n\nFrequent sources of flaky tests include:\n\n- Assertions requiring bit-exact output correctness when minor floating-point variation is expected. For example, a change in default kernel selection priority may cause exact-floating-point-correctness assertions to fail.\n- Tests that depend on the order of execution or the state of shared resources, which can lead to intermittent failures when tests are run in parallel or in different environments.\n\n#### 2.3: Test Automation and Integration\n\nvLLM's CI runs in Buildkite, with the launch configuration under `.buildkite/`. Ensure new tests run in an appropriate CI workflow when the required resources are available; add or update a workflow where needed. If CI cannot exercise the changed path because the required hardware or checkpoint is unavailable, document the missing coverage, the resource constraint, and validation performed outside CI. A CI coverage gap does not waive validation: the human submitter must confirm the required validation before publishing the PR.\n\n### 3. Code Quality and Style\n\nCode quality is another of the primary areas that maintainer effort is spent to address. Carefully audit the changes for adherence to coding standards, readability, maintainability, and overall design principles.\n\n#### 3.1: Comments\n\nKeep comments concise and use them sparingly. Consider whether the same information can be conveyed in fewer lines, and prefer clear code with meaningful, concise variable names, and fewer comments overall. Use comments to explain the reasoning behind complex logic, non-obvious decisions, or important context that is not immediately apparent from the code itself. Context regarding specific user decisions made during the design phase are often not needed and can instead be included as notes in the PR description instead.\n\nWhen writing new functions, consider when a docstring may be useful. Most short helper functions do not need a docstring, but more complex functions or those forming part of the public API should include one. In particular, docstrings are useful when adding custom kernels or other performance-optimized implementations of otherwise-straightforward logic, as they make clear the input and output shapes/dtypes/assumptions, and can shed light on hard-to-follow implementations.\n\nFor bug fixes, there is no need to include details of the original bug and explanation of why the pre-changed version of the code would be incorrect. Those details should be in the PR description instead.\n\n#### 3.2: Documentation and Examples\n\nUser-visible changes need docs in the same PR, placed and checked per [Documenting User-Visible Changes](../../../docs/contributing/README.md#documenting-user-visible-changes); missing or unfindable docs are blocking. Add usage examples under `examples/` where applicable.\n\n#### 3.3: Helper Functions\n\nIdentify and inline trivially-simple helper functions which have only one call site.\n\n#### 3.4: Formatting\n\nAvoid formatting or whitespace changes that are unrelated to the PR, as long as pre-commit still passes.\n\n#### 3.5: C++/CUDA Build Cost\n\nFiles in `csrc/` are compiled once per GPU architecture, so a build's critical path is one unit rather than the sum: when a PR grows a kernel translation unit, check whether it is, or is about to become, that unit, and whether the variants it instantiates should be split over several units instead. See [`csrc/AGENTS.md`](../../../csrc/AGENTS.md).\n\n### 4. Pull Request Contents\n\nThis section pertains to the contents of the pull request itself, rather than the changes.\n\nWhen acting as the author, prepare or update these contents. When acting as a reviewer, assess them and report missing context or evidence.\n\nStart from `.github/PULL_REQUEST_TEMPLATE.md`, retaining its sections and checklist. When creating a PR interactively, use `gh pr create --template .github/PULL_REQUEST_TEMPLATE.md`. For noninteractive creation or editing, fill out a copy of that template and pass the completed file with `--body-file`.\n\n#### 4.1: Description and Context\n\nEnsure the PR description has a short 1-2 line summary of the changes to facilitate quick understanding by reviewers. This section should link relevant issues, predecessor/blocking PRs, and provide any necessary context for the changes.\n\nKeep Claims to a few concrete bullets and explain motivation briefly. Keep explanations in Validation and Details concise too, while retaining the evidence, root cause, tradeoffs, and limitations needed to assess the change. Link full logs or use collapsible HTML details for lengthy supporting material rather than polluting the main narrative.\n\n#### 4.2: Claims and Supporting Evidence\n\nEnsure the PR makes clear, concise claims about the accomplishment:\n\n- For bug fixes, what specific issue is being resolved and how can it be verified?\n- For new features, what functionality is being added and how can it be utilized?\n- For refactoring, what was the motivation and what improvements are expected?\n- For performance optimizations, what specific model/hardware/serving configurations & workloads are being targeted and how can the performance gains be measured?\n\nFor the stated claims, ensure the PR provides sufficient evidence, examples, or references to support them, making it easy for reviewers to verify the correctness and impact of the changes.\n\nFor newly added tests, the PR description must disclose the commit SHA tests were run on, the testing commands and pytest summary output, including test time.\n\nPresent main and PR results with full commands (including server startup), commit IDs, and model/hardware configuration. Paste or attach raw reproducer, accuracy, and benchmark output;  summary tables are not a substitute. For repeated benchmarks, report run count and variability. For kernel performance changes, include before/after profile visualizations/timelines when they help explain the measured gains. Link relevant CI failures or regressing PRs when they motivate the change. Use detail tags to organize and contain long sections.\n\n- For bug fixes, show the same command failing on main and passing on the PR, with raw error and success logs.\n- For new features, ensure that usage examples are included and validated to confirm that the feature works as intended.\n- For refactoring, ensure that changes are sufficiently validated at appropriate test levels (unit is sufficient for minor refactors, E2E serving is required for significant refactoring).\n- For model-affecting changes, include before/after accuracy evaluation commands and raw output (e.g. `lm_eval`) on relevant tasks.\n- For performance optimizations, include benchmarks or tests that validate the claimed gains. Demonstrate an end-to-end speedup on a concrete serving workload (e.g. `vllm bench serve`), microbenchmarks alone is insufficient.\n\n#### 4.3: Root-Cause Analysis\n\nWhen fixing bugs or issues, provide a clear root-cause analysis. Explain what caused the problem, how it was identified, and why the chosen solution effectively addresses it. A patch which resolves the issue without a proper root-cause analysis may lead to recurring problems and increased maintenance overhead.\n\nFor fixes that involve disaggregated prefill/decode (PD) logic, such as the NIXL connector (`vllm/distributed/kv_transfer/kv_connector/v1/nixl/`), make a best effort to include a minimal example of the flow being changed and/or the initial flow that caused the failure. A short numbered sequence (or diagram) of a request's path across the P and D instances, e.g. scheduler admission, prefill execution, KV transfer registration and write, decode-side read, token generation, lets reviewers trace the root cause and the fix without reconstructing the distributed flow from the diff. Keep the example minimal: only the steps and components involved in the change. See the [disaggregated prefill](../../../docs/features/disagg_prefill.md), [NIXL KV push](../../../docs/design/nixl_kv_push_connector.md), and [NIXL KV cache lease](../../../docs/design/nixl_kv_cache_lease.md) docs for the flows involved.\n\n#### 4.4: Implementation Details\n\nProvide a detailed explanation of the implementation, including design decisions, trade-offs, and any relevant technical details. Highlight any non-obvious choices, tradeoffs, potential limitations, and areas where maintainer attention is required.\n\n#### 4.5: Contributing Guide\n\nEnsure that the PR follows the [contributing guide](https://docs.vllm.ai/en/latest/contributing), including adhering to coding standards, commit message conventions, and any other project-specific guidelines. This helps maintain consistency and quality across the codebase.\n", "skills/review-vllm-security/SKILL.md": "---\nname: review-vllm-security\ndescription: Prevent recurring vLLM security defects when designing, implementing, or reviewing models, processors, media loaders, endpoints and request fields, tool parsers, deployment settings, and changes to shared engine state, caches, or worker transports. Use when input changes how vLLM spends resources, crosses a trust boundary, or affects other requests.\n---\n\n# Review vLLM security\n\nUse this before choosing an implementation and again when reviewing the diff.\nRead the project's [threat model](../../../docs/usage/security.md) and\n[security policy](../../../SECURITY.md). Follow the\n[vulnerability management process](../../../docs/contributing/vulnerability_management.md)\nfor a reported vulnerability.\n\n## Review workflow\n\n1. Trace every affected input from its source to the first operation that trusts\n   it or spends resources on it. Distinguish inference callers, model output,\n   artifact authors, operators, and trusted peers. Include conversions,\n   defaults, expansion, and the error path.\n2. Use the quick screen below to identify applicable failure families.\n   Open only the review-area files relevant to your change. The change-type\n   table gives starting points, and the quick screen may identify other areas.\n3. Search for sibling consumers by field or operation. When applicable, compare\n   Python and Rust, HTTP and gRPC, streaming and buffered flows, model or backend\n   overrides, and opt-in and fallback paths. Identify where each path enforces\n   the control and which paths share it.\n4. Confirm where rejected work, cancellation, or a timeout leaves resources and\n   shared state. For each applicable risk, record the enforcing boundary, the\n   sibling paths checked, and the observed behavior or remaining verification.\n\n## Quick screen\n\n| Review area | Question to answer |\n| --- | --- |\n| [Resource budgets][budgets] | What bounds the bytes, counts, work, and retained state before each stage incurs the cost? |\n| [Input invariants and fault containment][input] | Which checks prevent invalid inputs from reaching the engine, scheduler, or native consumer? |\n| [Cache, request, and peer ownership][ownership] | What preserves ownership when requests, buffers, cache keys, and transfer IDs are reused? |\n| [Parser and rendering complexity][parsing] | What bounds parsing, compilation, and rendering under malformed or fragmented input and concurrent work? |\n| [Artifact trust and unsafe interpretation][artifacts] | What permits executable loading, and are trust choices and revision pins enforced at every actual load? |\n| [Fetch, filesystem, and decoder policy][fetch] | What confines every network destination, file access, and decoder invocation? |\n| [Authorization and capability gates][access] | Who can reach the action, set privileged state, or select and invoke a tool? |\n| [Sensitive output and error responses][output] | What can enter responses, logs, metrics, or model context, and how large can it become? |\n\n## Detailed checks by change\n\nStart with the families for each affected change type. Each file includes\nexamples from published advisories.\n\n| Change type | Checklist files |\n| --- | --- |\n| Endpoint, request field, or frontend | [Authorization][access], [resource budgets][budgets], [input invariants][input], [sensitive output][output] |\n| Multimodal model, processor, or media backend | [Fetch and decoder policy][fetch], [resource budgets][budgets], [input invariants][input], [artifact trust][artifacts] |\n| Model, tokenizer, quantization, or artifact loading | [Artifact trust][artifacts], [path confinement][fetch], [native input invariants][input] |\n| Structured output, template, reasoning, or tool calls | [Parser complexity][parsing], [authorization][access], [resource budgets][budgets], [sensitive output][output] |\n| Engine, scheduler, sampler, or native kernel | [Input invariants][input], [resource budgets][budgets], [shared-state ownership][ownership] |\n| Cache, batching, IPC, or disaggregated serving | [Ownership][ownership], [authorization][access], [resource budgets][budgets], [safe IPC decoding][artifacts] |\n| Deployment, configuration, or plugin | [Authorization][access], [artifact trust][artifacts] |\n| Errors, logging, metrics, or usage reporting | [Sensitive output][output], [resource budgets][budgets] |\n\nUse the relevant section of [Checks by change](references/checks-by-change.md)\nwhen you need vLLM entry points or examples of what to verify.\n\nFor a limit regression, use a small configured cap or a stubbed consumer.\nCheck valid boundary behavior and rejection before expensive work. For\nshared-state changes, follow a failed or cancelled request with a valid one,\nor interleave two requests and verify their results and cleanup independently.\n\n[budgets]: references/failure-modes/resource-budgets.md\n[input]: references/failure-modes/input-invariants.md\n[ownership]: references/failure-modes/cache-and-request-ownership.md\n[parsing]: references/failure-modes/parser-and-rendering.md\n[artifacts]: references/failure-modes/artifact-trust.md\n[fetch]: references/failure-modes/fetch-and-decoder-policy.md\n[access]: references/failure-modes/authorization.md\n[output]: references/failure-modes/sensitive-output.md\n", "skills/review-vllm-security/references/checks-by-change.md": "# Checks by change\n\nUse the sections relevant to your change for vLLM entry points and verification\nexamples. See [the skill](../SKILL.md) for the quick screen and review-area files.\n\n## New endpoint, request field, or frontend\n\n- Find route registration, the request model or RPC conversion, middleware,\n  and the serving entry point. Follow the field through render, engine request\n  construction, and streaming and error responses. Check\n  [authorization](failure-modes/authorization.md),\n  [resource budgets](failure-modes/resource-budgets.md),\n  [input invariants](failure-modes/input-invariants.md),\n  and [error handling](failure-modes/sensitive-output.md).\n- Look for other consumers of the same field and the same underlying handler.\n  For batch or pooling routes, budget across the outer request before creating\n  child work. For token-in/token-out, render/derender, and scale-out, validate\n  caller-supplied intermediates when they re-enter the service.\n- Exercise the registered route under its supported configuration. For an\n  authenticated route, verify credential handling with the actual mount\n  prefix. For a limit, assert that the upstream consumer receives no work\n  when admission rejects the input. Check any distinct frontend exposing it.\n- For OpenAI- or Anthropic-compatible fields, also use\n  [API compatibility guidance](../../check-api-compat/SKILL.md).\n\n## New multimodal model, processor, or media backend\n\n- Trace acquisition through `MediaConnector` and media I/O, then through\n  processor overrides, placeholder construction, encoding, and the engine.\n  Check Python speech-to-text and Rust chat multimodal loading when the\n  change reaches either stack. Check [fetch and decoder policy](failure-modes/fetch-and-decoder-policy.md),\n  [resource budgets](failure-modes/resource-budgets.md), and\n  [input invariants](failure-modes/input-invariants.md).\n- Compare `get_supported_mm_limits`, `get_mm_max_tokens_per_item`, and model\n  profiling with runtime output shapes. Look for resize, padding, frame\n  selection, audio resampling, intermediate tensors, and placeholder or\n  token expansion that occur after `MediaDecodedBudget` accounts for decoded\n  media. Check backend-specific limits and any trusted per-request overrides.\n- Exercise the normal serving path with small configured limits. Verify\n  minimum-sized input, mixed or repeated media, and the aggregate limit.\n  Use a stub decoder or processor that reports its allocations to check\n  that materialization stops at the intended boundary. Compare independent\n  code paths such as inline and remote media or CPU and GPU decoding as needed.\n\n## Model, tokenizer, quantization, or artifact loading\n\n- Locate the main loader and secondary configs, weights, tokenizer, processor,\n  dynamic modules, packed tensors, and fallback reads used by the model.\n  Trace trust settings and revision pins to each consumer. Check\n  [artifact trust](failure-modes/artifact-trust.md),\n  [path confinement](failure-modes/fetch-and-decoder-policy.md),\n  and [native input invariants](failure-modes/input-invariants.md).\n- With stub loaders, record the repo, revision, trust choice, and local path\n  at the actual calls. Check a missing pinned asset and confirm that\n  resolution fails without an unpinned retry. For a new packed format,\n  verify that invalid metadata is rejected before invoking the kernel.\n\n## Structured output, templates, reasoning, and tool calls\n\n- Trace raw fields, generated schemas, backend dispatch, and validation.\n  Include the format constructed from tool definitions, streaming argument\n  parsing, and model-supplied templates. Check\n  [parser complexity](failure-modes/parser-and-rendering.md) and\n  [worker budgets](failure-modes/resource-budgets.md).\n- Follow parsed results into actual dispatch and the next model invocation.\n  For the Responses API, check both `HarmonyContext` and `ParsableContext`\n  where applicable. Treat schemas and results from `MCPToolServer` as data\n  from the remote service. Check [tool authority](failure-modes/authorization.md),\n  [data-only interpretation](failure-modes/artifact-trust.md),\n  and [model-visible context](failure-modes/sensitive-output.md).\n- Verify the same valid call across buffered and chunked outputs, and a\n  malformed or incomplete form in each affected backend. Use stub workers\n  and tools to check that only a complete authorized call is dispatched, that\n  duplicate completion does not cause another dispatch, and that timeout\n  cleanup and call budgets hold across continuations. Verify that tool\n  transport credentials stay out of model-visible prompts.\n\n## Engine, scheduler, sampler, or native kernel\n\n- Trace `SamplingParams` or the relevant request representation from the\n  frontend through input processing to the model runner, scheduler, or\n  native operation. Compare shared and alternate runners where they consume\n  the same field. Check\n  [input invariants](failure-modes/input-invariants.md),\n  [resource budgets](failure-modes/resource-budgets.md), and\n  [buffer ownership](failure-modes/cache-and-request-ownership.md).\n- Identify the actual dimension or ownership map that governs access. Verify\n  behavior at the accepted boundary, rejection of unsupported combinations,\n  and healthy inference after a rejected request. Test buffer and slot reuse\n  with two distinguishable requests when a change touches co-batched state.\n\n## Shared caches, batching, IPC, or disaggregated serving\n\n- Trace cache-key creation, translation into external keys, worker updates,\n  and eviction. When reusing media features, inspect the UUID namespace at\n  the processor and encoder caches independently of prefix-cache salting.\n  For transfers, follow admission through registration, peer selection,\n  completion, and cleanup on both ends. Check\n  [ownership](failure-modes/cache-and-request-ownership.md),\n  [capability gates](failure-modes/authorization.md),\n  [resource budgets](failure-modes/resource-budgets.md),\n  and [safe IPC decoding](failure-modes/artifact-trust.md).\n- With stub peers or caches, exercise interleaved requests, cancellation,\n  eviction, and duplicate or delayed completion. Check that resulting state\n  still belongs to the correct request and pending counts return to baseline.\n  For background workers, verify that a failed worker or stuck queue is\n  visible to whichever readiness or liveness signal the deployment uses.\n\n## Deployment, configuration, or plugin changes\n\n- Review defaults and opt-ins with the affected frontend and deployment mode.\n  Find which process binds the interface, which caller can reach it, and which\n  layer enforces access. Include changes in what a proxy routes, which network\n  can reach workers, or which directory holds executable or cached data.\n  Check [authorization](failure-modes/authorization.md)\n  and [artifact trust](failure-modes/artifact-trust.md).\n- Check option precedence and merged configuration at the consuming layer.\n  Exercise the default restricted behavior and an explicitly permitted\n  behavior. Compare administrative routes, custom plugin routes, and internal\n  RPC endpoints with their intended trust boundaries.\n\n## Errors, logging, metrics, or usage reporting\n\n- Trace validation, exception conversion, response serialization, and\n  diagnostics on all affected paths. Check\n  [sensitive output](failure-modes/sensitive-output.md)\n  and [resource budgets](failure-modes/resource-budgets.md).\n- Use a harmless sentinel value to verify that private fields stay out of\n  responses, logs, metrics, and tool prompts as applicable. Check bounded\n  error summaries with small configured caps and verify that usage or cache\n  counts are populated by the engine.\n", "skills/review-vllm-security/references/failure-modes/artifact-trust.md": "# Artifact trust and unsafe interpretation\n\n- **Executable loading.** Carry `trust_remote_code` to the actual dynamic\n  import or instantiation in model, tokenizer, processor, and config paths.\n  Treat artifact-provided class names and plugin declarations as data until\n  the trusted loader authorizes the action.\n- **Revision pins.** Track `revision` and `code_revision` separately to each\n  relevant file lookup and import. Include secondary config reads, weights,\n  tokenizer and processor assets, dynamic code dependencies, and fallback\n  resolution. Check failure behavior for missing pinned assets and\n  cross-repository references.\n- **Fallback trust.** Check fast and fallback loaders, remote and local\n  snapshots, dependency helpers, and optional formats. Preserve the operator's\n  decision through retry, error recovery, and model-specific wrappers.\n- **Deserialization.** Use data-only formats and safe APIs for untrusted\n  checkpoints, serialized embeddings, and IPC messages. Check indirect\n  deserialization through libraries, shared-memory helpers, and alternative\n  readers. Validate metadata before materializing tensors.\n- **Data-driven dispatch.** Use declarative parsing and validated registries\n  for model configuration and tool arguments. Keep authority to select\n  executable loaders, callbacks, modules, or plugins with the trusted code.\n- **Packed and local artifacts.** Resolve artifact-relative paths under the\n  intended root. Review quantization metadata that governs native dimensions,\n  offsets, or allocation. Use the project's private-cache trust assumptions\n  when a new path consumes cached files.\n- **Dependency guarantees.** Verify loader safeguards across the supported\n  versions and paths of the dependency, including legacy and fallback readers.\n\n## Published advisory examples\n\nVerify both artifact\nresolution and actual code or object loading.\n\n- [Model code trust control](https://github.com/vllm-project/vllm/security/advisories/GHSA-7972-pg2x-xr59)\n- [Artifact revision propagation](https://github.com/vllm-project/vllm/security/advisories/GHSA-3ww4-5jv9-j5gm)\n- [Shared-memory deserialization boundary](https://github.com/vllm-project/vllm/security/advisories/GHSA-6757-hggm-hp2w)\n", "skills/review-vllm-security/references/failure-modes/authorization.md": "# Authorization and capability gates\n\n- **Effective route.** Inspect registered routes, mount prefixes, methods,\n  WebSocket upgrades, middleware order, and the deployed frontend. Verify that\n  authorization and routing see consistent paths under supported prefix and\n  proxy configurations.\n- **Access boundary.** Check API-key coverage for the specific route. Apply\n  the documented trusted-network model to internal transports. Restrict\n  administrative, debug, and dynamic model-loading actions to their intended\n  principals.\n- **Browser and credential handling.** Check Host and origin behavior when\n  changing browser-facing listeners or local endpoints. Verify that gated\n  routes use the existing credential comparison path and test expected\n  credential handling.\n- **Operator-owned switches.** Check enablement of request templates,\n  multimodal overrides, insecure serialization, plugins, and privileged\n  tools at the operation that uses them. Include nested overrides, backend\n  selection, and continuation paths.\n- **Internal authority.** Use typed, server-owned context for peer selection,\n  tensor handles, cache transfer state, and internal routing. Review merging\n  of generic extra arguments with privileged fields.\n- **Tool dispatch.** Resolve tool identity and namespace from trusted\n  definitions. Enforce the allowlist at execution and share applicable call\n  budget counters across continuations. Check same-name tools and who may\n  turn a parsed tool call into an action. Treat remote tool results as data\n  with the trust of their source. Keep authorization decisions in trusted\n  server state.\n- **Tool retries.** Track dispatch and outcome by call identity when execution\n  can have side effects. Account for duplicate events and disconnects.\n  A timeout can leave the result unknown. Safe retries need an idempotency\n  guarantee or a way to verify the original outcome.\n- **Sessions and peers.** Bind tool sessions and connector actions to the\n  intended principal, instance, or authorized peer. Verify that caller\n  headers and IDs cannot take over a session or redirect an action.\n\n## Published advisory examples\n\nVerify authorization and trust\nsettings at the route and operation that consume input.\n\n- [Route authentication](https://github.com/vllm-project/vllm/security/advisories/GHSA-94f4-hr76-p5j6)\n- [Template trust gate](https://github.com/vllm-project/vllm/security/advisories/GHSA-x567-49g5-p4cf)\n", "skills/review-vllm-security/references/failure-modes/cache-and-request-ownership.md": "# Cache, request, and peer ownership\n\n- **Complete cache identity.** Include inputs that change the cached result or\n  its interpretation. Consider model and adapter identity, media shape and\n  mode, preprocessing, position or template state, and representation version.\n  Frame composite keys unambiguously and preserve hash strength where\n  collisions can expose or substitute another request's data.\n- **Sharing scope.** Preserve cache namespaces and `cache_salt` through\n  continuations, fan-out, serialization, and external stores where promised.\n  Trace prefix, processor, and encoder caches separately. Prefix-cache\n  salting covers the prefix cache. Verify the media UUID namespace for the\n  processor and encoder caches under the documented deployment assumptions.\n  [Media UUID security](../../../../../docs/usage/security.md#multimodal-media-uuid-security)\n- **Identity reuse.** Associate cache entries, transfer registrations, and\n  requests tracked across processes with their owners. Include a generation\n  or equivalent lifetime check when identifiers or slots can be reused.\n- **Batch and buffer reuse.** Initialize request-owned data before exposing it.\n  Clear or remap sampling masks, histories, token and logprob output, scratch\n  buffers, and CUDA graph inputs across batch insertion, removal, compaction,\n  and retries. Verify independence with distinct requests.\n- **Mirrored caches.** Coordinate publication, eviction, and rollback when a\n  frontend and worker hold paired cache state. Check missing entries, rejected\n  requests, stale handles, and asymmetric eviction.\n- **Transfer binding.** Bind peer, direction, request, block set, byte range,\n  and descriptor to authorized live state before scheduling, reading,\n  writing, or completing a transfer. Verify both producer and consumer paths.\n- **Async cleanup.** Release exactly the resources acquired on cancellation,\n  retry, rejection, or timeout. Check duplicate and late events against the\n  current owner. Reuse blocks or handles once in-flight work can no longer\n  access them.\n- **Shared adaptation and counters.** Scope mutable parser, estimator,\n  scheduler, and accounting state to the expected owner. Verify that one\n  request updates another request's behavior only where sharing is intended.\n\n## Published advisory examples\n\nPreserve cache ownership and namespace\nthrough transformations, errors, and eviction.\n\n- [Shared cache identity](https://github.com/vllm-project/vllm/security/advisories/GHSA-rh6f-3x46-j33q)\n- [Cache salt through tool continuations](https://github.com/vllm-project/vllm/security/advisories/GHSA-935w-9g4m-p28p)\n- [Mirrored cache consistency](https://github.com/vllm-project/vllm/security/advisories/GHSA-ph3r-5jfg-f84f)\n", "skills/review-vllm-security/references/failure-modes/fetch-and-decoder-policy.md": "# Fetch, filesystem, and decoder policy\n\n- **Every acquisition path.** Reuse the shared media connector or equivalent\n  controls. Trace sync and async fetches, model or tokenizer hooks, file and\n  inline handlers, and secondary reads during decoding or rendering.\n- **Effective destination.** Enforce the configured scheme, host, address,\n  and redirect policy on the destination actually used by the client. Keep\n  validation and fetch URL interpretation consistent. Reapply applicable\n  policy to each redirect.\n- **Request context.** Scope credentials and headers to their intended\n  destination. Keep ambient authorization, shared cookies, and caller session\n  state out of unrelated media fetches. Check retries and redirects for\n  unintended forwarding.\n- **Path confinement.** Apply configured local-media, artifact, and\n  shared-storage roots to the resolved path. Check absolute paths, symlinks,\n  archive members, and caller or artifact names used to construct paths.\n  Validate the target used by the actual open or write.\n- **Detected format.** Use the detected media format and nested stream type to\n  choose an allowed decoder. Review backend selection, fallbacks, and formats\n  that can launch helpers or open another file or network resource.\n- **Decoder safeguards.** Preserve pixel, sample, duration, and frame\n  protections across decoder choices. Keep time and byte limits active during\n  download and decode. Review model initialization for changes to shared\n  decoder safety settings.\n- **Decode failure.** Return a request error for unusable results, partial\n  reads, or unexpected dimensions. Verify that a failed decode cannot return\n  a buffer from an earlier request, including on native and hardware backends.\n\n## Published advisory examples\n\nCheck media acquisition and\nformat restrictions throughout model-specific paths.\n\n- [Media connector coverage](https://github.com/vllm-project/vllm/security/advisories/GHSA-4hhp-h66f-j5j7)\n- [Process-wide decoder safeguards](https://github.com/vllm-project/vllm/security/advisories/GHSA-mm38-5g96-7j6x)\n", "skills/review-vllm-security/references/failure-modes/input-invariants.md": "# Input invariants and fault containment\n\n- **Effective value.** Check omitted, null, empty, and default values plus\n  field combinations and feature capabilities. Recheck after conversions that\n  change the value or unit. Validate finite floats and signed ranges before\n  arithmetic, loops, or allocation.\n- **Derived arithmetic.** Guard casts and derived seeds, sizes, offsets,\n  counts, and index extrema in the consumer's integer width. Verify signedness\n  and inclusive or exclusive limits before dispatch to native code.\n- **Token IDs.** Trace prompt IDs, sampler lists, stop IDs, speculative and\n  recovered IDs, and detokenization input. Validate against the model's usable\n  vocabulary and consumer buffer dimensions, including differences between\n  tokenizer metadata and the loaded model.\n- **Tensor metadata and contents.** Check rank, dimensions, dtype, layout,\n  stride, storage span, and supported sparse representations. Verify relations\n  among parallel inputs before tensor conversion, device copy, or indexing.\n- **Media and model relationships.** Check minimum usable media sizes,\n  placeholder counts, offsets and lengths, alignment between media and feature\n  tensors, and positional or grid capacity. Verify supported combinations of\n  embeddings, pretokenized input, and optional model features.\n- **Wire representations.** Apply invariants where HTTP, gRPC, render,\n  derender, or disaggregated routes accept engine-shaped data. Check extra\n  fields, aliases, mixed typed and untyped values, frontend conversions, and\n  native defaults.\n- **Shared and native boundaries.** Check native index and storage assumptions\n  where real shapes and allocations are known. Return a request-local error for\n  invalid input before any fatal assertion, panic, unsafe index, or\n  worker-fatal exception. Keep genuine internal invariant failures\n  distinguishable from client errors.\n- **Admission and rollback.** Validate before registering or mutating shared\n  state when possible. On failure after registration, use the normal\n  request-failure and rollback path. Verify that rejected work leaves no stale\n  metadata and that subsequent inference succeeds.\n\n## Published advisory examples\n\nUse the effective model bounds in\neach frontend and keep invalid request or compilation errors request-local.\n\n- [Rust and Python token ID bounds](https://github.com/vllm-project/vllm/security/advisories/GHSA-qff2-492f-9fm4)\n- [Structured-output error containment](https://github.com/vllm-project/vllm/security/advisories/GHSA-85xf-c7hm-whqw)\n", "skills/review-vllm-security/references/failure-modes/parser-and-rendering.md": "# Parser and rendering complexity\n\n- **Source and expansion bounds.** Limit nesting, references, branches,\n  alternatives, tool definitions, and generated schema size before compilation.\n  Check translated schemas and grammar forms as well as raw input.\n- **Invalid and incomplete forms.** Check empty, malformed, recursive, and\n  incomplete input on each backend. Confirm preprocessing and validation run\n  before compiler or native calls for every supported schema format.\n- **Repeated work.** Look for repeated copying and rescanning of growing\n  state during rendering, token replacement, incremental parsing, and\n  sanitization. Check streaming deltas, unmatched delimiters, nested quotes,\n  and immediate rejection paths.\n- **Pattern matching cost.** Review regex and grammar complexity on caller\n  data and model output, including patterns used in error handling. Prefer\n  bounded or linear algorithms where feasible. Check compile and match\n  controls on every backend that can consume the input.\n- **Timeout behavior.** Bound worker occupancy and work that continues after\n  a deadline. Check repeated timeouts, cancelled callers, executor capacity,\n  and event-loop responsiveness.\n- **Streaming semantics.** Compare buffered parsing with chunks split across\n  quotes, escapes, or delimiters. Keep parser state request-local. Preserve\n  the distinction between quoted data and tool syntax through dispatch.\n- **Executable output boundary.** Keep streaming fragments in parser state\n  until a complete call and its required arguments are validated. Emit a call\n  for dispatch once, and handle invalid or incomplete terminal output without\n  executing it.\n- **Template execution.** Apply trust policy, permitted template context, and\n  execution limits to model-provided templates and alternate renderers.\n  Review template argument preparation as well as the render itself.\n\n## Published advisory examples\n\nBound worker occupancy and apply\ncompilation controls across supported backends.\n\n- [Template rendering resources](https://github.com/vllm-project/vllm/security/advisories/GHSA-542m-9234-8gvf)\n- [Structured-output regex compilation](https://github.com/vllm-project/vllm/security/advisories/GHSA-48jh-3gj7-fg8v)\n", "skills/review-vllm-security/references/failure-modes/resource-budgets.md": "# Resource budgets\n\n- **Transport limits.** Apply body, header, multipart, WebSocket, and RPC\n  receive limits at the corresponding transport or reader. Check streamed and\n  lengthless input and alternate server configurations. Enforce the cumulative\n  byte limit while reading, before a full body is materialized.\n- **Parsed input limits.** Bound collection sizes, nesting, and string lengths\n  before tokenization, copying, rendering, or task submission. Count outer\n  lists as well as inner elements. Inspect empty, omitted, and explicitly\n  unlimited configurations.\n- **Total fan-out.** Account for total prompts, documents, candidates,\n  output sequences, and media items across child requests. Check the products\n  of limits that multiply work. Reserve capacity before spawning children\n  and define how partial failure unwinds it.\n- **Token and sampling costs.** Bound input and output tokens, requested\n  logprobs, stop and allow/block lists, and per-token work. Include template\n  and multimodal token expansion, pretokenized inputs, and combinations of\n  truncation parameters that change which work is performed.\n- **Downloaded and decoded media.** Check downloaded bytes, decoded pixel and\n  sample counts, frames, and total decoded bytes where each consumes a distinct\n  resource. Charge the whole request, including repeated media. Enforce totals\n  as actual data arrives when metadata is incomplete or inaccurate.\n- **Processor amplification.** Bound post-resize and padded geometry, sampled\n  frames, resampling output, derived tensors and patches, and generated media\n  tokens before materializing them. Check the largest intermediate and final\n  dimensions when accounting starts from source dimensions.\n- **Profiling and reservation.** Compare runtime media and batch maxima with\n  profiling, encoder cache and graph buffer capacity, and host and device\n  memory reservations. Include optional and fallback backends that use\n  different representations or allocate in a different address space.\n- **Long-lived streams.** Apply cumulative limits to incremental or resumed\n  sessions. Bound buffered output and queued input, use backpressure with slow\n  consumers, and stop producers when the request closes or is cancelled.\n- **Workers and pending work.** Bound outstanding parser jobs, renderer threads,\n  network requests, and connector tasks as well as per-job cost. Verify\n  behavior at capacity and release permits on submission failure, timeout, and\n  cancellation.\n- **Retained state.** Limit cache and registry entry counts, bytes, and other\n  scarce resources such as file descriptors. Verify eviction and expiry for\n  large entries, many tiny or empty entries, and failed or never-established\n  sessions.\n- **Overrides and parity.** Check where request, model, backend, and operator\n  settings merge. Verify that aliases, overrides, fallback loaders, and\n  backend-specific work honor the effective policy and budget.\n\n## Published advisory examples\n\nLimit transport reads, media materialization, and\ntotal prompt or media work across the request.\n\n- [HTTP headers](https://github.com/vllm-project/vllm/security/advisories/GHSA-rxc4-3w6r-4v47)\n- [Media downloads](https://github.com/vllm-project/vllm/security/advisories/GHSA-p6g9-7v3x-m8mv)\n- [Request-wide media budget](https://github.com/vllm-project/vllm/security/advisories/GHSA-5r3c-5x4v-8gjh)\n- [Prompt list fan-out](https://github.com/vllm-project/vllm/security/advisories/GHSA-87x5-vmc3-756j)\n", "skills/review-vllm-security/references/failure-modes/sensitive-output.md": "# Sensitive output and error responses\n\n- **Safe client errors.** Use structured error codes and safe fields. Keep\n  internal paths, usernames, native object representations, stack traces, raw\n  request bodies, and credentials out of client-visible errors. Compare HTTP,\n  gRPC, streaming, and model-specific wrappers.\n- **Error amplification.** Limit how many validation errors are collected,\n  how much each field echoes, and the total response size. Account for\n  validation, redaction, and serialization costs on rejected requests.\n- **Logs and metrics.** Keep secret and high-volume input fields out of\n  routine diagnostics. Bound log records and use a fixed vocabulary for\n  metric labels derived from methods, paths, or error classes.\n- **Model-visible context.** Render only intended tool and prompt fields.\n  Keep service credentials, connection headers, and private execution state\n  in the corresponding transport or server context.\n- **Output provenance.** Verify that returned tokens, logprobs, media, and\n  intermediate representations come from this request and initialized storage.\n  Derive usage and cached-token counts from the trusted accounting source.\n- **Signals from shared resources.** Check timing, cache-hit indicators, and\n  operational metadata when changing what callers can learn about shared\n  state. Tie guarantees to the documented cache and deployment assumptions.\n\n## Published advisory examples\n\nCheck diagnostics for both\ndisclosure and unbounded output.\n\n- [Validation error disclosure](https://github.com/vllm-project/vllm/security/advisories/GHSA-hwrm-c4cx-rf4j)\n- [Error representation across frontends](https://github.com/vllm-project/vllm/security/advisories/GHSA-hgg8-fqqc-vfmw)\n- [Metric label cardinality](https://github.com/vllm-project/vllm/security/advisories/GHSA-5fj9-pfhr-6j48)\n", "skills/transformers-upgrade/SKILL.md": "---\nname: transformers-upgrade\ndescription: \"Playbook for changing vLLM's Transformers version bounds. Use when bumping the pinned or maximum Transformers version, raising the minimum Transformers version, or deleting vendored configs, processors, or compat shims that upstream Transformers now provides.\"\n---\n\n# Upgrading Transformers\n\nThe supported range lives in `requirements/common.txt`. CI pins one exact\nversion in `requirements/test/*.in` and the compiled `requirements/test/*.txt`.\nA version change is one of two jobs, and they usually come as a pair:\n\n- **Bump the pin**: a new Transformers release becomes the CI version and\n  the upper bound. vLLM grows compat code for it.\n- **Raise the floor**: the minimum moves up. That compat code, and every\n  vendored config or processor upstream now ships, becomes dead weight.\n  Every floor raise ends with an **unvendoring pass**.\n\n## Bump the pin\n\n1. Edit the pin line in each `requirements/test/*.in` and `*.txt` and the\n   upper bound in `requirements/common.txt`. Past bumps edit only the pin\n   line in the compiled files; see `git log -- requirements/common.txt`.\n2. Read the release notes for config validation changes, renamed auto-mapping\n   formats, and removed attributes; these are what break vLLM.\n3. Search `tests/` for `min_transformers_version` and skip markers naming the\n   new version, and run those tests on the new pin. Keep the gates: older\n   versions in the supported range still lack the feature, so a gate goes\n   only when the floor reaches it.\n4. Run the suites in [Testing](#testing) and fix what breaks. Mark every\n   shim with a `# Transformers >= X` comment so the next floor raise finds it.\n\nDone when the [Testing](#testing) suites and every test gated on this\nversion pass on the new pin.\n\n## Raise the floor (unvendoring pass)\n\n### 1. Inventory\n\nInventory candidates with the floor version installed (no vLLM install needed):\n\n```bash\nuv run --no-project --with transformers==<floor> \\\n    python .agents/skills/transformers-upgrade/scripts/find_upstreamed.py\n```\n\nIt lists:\n\n- vendored configs whose `model_type` upstream now owns;\n- `_CONFIG_REGISTRY` overrides of upstream types;\n- registered processors that collide with upstream class names or models;\n- version-gated code at or below the floor;\n- code that reads the installed Transformers version, whatever its threshold;\n- patches citing a Transformers issue or PR (with whether a referenced PR is\n  in the floor release) or a future minimum version.\n\nIt finds candidates by name only. Every hit still needs a verdict.\n\n### 2. Port each candidate to upstream\n\nEvery hit is deleted by default. A vendored copy is a liability: it drifts\nfrom upstream, hides upstream fixes, and shadows the native class. Port the\nvLLM model code to the upstream schema instead, renaming attribute reads and\nderiving values from upstream fields.\n\nFan candidates out to parallel subagents. Each one compares the vendored and\nupstream classes, then greps every attribute the vLLM model code reads.\n[Upstreaming hazards](#upstreaming-hazards) lists the usual fixes.\n\nKeep a vendored class only when upstream cannot load a checkpoint vLLM must\nkeep serving, and record why in the PR description. A different upstream\nschema, a model-code rewrite, or a needed eval is work for the PR, not a\nreason to keep.\n\n### 3. Prove it on real checkpoints\n\nFor every checkpoint in `tests/models/registry.py` that uses a ported\nconfig, dump what vLLM builds before and after the change, then diff the two.\nRun both dumps; each catches what the other misses:\n\n- `dump_configs.py`: the resolved config, attribute by attribute.\n- `dump_model.py`: the model built on the meta device with no GPU or weights.\n  It records ModelConfig sizes, every parameter shape, and every module's\n  scalar attributes (`head_dim`, `num_kv_heads`, `scaling`, ...). Missing\n  fields that are read with defaults only show up here.\n\n```bash\ngit worktree add --detach <scratch>/vllm-base upstream/main\nS=.agents/skills/transformers-upgrade/scripts\nfor dump in dump_configs dump_model; do\n    PYTHONPATH=<scratch>/vllm-base .venv/bin/python $S/$dump.py before.jsonl <repos>\n    PYTHONPATH=$PWD .venv/bin/python $S/$dump.py after.jsonl <repos>\n    .venv/bin/python $S/diff_dumps.py before.jsonl after.jsonl\ndone\n```\n\nAdd `--trust-remote-code` for checkpoints whose `config.json` has an\n`auto_map`, and dump both ways.\n\nHow to read the diffs:\n\n- **A `<MISSING>` config field the model reads:** this crashes or silently\n  falls back to a default. Port the model code to the upstream field.\n- **New upstream-only defaults** (`attention_bias=False`,\n  `pad_token_id=None`): usually benign. A model diff of 0 confirms it.\n- **Any model diff:** this is a numerics change, and the PR needs a model\n  eval. For example, A.X-K1 gained the checkpoint's YaRN rope scaling, which\n  the vendored class had been dropping; it shows up as\n  `layers.*.self_attn.scaling (x61)`.\n\n### 4. Delete\n\nFor each deleted config:\n\n- Delete the file.\n- Remove its entries from `_CLASS_TO_MODULE` and `__all__` in\n  `vllm/transformers_utils/configs/__init__.py`.\n- Remove its entries from `_CONFIG_REGISTRY` in\n  `vllm/transformers_utils/config.py`.\n- Switch every importer, including tests, to `from transformers import ...`.\n- Remove the `source_file_dependencies` lines naming the file from\n  `.buildkite/`.\n\nDeleted processors follow the same steps in\n`vllm/transformers_utils/processors/__init__.py`.\n\nBefore merging, rebase and grep again for the old field names: PRs that land\nin between still read them.\n\nDone when every line of the inventory output is deleted, or kept with a\nreason that meets the bar in step 2. The PR also carries the config diff\nresults and evals for any changed values.\n\n## Upstreaming hazards\n\nUpstream configs are `@strict` dataclasses. Checkpoint keys upstream does not\ndeclare survive as plain attributes, but only when the checkpoint sets them.\nDefaults that only vLLM sets, and values vLLM derives, vanish.\n\n| Hazard | Signal | Fix |\n| --- | --- | --- |\n| Upstream consumes legacy keys | `__post_init__` pops keys the model reads (`deepseek_v4` `compress_ratios`) | Read the upstream replacement (`layer_types`, `mlp_layer_types`, per-layer `rope_parameters`) |\n| Renamed or dropped fields | Diff shows `<MISSING>` for a field the model reads | Read the upstream name; derive dropped flags from what implies them (`enable_moe_block` from `num_experts`) |\n| Undeclared field without a default | `config.x` raises `AttributeError` for configs that omit `x`, e.g. minimal test configs. Dumps of real checkpoints miss it | Upstream ignoring `x` usually means vLLM can stop reading it; if vLLM truly needs it, read `getattr(config, \"x\", <old default>)` |\n| Top-level config stops forwarding | The vendored top-level config forwarded reads to `text_config`; upstream does not. `getattr(config, \"x\", default)` silently takes the default, e.g. on MTP draft configs from `SpeculativeConfig.hf_config_override`, which the dumps do not build | Read from `get_text_config()`; grep `getattr` reads of every field, including speculative-decoding paths |\n| Type check on the config | `ctx.get_hf_config(SomeConfig)` relies on the vendored base class | Accept the upstream class too, e.g. a `Cosmos3ProcessingInfo` overriding `get_hf_config` |\n| Remote code takes over | Checkpoint `config.json` has `auto_map`; with `--trust-remote-code`, the hub class replaces the native one once vLLM stops registering its own | Check the remote class loads; if not, register the upstream class for that `model_type` |\n| Read-only upstream fields | Properties or derived fields break subclasses and `hf_overrides` (`nemotron_h` `hybrid_override_pattern`) | Override the source field (`layers_block_type`) instead |\n| Behavioural rewrite | Upstream derives fields differently (`diffusion_gemma` `sliding_window`) | Upstream matches the reference implementation; verify with an eval |\n| Original checkpoint format | Upstream targets `-hf` conversions; vLLM serves the originals (`qwen3_asr`, `qianfan_ocr`) | Keep only if upstream cannot load the original at all |\n| Processor output contract | Model code consumes keys upstream does not emit | Port the model to upstream's keys |\n| Name collision | A registered vendored processor shares an upstream class name and hijacks `get_processor` (`InternVLProcessor`) | Drop the registry entry |\n\nVersion gates from the inventory need a decision:\n\n- **Code** only reachable below the floor is deleted. This covers:\n    - comparisons against `TRANSFORMERS_VERSION`;\n    - branches labelled `# Transformers < X`;\n    - fallbacks for fields that upstream configs now always set, e.g.\n    `mlp_layer_types`, `per_layer_config` or legacy `layer_types` names.\n\n  A `skipif` whose condition is now always true becomes an unconditional\n  `skip` with the same reason.\n- **`min_transformers_version`** at or below the floor is removed.\n- **`max_transformers_version`** below the floor means CI never tests that\n  model; report it rather than deleting it silently.\n- **Patches citing a Transformers issue or PR:**\n    - Delete the patch when its fix is in the floor release.\n    - For an issue, find the PR that closed it and check that PR. A closed\n      issue is not a fixed one: issues get closed while the bug is still in\n      the release.\n    - Re-run the patched behaviour before deleting. A fix in the release does\n      not always cover vLLM's path: Emu3's processor gained BOS upstream, but\n      vLLM tokenizes without the processor.\n    - Links that only explain a design choice (e.g. a float32 RoPE note) are\n      not patches; leave them.\n\n## Testing\n\n```bash\n.venv/bin/python -m pytest tests/transformers_utils tests/config tests/tokenizers_\n.venv/bin/python -m pytest tests/models/multimodal/processing/test_common.py -k \"<models>\"\n```\n\nAdd `tests/models/test_initialization.py -k \"<archs>\"` where a GPU is\navailable, and a model eval for any model whose resolved config changed.\n\nModels in `vllm/models/` are high priority: whenever their config or model\ncode changes, run GSM8k (`tests/evals/gsm8k/`) and GPQA Diamond\n(`tests/evals/gpt_oss/`) on `main` and the branch, even when the dumps show\nno diff, and put both scores in the PR. FlashInfer autotuning picks kernel\ntactics afresh on every server start, which moved DeepSeek-V4-Flash GSM8k by\nabout 1 point; pass `--kernel-config '{\"enable_flashinfer_autotune\": false}'`\nto both servers so greedy outputs are comparable.\n", "skills/transformers-upgrade/agents/openai.yaml": "interface:\n  display_name: \"Transformers Upgrade\"\n  short_description: \"Bump vLLM's Transformers version and delete vendored code upstream now provides.\"\n  default_prompt: \"Use $transformers-upgrade to raise the minimum Transformers version and remove vendored configs, processors, and shims it makes redundant.\"\n", "skills/transformers-upgrade/scripts/diff_dumps.py": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\"\"\"Diff two dump_configs.py or dump_model.py outputs, per repo.\n\npython diff_dumps.py before.jsonl after.jsonl\n\"\"\"\n\nimport json\nimport sys\nfrom collections import Counter\n\nimport regex as re\n\nIGNORED = {\"transformers_version\", \"_name_or_path\", \"architectures\", \"auto_map\"}\n\n\ndef load(path: str) -> dict[str, dict]:\n    with open(path) as f:\n        return {record[\"repo\"]: record for record in map(json.loads, f)}\n\n\ndef diff(before: dict, after: dict, prefix: str = \"\"):\n    for key in sorted(set(before) | set(after)):\n        if key in IGNORED:\n            continue\n        old, new = before.get(key, \"<MISSING>\"), after.get(key, \"<MISSING>\")\n        if isinstance(old, dict) and isinstance(new, dict) and key != \"rope_parameters\":\n            yield from diff(old, new, f\"{prefix}{key}.\")\n        elif old != new:\n            yield f\"{prefix}{key}\", json.dumps(old), json.dumps(new)\n\n\ndef collapse(diffs) -> Counter:\n    \"\"\"Merge diffs that differ only by layer index, e.g. `layers.*.scaling`.\"\"\"\n    return Counter(\n        (re.sub(r\"\\.\\d+\\.\", \".*.\", path), old, new) for path, old, new in diffs\n    )\n\n\nbefore, after = load(sys.argv[1]), load(sys.argv[2])\nfor repo, old in before.items():\n    new = after.get(repo, {\"error\": \"missing from after\"})\n    if \"error\" in old or \"error\" in new:\n        print(f\"== {repo}\\n   before: {old.get('error', 'ok')}\")\n        print(f\"   after:  {new.get('error', 'ok')}\")\n        continue\n    diffs = collapse(diff(old[\"cfg\"], new[\"cfg\"]))\n    print(f\"== {repo}: {old['cls']} -> {new['cls']} ({sum(diffs.values())} diffs)\")\n    for (path, old_value, new_value), count in diffs.items():\n        times = f\" (x{count})\" if count > 1 else \"\"\n        print(f\"   {path}{times}: before={old_value} after={new_value}\")\n", "skills/transformers-upgrade/scripts/dump_configs.py": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\"\"\"Dump the config vLLM resolves for each checkpoint, one JSON line per repo.\n\nRun once per vLLM tree (before and after a change), then compare the two\noutputs with diff_dumps.py:\n\n    PYTHONPATH=<vllm tree> .venv/bin/python dump_configs.py out.jsonl <repo>...\n\nPass --trust-remote-code to resolve checkpoints the way users who set it do.\n\"\"\"\n\nimport json\nimport sys\n\nfrom vllm.transformers_utils.config import get_config\n\nout, *args = sys.argv[1:]\ntrust_remote_code = \"--trust-remote-code\" in args\nwith open(out, \"w\") as f:\n    for repo in (arg for arg in args if arg != \"--trust-remote-code\"):\n        try:\n            config = get_config(repo, trust_remote_code=trust_remote_code)\n            cls = f\"{type(config).__module__}.{type(config).__name__}\"\n            record = {\"repo\": repo, \"cls\": cls, \"cfg\": config.to_dict()}\n        except Exception as e:\n            error = f\"{type(e).__name__}: {e}\".splitlines()[0]\n            record = {\"repo\": repo, \"error\": error}\n        f.write(json.dumps(record, default=str, sort_keys=True) + \"\\n\")\n        f.flush()\n", "skills/transformers-upgrade/scripts/dump_model.py": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\"\"\"Build each model on the meta device and dump what vLLM constructs.\n\nRecords ModelConfig-derived sizes, every parameter shape, and scalar\nattributes of every module (head_dim, num_kv_heads, sliding_window, ...).\nNeeds no GPU and no weights. Run once per vLLM tree, then compare the two\noutputs with diff_dumps.py:\n\n    PYTHONPATH=<vllm tree> .venv/bin/python dump_model.py out.jsonl <repo>...\n\nPass --trust-remote-code to resolve checkpoints the way users who set it do.\n\"\"\"\n\nimport json\nimport socket\nimport sys\n\nimport torch\n\nfrom vllm.config import set_current_vllm_config\nfrom vllm.config.vllm import VllmConfig\nfrom vllm.distributed import (\n    init_distributed_environment,\n    initialize_model_parallel,\n    model_parallel_is_initialized,\n)\nfrom vllm.engine.arg_utils import EngineArgs\nfrom vllm.model_executor.model_loader.utils import initialize_model\nfrom vllm.utils.torch_utils import set_default_torch_dtype\n\n# Construction only: skip model runner checks that need a GPU or Triton\nVllmConfig._get_v1_model_runner_unsupported_features = lambda self: []  # type: ignore[method-assign]\n\n# Model code that moves submodules to a device must leave them on meta\n_module_to = torch.nn.Module.to\n\n\ndef _meta_safe_to(self, *args, **kwargs):\n    kwargs.pop(\"device\", None)\n    args = tuple(a for a in args if not isinstance(a, (torch.device, str, int)))\n    return _module_to(self, *args, **kwargs)\n\n\ntorch.nn.Module.to = _meta_safe_to  # type: ignore[method-assign]\n\nSCALARS = (bool, int, float, str)\n\n\ndef module_attrs(model: torch.nn.Module) -> dict[str, dict]:\n    attrs = {}\n    for name, module in model.named_modules():\n        scalars = {\n            key: value\n            for key, value in vars(module).items()\n            if not key.startswith(\"_\") and isinstance(value, SCALARS)\n        }\n        if scalars:\n            attrs[name or \"<root>\"] = scalars\n    return attrs\n\n\ndef dump(repo: str, trust_remote_code: bool) -> dict:\n    args = EngineArgs(\n        model=repo,\n        load_format=\"dummy\",\n        enforce_eager=True,\n        max_model_len=4096,\n        trust_remote_code=trust_remote_code,\n    )\n    vllm_config = args.create_engine_config()\n    model_config = vllm_config.model_config\n    with set_current_vllm_config(vllm_config):\n        if not model_parallel_is_initialized():\n            with socket.socket() as sock:\n                sock.bind((\"\", 0))\n                port = sock.getsockname()[1]\n            init_distributed_environment(1, 0, f\"tcp://127.0.0.1:{port}\", 0, \"gloo\")\n            initialize_model_parallel(1, 1)\n        with set_default_torch_dtype(model_config.dtype), torch.device(\"meta\"):\n            model = initialize_model(vllm_config=vllm_config)\n    return {\n        \"repo\": repo,\n        \"cls\": type(model).__name__,\n        \"cfg\": {\n            \"model_config\": {\n                \"head_size\": model_config.get_head_size(),\n                \"total_num_kv_heads\": model_config.get_total_num_kv_heads(),\n                \"sliding_window\": model_config.get_sliding_window(),\n                \"num_layers\": model_config.get_num_layers(vllm_config.parallel_config),\n            },\n            \"params\": {n: list(p.shape) for n, p in model.named_parameters()},\n            \"modules\": module_attrs(model),\n        },\n    }\n\n\ndef main() -> None:\n    out, *args = sys.argv[1:]\n    trust_remote_code = \"--trust-remote-code\" in args\n    repos = [arg for arg in args if arg != \"--trust-remote-code\"]\n    with open(out, \"w\") as f:\n        for repo in repos:\n            try:\n                record = dump(repo, trust_remote_code)\n            except Exception as e:\n                error = f\"{type(e).__name__}: {e}\".splitlines()[0]\n                record = {\"repo\": repo, \"error\": error}\n            f.write(json.dumps(record, default=str, sort_keys=True) + \"\\n\")\n            f.flush()\n\n\nif __name__ == \"__main__\":\n    main()\n", "skills/transformers-upgrade/scripts/find_upstreamed.py": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\"\"\"List vendored vLLM code that the installed Transformers may make redundant.\n\nRun with the Transformers version under test, from the vLLM repo root:\n\n    uv run --no-project --with transformers==<version> \\\n        python .agents/skills/transformers-upgrade/scripts/find_upstreamed.py\n\nImports nothing from vLLM, so no vLLM install is needed. Uses the `gh` CLI, if\navailable, to check whether referenced Transformers PRs are in this release.\n\"\"\"\n\nimport json\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nimport regex as re\nimport transformers\nfrom packaging.version import Version\nfrom transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES\nfrom transformers.models.auto.processing_auto import PROCESSOR_MAPPING_NAMES\n\nROOT = Path(sys.argv[1] if len(sys.argv) > 1 else \".\")\nFLOOR = Version(transformers.__version__)\nUPSTREAM_NAMES = set(dir(transformers))\n\nMODEL_TYPE = re.compile(r'model_type\\s*(?::\\s*str\\s*)?=\\s*\"([^\"]+)\"')\nREGISTRY_KEY = re.compile(r'^\\s+(?:\\*\\*\\{)?\"?([\\w-]+)\"?(?:=|\": )\"(\\w+)\"', re.M)\nCLASS_KEY = re.compile(r'^\\s+\"(\\w+)\": ', re.M)\nUPSTREAM_REF = re.compile(\n    r\"huggingface/transformers(?:/(?:issues|pull)/|#)(\\d+)\"\n    r\"|(?:once|until|when) [Tt]ransformers [\\d.]+ is the minimum\"\n)\nVERSIONED = re.compile(\n    r\"(?:min_transformers_version|max_transformers_version|check_version|Version)\"\n    r'\\(?\\s*=?\\s*\"([45]\\.\\d+(?:\\.\\d+)?)[^\"]*\"'\n    r\"|[Tt]ransformers\\s*(?:v|[<>]=?\\s*)([45]\\.\\d+(?:\\.\\d+)?|4)\\b\"\n)\nREADS_VERSION = re.compile(\n    r\"transformers import __version__|transformers\\.__version__\"\n    r\"|version\\([\\\"']transformers[\\\"']\\)|TRANSFORMERS_VERSION|check_version\\(\"\n)\n\n\ndef section(title: str) -> None:\n    print(f\"\\n## {title}\")\n\n\ndef vendored_configs() -> None:\n    section(f\"Vendored configs whose model_type is upstream in {FLOOR}\")\n    files = sorted(ROOT.glob(\"vllm/transformers_utils/configs/*.py\"))\n    files += sorted(ROOT.glob(\"vllm/models/*/config*.py\"))\n    files += sorted(ROOT.glob(\"vllm/models/*/configs/*.py\"))\n    for path in files:\n        types = sorted(set(MODEL_TYPE.findall(path.read_text())))\n        hits = [t for t in types if t in CONFIG_MAPPING_NAMES]\n        if hits:\n            upstream = \", \".join(f\"{t} -> {CONFIG_MAPPING_NAMES[t]}\" for t in hits)\n            print(f\"- {path.relative_to(ROOT)}: {upstream}\")\n\n    registry = (ROOT / \"vllm/transformers_utils/config.py\").read_text()\n    start = registry.index(\"_CONFIG_REGISTRY\")\n    body = registry[start : registry.index(\"\\n)\\n\", start)]\n    section(\"_CONFIG_REGISTRY entries that override an upstream model_type\")\n    for model_type, cls in REGISTRY_KEY.findall(body):\n        if model_type in CONFIG_MAPPING_NAMES:\n            print(f\"- {model_type}: vLLM {cls} over {CONFIG_MAPPING_NAMES[model_type]}\")\n\n\ndef vendored_processors() -> None:\n    init = (ROOT / \"vllm/transformers_utils/processors/__init__.py\").read_text()\n    names = sorted(set(CLASS_KEY.findall(init)))\n    section(\"Registered processor names that collide with upstream classes\")\n    for name in names:\n        if name in UPSTREAM_NAMES:\n            print(f\"- {name}\")\n    section(\"Processor files named after a model_type with an upstream processor\")\n    for path in sorted(ROOT.glob(\"vllm/transformers_utils/processors/*.py\")):\n        if path.stem in PROCESSOR_MAPPING_NAMES:\n            upstream = PROCESSOR_MAPPING_NAMES[path.stem]\n            print(f\"- {path.relative_to(ROOT)} -> {upstream}\")\n\n\ndef version_gates() -> None:\n    files = sorted([*ROOT.glob(\"vllm/**/*.py\"), *ROOT.glob(\"tests/**/*.py\")])\n    section(f\"Version-gated code at or below {FLOOR} (review each)\")\n    for path in files:\n        for lineno, line in enumerate(path.read_text().splitlines(), 1):\n            for match in VERSIONED.finditer(line):\n                version = Version(match.group(1) or match.group(2))\n                if version <= FLOOR:\n                    print(f\"- {path.relative_to(ROOT)}:{lineno}: {line.strip()}\")\n                    break\n    section(\"Code that reads the installed Transformers version (review each)\")\n    for path in files:\n        for lineno, line in enumerate(path.read_text().splitlines(), 1):\n            if READS_VERSION.search(line):\n                print(f\"- {path.relative_to(ROOT)}:{lineno}: {line.strip()}\")\n\n\ndef upstream_status(number: str) -> str:\n    \"\"\"Whether Transformers issue/PR `number` is resolved in this release.\"\"\"\n\n    def gh(path: str) -> dict | None:\n        try:\n            out = subprocess.run([\"gh\", \"api\", path], capture_output=True, text=True)\n        except FileNotFoundError:\n            return None\n        return json.loads(out.stdout) if out.returncode == 0 else None\n\n    repo = \"repos/huggingface/transformers\"\n    if (issue := gh(f\"{repo}/issues/{number}\")) is None:\n        return \"status unknown\"\n    if \"pull_request\" not in issue:\n        return f\"issue {issue['state']}, check which PR fixed it\"\n    pr = gh(f\"{repo}/pulls/{number}\")\n    if pr is None or not pr[\"merged_at\"]:\n        return \"PR not merged\"\n    compare = gh(f\"{repo}/compare/v{FLOOR}...{pr['merge_commit_sha']}\")\n    included = compare and compare[\"status\"] in (\"behind\", \"identical\")\n    return f\"PR merged, {'in' if included else 'not in'} v{FLOOR}\"\n\n\ndef upstream_refs() -> None:\n    section(\"Patches referencing Transformers issues/PRs or a future minimum\")\n    files = sorted([*ROOT.glob(\"vllm/**/*.py\"), *ROOT.glob(\"tests/**/*.py\")])\n    statuses: dict[str, str] = {}\n    for path in files:\n        for lineno, line in enumerate(path.read_text().splitlines(), 1):\n            if (match := UPSTREAM_REF.search(line)) is None:\n                continue\n            note = \"\"\n            if number := match.group(1):\n                if number not in statuses:\n                    statuses[number] = upstream_status(number)\n                note = f\" [#{number}: {statuses[number]}]\"\n            print(f\"- {path.relative_to(ROOT)}:{lineno}:{note} {line.strip()}\")\n\n\nif __name__ == \"__main__\":\n    print(f\"# Transformers {FLOOR}\")\n    vendored_configs()\n    vendored_processors()\n    version_gates()\n    upstream_refs()\n", "skills/triton-kernel-writing/SKILL.md": "---\nname: triton-kernel-writing\ndescription: Write or review Triton kernels for vLLM, with practical guidance for generated-code inspection, launch grids, indexing, specialization, tuning, and representative performance validation. Use when adding, modifying, optimizing, or reviewing a `@triton.jit` kernel in vLLM.\n---\n\n# Triton Kernel Writing\n\n## Implementation\n\n- Follow the official\n  [Triton semantics](https://triton-lang.org/main/python-api/triton-semantics.html).\n  Check it when behavior may differ from Python or NumPy, especially type\n  promotion, integer division and modulo, casts, broadcasting, and variable\n  scoping.\n- Use the Triton kernel generated by `torch.compile` as a possible\n  implementation to inspect. Print Inductor's generated code with\n  `TORCH_LOGS=\"output_code\" .venv/bin/python <script>` or enable\n  `torch._logging.set_logs(output_code=True)` before the compiled function\n  runs. Treat generated code as a reference, not as proof of correctness or\n  optimality.\n- Find reasonable defaults for compile-time knobs such as `BLOCK_SIZE`, or use\n  a small, legible heuristic when workloads need different choices. Use\n  `triton.autotune` only when tuning is critical to performance, such as for a\n  matrix multiplication. Otherwise prioritize simple code and fast startup.\n- Avoid unintended runtime JIT compilation. Put unimportant runtime integer\n  scalars in `do_not_specialize`, especially values that alternate between 0\n  and 1. Pointer alignment also affects specialization: an offset tensor view\n  can trigger a new variant after warmup used an aligned allocation. For\n  scalar-only pointers whose alignment provides no useful optimization, use\n  `@triton.jit(do_not_specialize_on_alignment=[\"end_ptr\"])`. Retain alignment\n  specialization when vectorized accesses benefit from it. See the\n  [Triton JIT options](https://triton-lang.org/main/python-api/generated/triton.jit.html).\n- The Triton compiler does not guarantee safe ordering when a kernel writes to\n  a pointer and subsequently reads from the same pointer. This pattern must\n  have a `tl.debug_barrier()` between the write and read. The barrier\n  synchronizes threads in the block; it does not synchronize separate program\n  instances.\n\n## Launch and Indexing\n\n- `grid[1]` and `grid[2]` must be at most 65,535. Choose or flatten the grid\n  order so those dimensions cannot exceed the limit for supported shapes.\n  For example, `num_tokens` is commonly 8K or 16K, but users may configure 32K\n  or more. If `num_tokens` is a grid dimension, it is safe to put it in\n  `grid[0]` (or tile it).\n- Use `int64` for offset arithmetic when an index can exceed 32-bit range,\n  especially for KV-cache addressing. Cast operands before multiplication or\n  addition so an intermediate does not overflow in 32-bit arithmetic.\n- A `[num_tokens, num_heads]` grid can be a good low-latency mapping for decode,\n  but it can be very slow for prefill. If the kernel serves prefill, consider\n  tiling tokens or otherwise increasing the work and locality per program.\n\n## Validation\n\n- Check correctness at boundary shapes and at sizes that exercise masks and\n  large offsets. Include offset tensor views, not only fresh allocations.\n  Warm aligned buffers, then exercise offset views with vLLM's\n  `--jit-monitor-mode error --jit-monitor-verbose` to catch missing variants.\n- Choose accumulation and intermediate dtypes explicitly. Test numerically\n  difficult inputs, not only random, well-scaled tensors.\n- Use `$kernel-microbenchmark` for benchmark construction, measurement, and\n  interpretation.\n- Benchmark a sweep of `num_tokens` covering decode and representative prefill\n  workloads. Include relevant head counts and dimensions when they affect the\n  launch shape, and do not select an implementation or tuning heuristic from a\n  single setup.\n- Include compilation or autotuning overhead when evaluating startup behavior;\n  report steady-state kernel performance separately.\n", "skills/triton-kernel-writing/agents/openai.yaml": "interface:\n  display_name: \"Triton Kernel Writing\"\n  short_description: \"Write robust, practical Triton kernels for vLLM.\"\n  default_prompt: \"Use $triton-kernel-writing to implement or review this Triton kernel.\"\n"}}
