vllm-knapsack-weight-replication 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. vllm_knapsack_weight_replication/__init__.py +5 -0
  2. vllm_knapsack_weight_replication/_envs.py +82 -0
  3. vllm_knapsack_weight_replication/_patching.py +83 -0
  4. vllm_knapsack_weight_replication/_transplant.py +224 -0
  5. vllm_knapsack_weight_replication/autotune_patch.py +50 -0
  6. vllm_knapsack_weight_replication/canonical_topk.py +247 -0
  7. vllm_knapsack_weight_replication/models/__init__.py +0 -0
  8. vllm_knapsack_weight_replication/models/deepseek_v41.py +20 -0
  9. vllm_knapsack_weight_replication/models/dsa.py +20 -0
  10. vllm_knapsack_weight_replication/models/dsa_auto.py +112 -0
  11. vllm_knapsack_weight_replication/models/dsv41_auto.py +19 -0
  12. vllm_knapsack_weight_replication/models/minimax_m3.py +20 -0
  13. vllm_knapsack_weight_replication/models/qwen3_5.py +94 -0
  14. vllm_knapsack_weight_replication/models/qwen3_5_replicate.py +47 -0
  15. vllm_knapsack_weight_replication/plugin.py +122 -0
  16. vllm_knapsack_weight_replication/topk_patch.py +168 -0
  17. vllm_knapsack_weight_replication/tp_synced_autotune.py +190 -0
  18. vllm_knapsack_weight_replication/upstream/__init__.py +0 -0
  19. vllm_knapsack_weight_replication/upstream/dsa/__init__.py +0 -0
  20. vllm_knapsack_weight_replication/upstream/dsa/manifest.py +24 -0
  21. vllm_knapsack_weight_replication/upstream/dsa/vllm/models/deepseek_v32/attention.py +801 -0
  22. vllm_knapsack_weight_replication/upstream/dsa/vllm/models/deepseek_v32/nvidia/model.py +514 -0
  23. vllm_knapsack_weight_replication/upstream/dsa/vllm/v1/attention/backends/mla/flashinfer_mla_sparse_sm120.py +257 -0
  24. vllm_knapsack_weight_replication/upstream/dsa_auto/__init__.py +0 -0
  25. vllm_knapsack_weight_replication/upstream/dsa_auto/manifest.py +27 -0
  26. vllm_knapsack_weight_replication/upstream/dsa_auto/vllm/model_executor/layers/tp_replication.py +75 -0
  27. vllm_knapsack_weight_replication/upstream/dsa_auto/vllm/model_executor/layers/tp_replication_planner.py +763 -0
  28. vllm_knapsack_weight_replication/upstream/dsa_auto/vllm/model_executor/layers/tp_replication_probe.py +484 -0
  29. vllm_knapsack_weight_replication/upstream/dsa_auto/vllm/models/deepseek_v32/nvidia/model.py +646 -0
  30. vllm_knapsack_weight_replication/upstream/dsv41/__init__.py +0 -0
  31. vllm_knapsack_weight_replication/upstream/dsv41/manifest.py +24 -0
  32. vllm_knapsack_weight_replication/upstream/dsv41/vllm/models/deepseek_v41/attention.py +1772 -0
  33. vllm_knapsack_weight_replication/upstream/dsv41/vllm/models/deepseek_v41/nvidia/flash_mla_mega_attn.py +618 -0
  34. vllm_knapsack_weight_replication/upstream/dsv41/vllm/models/deepseek_v41/nvidia/model.py +2088 -0
  35. vllm_knapsack_weight_replication/upstream/dsv41/vllm/models/deepseek_v41/nvidia/specialized_decode/__init__.py +214 -0
  36. vllm_knapsack_weight_replication/upstream/dsv41_auto/__init__.py +0 -0
  37. vllm_knapsack_weight_replication/upstream/dsv41_auto/manifest.py +20 -0
  38. vllm_knapsack_weight_replication/upstream/dsv41_auto/vllm/models/deepseek_v41/nvidia/flash_mla_mega_attn.py +621 -0
  39. vllm_knapsack_weight_replication/upstream/dsv41_auto/vllm/models/deepseek_v41/nvidia/model.py +2181 -0
  40. vllm_knapsack_weight_replication/upstream/dsv41_auto/vllm/models/deepseek_v41/nvidia/specialized_decode/__init__.py +218 -0
  41. vllm_knapsack_weight_replication/upstream/minimax_m3/__init__.py +0 -0
  42. vllm_knapsack_weight_replication/upstream/minimax_m3/manifest.py +27 -0
  43. vllm_knapsack_weight_replication/upstream/minimax_m3/vllm/model_executor/layers/linear.py +1905 -0
  44. vllm_knapsack_weight_replication/upstream/minimax_m3/vllm/models/minimax_m3/common/indexer.py +793 -0
  45. vllm_knapsack_weight_replication/upstream/minimax_m3/vllm/models/minimax_m3/common/replicate.py +32 -0
  46. vllm_knapsack_weight_replication/upstream/minimax_m3/vllm/models/minimax_m3/nvidia/model.py +2032 -0
  47. vllm_knapsack_weight_replication/upstream/minimax_m3/vllm/models/minimax_m3/nvidia/sparse_attention_msa.py +604 -0
  48. vllm_knapsack_weight_replication-0.5.0.dist-info/METADATA +122 -0
  49. vllm_knapsack_weight_replication-0.5.0.dist-info/RECORD +53 -0
  50. vllm_knapsack_weight_replication-0.5.0.dist-info/WHEEL +5 -0
  51. vllm_knapsack_weight_replication-0.5.0.dist-info/entry_points.txt +2 -0
  52. vllm_knapsack_weight_replication-0.5.0.dist-info/licenses/LICENSE +202 -0
  53. vllm_knapsack_weight_replication-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,5 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ """TP block replication for vLLM, packaged as a general plugin."""
