Skip to content
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,13 @@ repos:
entry: python tools/pre_commit/check_boolean_context_manager.py
language: python
types: [python]
- id: check-docstring-crossrefs
name: Check for accidental cross-references in docstrings
entry: python tools/pre_commit/check_docstring_crossrefs.py
language: python
types: [python]
files: ^vllm/
additional_dependencies: [regex]
- id: check-trust-remote-code
name: Check for hardcoded trust_remote_code=True
entry: python tools/pre_commit/check_trust_remote_code.py
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ pre-commit run ruff-check --all-files
The line length limit for Python code is 88 characters. If you are not sure, use pre-commit to check.

Use [Google-style docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) (`Args:`/`Returns:`/`Raises:` sections), not reStructuredText/Sphinx fields (`:param:`, `:return:`, `:rtype:`).
Docstrings render as Markdown: wrap shapes and indexing like `[block][2][16]` in backticks, or mkdocs reads them as cross-references (the `check-docstring-crossrefs` hook catches this).

### Coding style guidelines

Expand Down
87 changes: 87 additions & 0 deletions tools/pre_commit/check_docstring_crossrefs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Lint: detect accidental cross-references in docstrings.

Docstrings render as Markdown in the API docs, where `[a][b]` is a reference
link that mkdocs-autorefs tries to resolve. Shapes and indexing written outside
code spans therefore produce broken cross-references:

[block][2][16] # BUG: looks up targets "2" and "16"
``[block][2][16]`` # OK: code span
[LLM][vllm.LLM] # OK: intended cross-reference
"""

import ast
import inspect
import sys

import regex as re

FENCE = re.compile(r"^\s*(```|~~~).*?^\s*\1", re.DOTALL | re.MULTILINE)
CODE_SPAN = re.compile(r"(`+).+?\1", re.DOTALL)
REF_LINK = re.compile(r"\[([^\[\]\n]+)\]\[([^\[\]\n]*)\]")
# Fully qualified Python paths, e.g. `vllm.LLM` or `torch.Tensor`
TARGET = re.compile(r"[A-Za-z_]\w*(\.[A-Za-z_]\w*)+")


def strip_indented_code(doc: str) -> str:
"""Drop Markdown indented code blocks (4+ spaces after a blank line)."""
kept, in_code, prev_blank = [], False, True
for line in inspect.cleandoc(doc).splitlines():
if not line.strip():
prev_blank = True
kept.append(line)
continue
in_code = line.startswith(" ") and (prev_blank or in_code)
prev_blank = False
if not in_code:
kept.append(line)
return "\n".join(kept)


def iter_docstrings(node: ast.AST):
"""Yield docstrings that mkdocstrings renders (not nested functions)."""
doc = ast.get_docstring(node, clean=False)
if doc is not None:
yield node.body[0].lineno, doc
if isinstance(node, (ast.Module, ast.ClassDef)):
for child in node.body:
if isinstance(child, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
yield from iter_docstrings(child)


def check_file(filepath: str) -> list[str]:
try:
with open(filepath, encoding="utf-8") as f:
tree = ast.parse(f.read(), filename=filepath)
except (OSError, UnicodeDecodeError, SyntaxError):
return []

violations = []
for lineno, doc in iter_docstrings(tree):
text = CODE_SPAN.sub("", FENCE.sub("", strip_indented_code(doc)))
for match in REF_LINK.finditer(text):
label, target = match.groups()
if not TARGET.fullmatch(target or label):
violations.append(f"{filepath}:{lineno}: {match.group()}")
return violations


def main() -> int:
violations = []
for filepath in sys.argv[1:]:
violations.extend(check_file(filepath))

if violations:
print("❌ Docstring text that mkdocs will read as a cross-reference:")
print("\n".join(f" {v}" for v in violations))
print(
" Wrap shapes and indexing in backticks (``[block][2][16]``), or "
"use a fully qualified target ([LLM][vllm.LLM])."
)
return 1
return 0


if __name__ == "__main__":
sys.exit(main())
4 changes: 2 additions & 2 deletions vllm/_custom_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -3355,8 +3355,8 @@ def swap_blocks(
and their matching destination block number on the destination tensor.
block_mapping is expected to be a tensor of shape (num_blocks_to_copy, 2)
where each block_mapping[i] represents a single copy operation, copying
block #block_mapping[i][0] from the source tensor
to block #block_mapping[i][1] on the destination tensor.
block ``block_mapping[i][0]`` from the source tensor
to block ``block_mapping[i][1]`` on the destination tensor.
block_mapping should have dtype int64.

The source and the destination tensors can be either on cpu or gpu,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def sent_on(c, which="ar"):

def sent_ix(src, col, t, s, width):
"""(OPT_SENT) Word index of (src rank, pair at ``col``, token t), blocked
[src][16-col group][token][8 pairs]; shared by push and reduce."""
``[src][16-col group][token][8 pairs]``; shared by push and reduce."""
return ((src * (width // 16) + col // 16) * s + t) * 8 + (col % 16) // 2


Expand Down
2 changes: 1 addition & 1 deletion vllm/models/kimi_k3/amd/specialized_decode/mono/layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def sent_bytes() -> int:

def rlogp_half_bytes() -> int:
"""(OPT_RLOG_PARTS) One epoch parity's RLOGP, tagged pairs
[src rank][part][token][router row], SENT_ROWS rows."""
``[src rank][part][token][router row]``, SENT_ROWS rows."""
return TP_ * k2b.R_PARTS * SENT_ROWS * (k2b.E // TP_) * 8


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ def _route_out(c, t, red, sel, rank, me, ms):
@traced
def route_parts(c, t):
"""(OPT_RLOG_PARTS) Token t's router partials (every rank's 4 K
parts, RLOGP) -> LDS ``vals`` [part][expert], wave q < R_PARTS polling part
parts, RLOGP) -> LDS ``vals[part][expert]``, wave q < R_PARTS polling part
q (one batch: the 14 experts of its lane); ``stage_route`` sums each
expert's parts in part order, as the router's part 0 did."""
s, lane, wave = c["S"], c["lane"], c["wave"]
Expand Down
5 changes: 3 additions & 2 deletions vllm/models/minimax_m3/amd/mono/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,9 @@ def _layout(items, align=256):


def sym_layout(npes: int):
"""Per-rank symmetric buffer: attn / ffn partial regions, [src rank][token][HIDDEN],
and the peers' index-selection candidates (``sel_cp``)."""
"""Per-rank symmetric buffer: attn / ffn partial regions,
``[src rank][token][HIDDEN]``, and the peers' index-selection candidates
(``sel_cp``)."""
rows = npes * MAX_TOKENS * HIDDEN // 2
# a_ag / ffn_ag: the finished attention / FFN all-reduce rows, each written by
# its owner rank (the reduce-scatter + all-gather form, S >= AG_RS_FROM)
Expand Down
8 changes: 4 additions & 4 deletions vllm/models/muse_spark/amd/mono/kernels/attn_frag.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@

Shapes (a TP8 rank): 16 q heads, 2 kv heads (QPK = 8), head dim 64, 8 query tokens a request,
NR requests (K3 S8: 1, S16: 2; HA S32: 4). K / V bf16 in the layer's vLLM LBHNC cache
[block][2][16][K 64 | V 64] (block 16); the page table is the layer group's block_table
(int32 [NR][stride]); seq_used = vLLM's seq_lens (int32 [NR], keys incl. the 8 new ones).
``[block][2][16][K 64 | V 64]`` (block 16); the page table is the layer group's block_table
(int32 ``[NR][stride]``); seq_used = vLLM's seq_lens (int32 [NR], keys incl. the 8 new ones).
q [8 NR, 16, 64] bf16 (row stride 1024, without the QK scale); out attn_o [8 NR, 1024] bf16.
SWA: vLLM's window (2047, 0), keys qpos - key < 2048, and only keys in the window are read
(vLLM frees the blocks before it: their block-table entries are stale).
Expand Down Expand Up @@ -633,8 +633,8 @@ def vllm_scale_word(scale):

def vllm_desc(q, kv_cache, block_table, seq_lens, out, part, nreq, scale):
"""The 10 descriptor words of one layer: q [8 nreq.., 16 x 64] bf16 rows,
kv_cache the layer's [block][2][16][128] bf16 view (block stride = kv_cache.stride(0)), block_table int32
[>= nreq][stride] of the layer's group, seq_lens int32 [>= nreq], out attn_o [rows, 1024] bf16, part the scratch
kv_cache the layer's ``[block][2][16][128]`` bf16 view (block stride = kv_cache.stride(0)), block_table int32
``[>= nreq][stride]`` of the layer's group, seq_lens int32 [>= nreq], out attn_o [rows, 1024] bf16, part the scratch
(int32, part_bytes()), nreq the requests of the step (graph padding included: seq_len 0 = no keys, zero rows)."""
import torch

Expand Down
Loading