4
+
5
+ __version__ = "0.5.0"
@@ -0,0 +1,82 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ """The switches, under the same names as the vLLM pull requests.
4
+
5
+ They are added to `vllm.envs.environment_variables`, so `vllm.envs.<NAME>` works in
6
+ the patched code and moving to a vLLM that ships them needs no configuration change.
7
+ """
8
+
9
+ import os
10
+ from collections.abc import Callable
11
+ from typing import Any
12
+
13
+
14
+ def _flag(name: str) -> Callable[[], bool]:
15
+ return lambda: os.getenv(name, "0").strip().lower() in ("1", "true")
16
+
17
+
18
+ FLAGS: dict[str, Callable[[], Any]] = {
19
+ # vllm-project/vllm#66526: every TP rank adopts rank 0's Triton autotune choice.
20
+ "VLLM_TRITON_SYNC_AUTOTUNE_TP": _flag("VLLM_TRITON_SYNC_AUTOTUNE_TP"),
21
+ # vllm-project/vllm#67044: canonical (deterministic) sparse-indexer top-k.
22
+ "VLLM_DETERMINISTIC_SPARSE_TOPK": _flag("VLLM_DETERMINISTIC_SPARSE_TOPK"),
23
+ # vllm-project/vllm#67285: dense Qwen3.5 keeps every MLP whole on each TP rank.
24
+ "VLLM_KNAPSACK_QWEN3_5_FFN": _flag("VLLM_KNAPSACK_QWEN3_5_FFN"),
25
+ # vllm-project/vllm#66867: DSA models (DeepSeek-V3.2, GLM-5.x) keep every
26
+ # sparse-MLA layer whole on each TP rank; MoE/MLP stay tensor-parallel.
27
+ "VLLM_KNAPSACK_DSA_ATTN": _flag("VLLM_KNAPSACK_DSA_ATTN"),
28
+ # With VLLM_KNAPSACK_DSA_ATTN, steps with fewer tokens than this run the
29
+ # attention head-sharded on slices of the replicated weights, then all-reduce.
30
+ "VLLM_KNAPSACK_DSA_ATTN_MIN_TOKENS": lambda: int(
31
+ os.getenv("VLLM_KNAPSACK_DSA_ATTN_MIN_TOKENS", "0")
32
+ ),
33
+ # vllm-project/vllm#66869: DeepSeek-V4.1 keeps every attention layer whole on
34
+ # each TP rank; MoE stays tensor-parallel.
35
+ "VLLM_KNAPSACK_DSV41_MIXER": _flag("VLLM_KNAPSACK_DSV41_MIXER"),
36
+ # vllm-project/vllm#66378: MiniMax-M3 keeps every attention layer whole on each
37
+ # TP rank; MoE stays tensor-parallel.
38
+ "VLLM_KNAPSACK_MINIMAX_M3_ATTN": _flag("VLLM_KNAPSACK_MINIMAX_M3_ATTN"),
39
+ # Per-layer replication (online planner, DSA models so far): "auto" picks the
40
+ # layers from the probe and the memory budget; "kind:0-3,7;..." names them.
41
+ # Unset: the per-model switches above apply.
42
+ "VLLM_KNAPSACK_PLAN": lambda: os.getenv("VLLM_KNAPSACK_PLAN", ""),
43
+ # `vllm serve` first runs the probe unless a result for the same arguments
44
+ # exists (single node). The result is the JSON the "auto" plan reads.
45
+ "VLLM_KNAPSACK_PROBE": lambda: bool(int(os.getenv("VLLM_KNAPSACK_PROBE", "0"))),
46
+ "VLLM_KNAPSACK_PROBE_RESULT": lambda: os.getenv("VLLM_KNAPSACK_PROBE_RESULT", ""),
47
+ # Load the "auto" plan sizes memory and weighs gains for: sessions whose KV
48
+ # stays resident, tokens per session (0: max_model_len), decode batch, a
49
+ # typical request's new prompt and output tokens, and the mean accepted
50
+ # draft tokens per verify step. Without sessions, a fixed budget in GiB.
51
+ "VLLM_KNAPSACK_SESSIONS": lambda: int(os.getenv("VLLM_KNAPSACK_SESSIONS", "0")),
52
+ "VLLM_KNAPSACK_SESSION_TOKENS": lambda: int(
53
+ os.getenv("VLLM_KNAPSACK_SESSION_TOKENS", "0")
54
+ ),
55
+ "VLLM_KNAPSACK_DECODE_BS": lambda: int(os.getenv("VLLM_KNAPSACK_DECODE_BS", "1")),
56
+ "VLLM_KNAPSACK_ISL": lambda: int(os.getenv("VLLM_KNAPSACK_ISL", "0")),
57
+ "VLLM_KNAPSACK_OSL": lambda: int(os.getenv("VLLM_KNAPSACK_OSL", "0")),
58
+ "VLLM_KNAPSACK_SPEC_ACCEPT": lambda: float(
59
+ os.getenv("VLLM_KNAPSACK_SPEC_ACCEPT", "0")
60
+ ),
61
+ "VLLM_KNAPSACK_BUDGET_GIB": lambda: float(
62
+ os.getenv("VLLM_KNAPSACK_BUDGET_GIB", "0")
63
+ ),
64
+ # Host RAM per rank for idle sessions' KV (e.g. vLLM's KV offloading).
65
+ "VLLM_KNAPSACK_KV_OFFLOAD_GIB": lambda: float(
66
+ os.getenv("VLLM_KNAPSACK_KV_OFFLOAD_GIB", "0")
67
+ ),
68
+ }
69
+
70
+
71
+ def get(name: str) -> Any:
72
+ return FLAGS[name]()
73
+
74
+
75
+ def register() -> list[str]:
76
+ """Add the flags vLLM does not define yet; return the names vLLM already had."""
77
+ import vllm.envs as envs
78
+
79
+ shipped = [n for n in FLAGS if n in envs.environment_variables]
80
+ for name, read in FLAGS.items():
81
+ envs.environment_variables.setdefault(name, read)
82
+ return shipped
@@ -0,0 +1,83 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ """Small helpers shared by the patches: fail loudly when a hook point moved."""
4
+
5
+ import importlib
6
+ import sys
7
+ from types import ModuleType
8
+ from typing import Any
9
+
10
+
11
+ class HookPointMissing(RuntimeError):
12
+ """The installed vLLM lacks a function or class this package patches."""
13
+
14
+
15
+ def require(module: str, *attrs: str) -> ModuleType:
16
+ mod = importlib.import_module(module)
17
+ missing = [
18
+ a
19
+ for a in attrs
20
+ if not hasattr(_resolve(mod, a.split(".")[:-1]), a.split(".")[-1])
21
+ ]
22
+ if missing:
23
+ raise HookPointMissing(
24
+ f"vllm-knapsack-weight-replication: {module} has no "
25
+ f"{', '.join(missing)}; this vLLM version is not supported "
26
+ "(see README, Compatibility)."
27
+ )
28
+ return mod
29
+
30
+
31
+ def _resolve(obj: Any, path: list[str]) -> Any:
32
+ for part in path:
33
+ obj = getattr(obj, part)
34
+ return obj
35
+
36
+
37
+ def optional(module: str) -> ModuleType | None:
38
+ """Import a module that only some vLLM builds have (a model package)."""
39
+ try:
40
+ return importlib.import_module(module)
41
+ except ImportError:
42
+ return None
43
+
44
+
45
+ def alias_module(name: str, module: ModuleType) -> None:
46
+ """Expose `module` as `name` (e.g. vllm.triton_utils.tp_synced_autotune), so code
47
+ written against the upstream pull requests imports it unchanged."""
48
+ sys.modules[name] = module
49
+ if hasattr(module, "logger"):
50
+ # vLLM configures the "vllm" logger tree only: log under the upstream name.
51
+ from vllm.logger import init_logger
52
+
53
+ module.logger = init_logger(name)
54
+ parent, _, child = name.rpartition(".")
55
+ setattr(importlib.import_module(parent), child, module)
56
+
57
+
58
+ def wrap_method(cls: type, name: str, make: Any) -> None:
59
+ """Replace cls.name by make(original) once per `make`."""
60
+ original = cls.__dict__[name]
61
+ wrapped = _wrap(original, make)
62
+ if wrapped is not None:
63
+ setattr(cls, name, wrapped)
64
+
65
+
66
+ def wrap_function(module: ModuleType, name: str, make: Any) -> None:
67
+ """Replace a module-level function; callers that look it up at call time
68
+ (plain calls inside that module) see the wrapper."""
69
+ wrapped = _wrap(getattr(module, name), make)
70
+ if wrapped is not None:
71
+ setattr(module, name, wrapped)
72
+
73
+
74
+ def _wrap(original: Any, make: Any) -> Any:
75
+ """make(original), tagged with every wrapper in the chain; None if `make` is
76
+ already in it (plugins can be loaded more than once per process)."""
77
+ applied = getattr(original, "_vllm_knapsack_weight_replication", frozenset())
78
+ tag = f"{make.__module__}.{make.__qualname__}"
79
+ if tag in applied:
80
+ return None
81
+ wrapped = make(original)
82
+ wrapped._vllm_knapsack_weight_replication = applied | {tag}
83
+ return wrapped
@@ -0,0 +1,224 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ """Install a pull request's version of the symbols it changes, in memory.
4
+
5
+ The model pull requests edit constructors and forward passes deep inside vLLM
6
+ modules, where a wrapper cannot reach. For those, the package carries the PR's file
7
+ unchanged and a manifest (tools/sync_pr.py) naming each changed symbol with the
8
+ hash of its source at the PR base. When vLLM imports the module, every listed symbol
9
+ is checked against the installed source and replaced by the PR's version, compiled
10
+ in the module's own namespace. If one differs from the PR base, nothing is touched
11
+ and HookPointMissing names it: the plugin never patches code it was not written for.
12
+ Files on disk are never modified.
13
+ """
14
+
15
+ import ast
16
+ import hashlib
17
+ import importlib.machinery
18
+ import importlib.util
19
+ import re
20
+ import sys
21
+ import textwrap
22
+ from collections.abc import Callable
23
+ from pathlib import Path
24
+ from types import ModuleType
25
+ from typing import Any
26
+
27
+ from vllm_knapsack_weight_replication._patching import HookPointMissing
28
+
29
+ _PKG = Path(__file__).resolve().parent
30
+
31
+
32
+ def _segment(lines: list[str], node: ast.AST) -> tuple[str, int]:
33
+ start = min([node.lineno] + [d.lineno for d in getattr(node, "decorator_list", [])])
34
+ return textwrap.dedent("".join(lines[start - 1 : node.end_lineno])), start
35
+
36
+
37
+ def _entry(src: str, start: int) -> tuple[str, str, int]:
38
+ return src, hashlib.sha256(src.encode()).hexdigest()[:16], start
39
+
40
+
41
+ def symbol_sources(text: str) -> dict[str, tuple[str, str, int]]:
42
+ """name -> (source, hash, first line) for a module's symbols, in file order.
43
+
44
+ Names: top-level functions and assignments, `Class.member` for methods and
45
+ class attributes; `<...>` keys cover class headers and other top-level
46
+ statements (checked by the generator, never transplanted). Imports are left
47
+ out: the PR's imports are executed as a whole."""
48
+ lines = text.splitlines(keepends=True)
49
+ out: dict[str, tuple[str, str, int]] = {}
50
+ for node in ast.parse(text).body:
51
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
52
+ continue
53
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
54
+ out[node.name] = _entry(*_segment(lines, node))
55
+ elif isinstance(node, ast.ClassDef):
56
+ first = node.body[0].lineno
57
+ start = min([node.lineno] + [d.lineno for d in node.decorator_list])
58
+ out[f"<class {node.name}>"] = _entry(
59
+ "".join(lines[start - 1 : first - 1]), start
60
+ )
61
+ for member in node.body:
62
+ name = _member_name(member)
63
+ if name is not None:
64
+ out[f"{node.name}.{name}"] = _entry(*_segment(lines, member))
65
+ elif (name := _member_name(node)) is not None:
66
+ out[name] = _entry(*_segment(lines, node))
67
+ else:
68
+ src, start = _segment(lines, node)
69
+ out[f"<{src.splitlines()[0].strip()}>"] = _entry(src, start)
70
+ return out
71
+
72
+
73
+ def _member_name(node: ast.AST) -> str | None:
74
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
75
+ return node.name
76
+ if isinstance(node, ast.Assign) and len(node.targets) == 1:
77
+ target = node.targets[0]
78
+ return target.id if isinstance(target, ast.Name) else None
79
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
80
+ return node.target.id
81
+ return None
82
+
83
+
84
+ def _imports(text: str) -> list[tuple[str, int]]:
85
+ lines = text.splitlines(keepends=True)
86
+ return [
87
+ _segment(lines, node)
88
+ for node in ast.parse(text).body
89
+ if isinstance(node, (ast.Import, ast.ImportFrom))
90
+ ]
91
+
92
+
93
+ def _compile(src: str, start: int, filename: str, flags: int = 0) -> Any:
94
+ return compile("\n" * (start - 1) + src, filename, "exec", flags, dont_inherit=True)
95
+
96
+
97
+ def _future_flags(text: str) -> int:
98
+ """Compiler flags of the file's `from __future__` imports (e.g. annotations)."""
99
+ import __future__
100
+
101
+ flags = 0
102
+ for node in ast.parse(text).body:
103
+ if isinstance(node, ast.ImportFrom) and node.module == "__future__":
104
+ for alias in node.names:
105
+ flags |= getattr(__future__, alias.name).compiler_flag
106
+ return flags
107
+
108
+
109
+ _MANGLED = re.compile(r"\.__\w*[^_\W]\b")
110
+
111
+
112
+ def transplant(mod: ModuleType, entry: dict, feature: str) -> None:
113
+ """Check the installed module against the PR base, then install the PR symbols."""
114
+ done = mod.__dict__.setdefault("_vllm_knapsack_transplanted", set())
115
+ if feature in done:
116
+ return
117
+ installed = symbol_sources(Path(mod.__file__).read_text())
118
+ moved = [
119
+ name
120
+ for name, base_hash in entry["symbols"].items()
121
+ if (installed[name][1] if name in installed else None) != base_hash
122
+ ]
123
+ if moved:
124
+ raise HookPointMissing(
125
+ f"vllm-knapsack-weight-replication ({feature}): {mod.__name__} "
126
+ f"differs from the pull request base in {', '.join(moved)}; this vLLM "
127
+ "version is not supported (see README, Compatibility). Nothing was patched."
128
+ )
129
+ pr_file = _PKG / entry["file"]
130
+ pr_text = pr_file.read_text()
131
+ pr = symbol_sources(pr_text)
132
+ filename = str(pr_file)
133
+ flags = _future_flags(pr_text)
134
+ for src, start in _imports(pr_text):
135
+ if "__future__" not in src:
136
+ exec(_compile(src, start, filename), mod.__dict__)
137
+ for name in pr: # file order: helpers before the methods that use them
138
+ if name not in entry["symbols"]:
139
+ continue
140
+ src, _, start = pr[name]
141
+ owner, _, attr = name.rpartition(".")
142
+ scope: dict[str, Any] = {}
143
+ if owner:
144
+ if _MANGLED.search(src):
145
+ raise HookPointMissing(f"{name}: private (mangled) names unsupported")
146
+ src = re.sub(r"\bsuper\(\)", f"super({owner}, self)", src)
147
+ exec(_compile(src, start, filename, flags), mod.__dict__, scope)
148
+ value = scope[attr]
149
+ if hasattr(value, "__qualname__") and callable(value):
150
+ value.__qualname__ = name
151
+ setattr(getattr(mod, owner), attr, value)
152
+ else:
153
+ exec(_compile(src, start, filename, flags), mod.__dict__)
154
+ done.add(feature)
155
+
156
+
157
+ class _Finder:
158
+ """Post-import hooks and modules served from the package, on sys.meta_path."""
159
+
160
+ def __init__(self) -> None:
161
+ self.after: dict[str, list[Callable[[ModuleType], None]]] = {}
162
+ self.serve: dict[str, Path] = {}
163
+
164
+ def find_spec(self, fullname, path=None, target=None):
165
+ if fullname in self.serve:
166
+ return importlib.util.spec_from_file_location(
167
+ fullname, self.serve[fullname]
168
+ )
169
+ if fullname not in self.after:
170
+ return None
171
+ spec = importlib.machinery.PathFinder.find_spec(fullname, path, target)
172
+ if spec is None or spec.loader is None:
173
+ return None
174
+ spec.loader = _Loader(spec.loader, self.after[fullname])
175
+ return spec
176
+
177
+
178
+ class _Loader:
179
+ def __init__(self, inner: Any, callbacks: list) -> None:
180
+ self._inner, self._callbacks = inner, callbacks
181
+
182
+ def create_module(self, spec):
183
+ return self._inner.create_module(spec)
184
+
185
+ def exec_module(self, module):
186
+ self._inner.exec_module(module)
187
+ for callback in self._callbacks:
188
+ callback(module)
189
+
190
+ def __getattr__(self, name):
191
+ return getattr(self._inner, name)
192
+
193
+
194
+ _finder = _Finder()
195
+
196
+
197
+ def _install_finder() -> None:
198
+ if _finder not in sys.meta_path:
199
+ sys.meta_path.insert(0, _finder)
200
+
201
+
202
+ def after_import(name: str, callback: Callable[[ModuleType], None]) -> None:
203
+ """Run callback(module) once `name` is imported (now, if it already is)."""
204
+ _install_finder()
205
+ _finder.after.setdefault(name, []).append(callback)
206
+ if name in sys.modules:
207
+ callback(sys.modules[name])
208
+
209
+
210
+ def apply_manifest(manifest: ModuleType, feature: str) -> None:
211
+ """Serve the PR's new modules and transplant its changed symbols."""
212
+ _install_finder()
213
+ for entry in manifest.ENTRIES:
214
+ if entry.get("new_module"):
215
+ path = _PKG / entry["file"]
216
+ _finder.serve[entry["module"]] = path
217
+ loaded = sys.modules.get(entry["module"])
218
+ if loaded is not None and Path(loaded.__file__) != path:
219
+ raise HookPointMissing(
220
+ f"vllm-knapsack-weight-replication ({feature}): vLLM already has "
221
+ f"{entry['module']}; this vLLM version is not supported."
222
+ )
223
+ continue
224
+ after_import(entry["module"], lambda mod, e=entry: transplant(mod, e, feature))
@@ -0,0 +1,50 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ """vllm-project/vllm#66526 (VLLM_TRITON_SYNC_AUTOTUNE_TP) as patches.
4
+
5
+ The module itself is `tp_synced_autotune` (the PR's file, unchanged), exposed as
6
+ `vllm.triton_utils.tp_synced_autotune`. The PR's three edits to vLLM become:
7
+ - vllm/triton_utils/__init__.py installs it when the flag is set -> `apply()`;
8
+ - Worker.init_device calls `configure()` once the parallel layout is known;
9
+ - Mamba's `launch_autotuned` keys its config cache on `syncing()`.
10
+ """
11
+
12
+ import functools
13
+ from typing import Any
14
+
15
+ from vllm_knapsack_weight_replication import _envs, _patching, tp_synced_autotune
16
+
17
+
18
+ class _SyncAwareConfigs(dict):
19
+ """Mamba's launch cache, kept apart for synced and local launches (the PR adds
20
+ `tp_synced_autotune.syncing()` to the key)."""
21
+
22
+ def get(self, key: Any, default: Any = None) -> Any:
23
+ return super().get((tp_synced_autotune.syncing(), key), default)
24
+
25
+ def __setitem__(self, key: Any, value: Any) -> None:
26
+ super().__setitem__((tp_synced_autotune.syncing(), key), value)
27
+
28
+
29
+ def _configure_after(original):
30
+ @functools.wraps(original)
31
+ def init_device(self, *args, **kwargs):
32
+ out = original(self, *args, **kwargs)
33
+ # Cheap; also arms the sync when a model installs it itself.
34
+ tp_synced_autotune.configure(self.vllm_config.parallel_config)
35
+ return out
36
+
37
+ return init_device
38
+
39
+
40
+ def apply() -> None:
41
+ _patching.alias_module("vllm.triton_utils.tp_synced_autotune", tp_synced_autotune)
42
+ gpu_worker = _patching.require("vllm.v1.worker.gpu_worker", "Worker.init_device")
43
+ _patching.wrap_method(gpu_worker.Worker, "init_device", _configure_after)
44
+ helpers = _patching.optional("vllm.model_executor.layers.mamba.ops.triton_helpers")
45
+ if helpers is not None and not isinstance(
46
+ getattr(helpers, "_autotuned_configs", None), _SyncAwareConfigs
47
+ ):
48
+ helpers._autotuned_configs = _SyncAwareConfigs()
49
+ if _envs.get("VLLM_TRITON_SYNC_AUTOTUNE_TP"):
50
+ tp_synced_autotune.install()
@@ -0,0 +1,247 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ """Canonical form of a sparse-indexer top-k: a deterministic set in ascending order.
4
+
5
+ The radix top-k kernels (persistent, cooperative, filtered) take output slots by
6
+ `atomicAdd`, so the order of the selected indices depends on thread scheduling,
7
+ and so does the set when several scores tie with the k-th one: the kernels keep
8
+ whichever tied candidates reach the last slots first. `canonicalize_topk_` rewrites
9
+ a top-k result so that it depends only on the scores: every candidate scoring above
10
+ the k-th score, then the lowest-index candidates that tie with it, all in ascending
11
+ index order. Scores are compared by value: -0.0 ties with +0.0 and every NaN ranks
12
+ above +inf, as in `torch.topk`. A radix selection, whose key (`convert_to_uint32_v2`)
13
+ puts -0.0 below +0.0, is a valid top-k under this order too, so every backend's
14
+ result maps to the same set; only a negative NaN, last for the radix key and first
15
+ here, can leave a row's set undefined (the writes stay in bounds).
16
+
17
+ Three kernels, no host synchronization: the k-th key per row, then per-block counts
18
+ of candidates above / tied with it, then each block writes its kept candidates at
19
+ their ascending positions.
20
+ """
21
+
22
+ import torch
23
+
24
+ import vllm.envs as envs
25
+ from vllm.logger import init_logger
26
+ from vllm.triton_utils import tl, triton
27
+
28
+ logger = init_logger(__name__)
29
+
30
+ # Features (e.g. a TP replication switch) that need a canonical top-k on top of
31
+ # VLLM_DETERMINISTIC_SPARSE_TOPK / VLLM_BATCH_INVARIANT.
32
+ _required_by: set[str] = set()
33
+
34
+
35
+ def require_deterministic_sparse_topk(reason: str) -> None:
36
+ """Turn the canonical sparse-indexer top-k on for this process.
37
+
38
+ Call it while the model is built, before the first forward pass and before
39
+ the attention metadata builders are made: every site reads the flag at call
40
+ time through `deterministic_sparse_topk()`."""
41
+ if reason not in _required_by:
42
+ _required_by.add(reason)
43
+ logger.info("Canonical sparse-indexer top-k turned on by %s.", reason)
44
+
45
+
46
+ def deterministic_sparse_topk() -> bool:
47
+ """Whether the sparse indexer top-k must be canonical (see module docstring)."""
48
+ return (
49
+ envs.VLLM_DETERMINISTIC_SPARSE_TOPK
50
+ or envs.VLLM_BATCH_INVARIANT
51
+ or bool(_required_by)
52
+ )
53
+
54
+
55
+ _BLOCK = 2048
56
+ # Largest key, above any score's: marks empty slots when taking the minimum.
57
+ _EMPTY_KEY = 2**33
58
+
59
+
60
+ def _ordered_key(scores: torch.Tensor) -> torch.Tensor:
61
+ """Ordered FP32 key as int64 (larger key = larger score), see `_key`."""
62
+ bits = scores.float().view(torch.int32).to(torch.int64) & 0xFFFFFFFF
63
+ bits = torch.where(bits == 0x80000000, 0, bits)
64
+ bits = torch.where((bits & 0x7FFFFFFF) > 0x7F800000, 0x7FFFFFFF, bits)
65
+ return torch.where(bits >= 2**31, 0xFFFFFFFF - bits, bits + 2**31)
66
+
67
+
68
+ @triton.jit
69
+ def _key(x):
70
+ # Value order: -0.0 is +0.0, and any NaN is the largest NaN (above +inf).
71
+ bits = x.to(tl.float32).to(tl.int32, bitcast=True).to(tl.int64) & 0xFFFFFFFF
72
+ bits = tl.where(bits == 2147483648, 0, bits)
73
+ bits = tl.where((bits & 2147483647) > 2139095040, 2147483647, bits)
74
+ return tl.where(bits >= 2147483648, 4294967295 - bits, bits + 2147483648)
75
+
76
+
77
+ @triton.jit
78
+ def _threshold_kernel(
79
+ logits_ptr,
80
+ stride_row,
81
+ idx_ptr,
82
+ stride_idx,
83
+ thresh_ptr,
84
+ num_valid_ptr,
85
+ K: tl.constexpr,
86
+ K_POW2: tl.constexpr,
87
+ EMPTY: tl.constexpr,
88
+ ):
89
+ """Per row: the smallest key among the selected candidates, and their count."""
90
+ row = tl.program_id(0)
91
+ slots = tl.arange(0, K_POW2)
92
+ idx = tl.load(idx_ptr + row * stride_idx + slots, mask=slots < K, other=-1)
93
+ valid = idx >= 0
94
+ x = tl.load(logits_ptr + row * stride_row + idx, mask=valid, other=0.0)
95
+ key = tl.where(valid, _key(x), EMPTY)
96
+ tl.store(thresh_ptr + row, tl.min(key, 0))
97
+ tl.store(num_valid_ptr + row, tl.sum(valid.to(tl.int32), 0))
98
+
99
+
100
+ @triton.jit
101
+ def _count_kernel(
102
+ logits_ptr,
103
+ stride_row,
104
+ row_ends_ptr,
105
+ thresh_ptr,
106
+ counts_ptr,
107
+ num_blocks,
108
+ BLOCK: tl.constexpr,
109
+ ):
110
+ """Per (row, block): candidates above the threshold key and tied with it."""
111
+ row = tl.program_id(0)
112
+ blk = tl.program_id(1)
113
+ base = counts_ptr + (row * num_blocks + blk) * 2
114
+ row_end = tl.load(row_ends_ptr + row)
115
+ # The grid spans max_model_len (fixed under CUDA graphs): past the row's
116
+ # end there is nothing to read, only zero counts to leave.
117
+ if blk * BLOCK >= row_end:
118
+ tl.store(base, 0)
119
+ tl.store(base + 1, 0)
120
+ return
121
+ cols = blk * BLOCK + tl.arange(0, BLOCK)
122
+ in_row = cols < row_end
123
+ x = tl.load(logits_ptr + row * stride_row + cols, mask=in_row, other=0.0)
124
+ key = _key(x)
125
+ t = tl.load(thresh_ptr + row)
126
+ tl.store(base, tl.sum((in_row & (key > t)).to(tl.int32), 0))
127
+ tl.store(base + 1, tl.sum((in_row & (key == t)).to(tl.int32), 0))
128
+
129
+
130
+ @triton.jit
131
+ def _write_kernel(
132
+ logits_ptr,
133
+ stride_row,
134
+ row_ends_ptr,
135
+ thresh_ptr,
136
+ num_valid_ptr,
137
+ counts_ptr,
138
+ out_ptr,
139
+ stride_out,
140
+ num_blocks,
141
+ K: tl.constexpr,
142
+ K_POW2: tl.constexpr,
143
+ BLOCK: tl.constexpr,
144
+ NB_POW2: tl.constexpr,
145
+ ):
146
+ """Per (row, block): write the kept candidates at their ascending positions."""
147
+ row = tl.program_id(0)
148
+ blk = tl.program_id(1)
149
+ num_valid = tl.load(num_valid_ptr + row)
150
+ if blk == 0:
151
+ # The kept candidates fill [0, num_valid); clear the rest.
152
+ slots = tl.arange(0, K_POW2)
153
+ tl.store(
154
+ out_ptr + row * stride_out + slots,
155
+ tl.full([K_POW2], -1, tl.int32),
156
+ mask=(slots >= num_valid) & (slots < K),
157
+ )
158
+ row_end = tl.load(row_ends_ptr + row)
159
+ if blk * BLOCK >= row_end:
160
+ return
161
+ # Counts of the whole row and of the blocks before this one.
162
+ b = tl.arange(0, NB_POW2)
163
+ in_range = b < num_blocks
164
+ row_counts = counts_ptr + row * num_blocks * 2 + b * 2
165
+ above_b = tl.load(row_counts, mask=in_range, other=0)
166
+ tied_b = tl.load(row_counts + 1, mask=in_range, other=0)
167
+ need = num_valid - tl.sum(above_b, 0)
168
+ before = b < blk
169
+ above_before = tl.sum(tl.where(before, above_b, 0), 0)
170
+ tied_before = tl.sum(tl.where(before, tied_b, 0), 0)
171
+
172
+ cols = blk * BLOCK + tl.arange(0, BLOCK)
173
+ in_row = cols < row_end
174
+ x = tl.load(logits_ptr + row * stride_row + cols, mask=in_row, other=0.0)
175
+ key = _key(x)
176
+ t = tl.load(thresh_ptr + row)
177
+ above = in_row & (key > t)
178
+ tied = in_row & (key == t)
179
+ tied_i = tied.to(tl.int32)
180
+ tie_rank = tied_before + tl.cumsum(tied_i, 0) - tied_i
181
+ keep = above | (tied & (tie_rank < need))
182
+ keep_i = keep.to(tl.int32)
183
+ pos = (
184
+ above_before
185
+ + tl.minimum(tl.maximum(need, 0), tied_before)
186
+ + tl.cumsum(keep_i, 0)
187
+ - keep_i
188
+ )
189
+ # Guard the output if `indices` was not an exact top-k of `logits`.
190
+ tl.store(out_ptr + row * stride_out + pos, cols.to(tl.int32), mask=keep & (pos < K))
191
+
192
+
193
+ def canonicalize_topk_(
194
+ logits: torch.Tensor, indices: torch.Tensor, row_ends: torch.Tensor
195
+ ) -> None:
196
+ """Rewrite `indices` in place into its canonical form (see module docstring).
197
+
198
+ logits: [rows, cols] scores the top-k was taken over (fp32/bf16/fp16), with
199
+ unit column stride; row r's candidates are columns [0, row_ends[r]).
200
+ indices: [rows, k] int32 column indices selected per row, -1 for empty slots.
201
+ row_ends: [rows] int32.
202
+
203
+ Each row keeps the same number of valid entries; only which tied candidates
204
+ are kept and the order change. Assumes `indices` is an exact top-k of
205
+ `logits` (every selected score >= every unselected one).
206
+ """
207
+ rows, k = indices.shape
208
+ if rows == 0 or k == 0 or logits.shape[1] == 0:
209
+ return
210
+ assert logits.stride(1) == 1 and indices.stride(1) == 1
211
+ assert indices.dtype == torch.int32 and row_ends.dtype == torch.int32
212
+ device = logits.device
213
+ num_blocks = triton.cdiv(logits.shape[1], _BLOCK)
214
+ thresh = torch.empty(rows, dtype=torch.int64, device=device)
215
+ num_valid = torch.empty(rows, dtype=torch.int32, device=device)
216
+ counts = torch.empty(rows, num_blocks, 2, dtype=torch.int32, device=device)
217
+ k_pow2 = triton.next_power_of_2(k)
218
+ _threshold_kernel[(rows,)](
219
+ logits,
220
+ logits.stride(0),
221
+ indices,
222
+ indices.stride(0),
223
+ thresh,
224
+ num_valid,
225
+ K=k,
226
+ K_POW2=k_pow2,
227
+ EMPTY=_EMPTY_KEY,
228
+ )
229
+ grid = (rows, num_blocks)
230
+ _count_kernel[grid](
231
+ logits, logits.stride(0), row_ends, thresh, counts, num_blocks, BLOCK=_BLOCK
232
+ )
233
+ _write_kernel[grid](
234
+ logits,
235
+ logits.stride(0),
236
+ row_ends,
237
+ thresh,
238
+ num_valid,
239
+ counts,
240
+ indices,
241
+ indices.stride(0),
242
+ num_blocks,
243
+ K=k,
244
+ K_POW2=k_pow2,
245
+ BLOCK=_BLOCK,
246
+ NB_POW2=triton.next_power_of_2(num_blocks),
247
+ )