Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion integrations/vllm/ds41_row_shard/ds41_row_shard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,11 +624,36 @@ def exec_module(self, module):


class _PatchFinder(importlib.abc.MetaPathFinder):
def __init__(self):
self._resolving = threading.local()

def _find_downstream_spec(self, name, path, target):
meta_path = list(sys.meta_path)
if self in meta_path:
candidates = meta_path[meta_path.index(self) + 1:]
else:
candidates = [f for f in meta_path if f is not self and not isinstance(f, type(self))]
for finder in candidates:
find_spec = getattr(finder, "find_spec", None)
if find_spec is None:
continue
spec = find_spec(name, path, target)
if spec is not None:
return spec
return None

def find_spec(self, name, path, target=None):
patch = _PATCHES.get(name)
if patch is None:
return None
spec = importlib.machinery.PathFinder.find_spec(name, path)
active = self._resolving.__dict__.setdefault("names", set())
if name in active:
return None
active.add(name)
try:
spec = self._find_downstream_spec(name, path, target)
finally:
active.discard(name)
if spec is None or spec.loader is None:
return None
spec.loader = _PatchLoader(spec.loader, patch)
Expand Down
203 changes: 203 additions & 0 deletions integrations/vllm/ds41_row_shard/tests/test_meta_path_chaining.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
"""Regression tests verifying MetaPathFinder shims chain downstream finders instead of clobbering sys.meta_path."""
from __future__ import annotations

import hashlib
import importlib
import importlib.abc
import importlib.util
from pathlib import Path
import sys
import threading

import ds41_row_shard

ROOT = Path(__file__).resolve().parents[4]


def _make_recording_finder(target_name: str, marker: str, fired: list[str]) -> importlib.abc.MetaPathFinder:
"""A second MetaPathFinder placed downstream of the shim under test."""

class _DownstreamLoader(importlib.abc.Loader):
def __init__(self, inner):
self._inner = inner

def create_module(self, spec):
return self._inner.create_module(spec)

def exec_module(self, module):
self._inner.exec_module(module)
fired.append(marker)
setattr(module, marker, True)

class _DownstreamFinder(importlib.abc.MetaPathFinder):
def __init__(self):
self._resolving = threading.local()

def find_spec(self, fullname, path=None, target=None):
if fullname != target_name:
return None
active = self._resolving.__dict__.setdefault("names", set())
if fullname in active:
return None
active.add(fullname)
try:
meta = list(sys.meta_path)
start = meta.index(self) + 1 if self in meta else 0
for finder in meta[start:]:
fn = getattr(finder, "find_spec", None)
if fn is None:
continue
spec = fn(fullname, path, target)
if spec is not None:
spec.loader = _DownstreamLoader(spec.loader)
return spec
finally:
active.discard(fullname)
return None

return _DownstreamFinder()


def _write_temp_module(root: Path, dotted_name: str, body: str) -> Path:
parts = dotted_name.split(".")
current = root
for pkg in parts[:-1]:
current = current / pkg
current.mkdir(parents=True, exist_ok=True)
init = current / "__init__.py"
if not init.exists():
init.write_text("", encoding="utf-8")
mod_file = current / f"{parts[-1]}.py"
mod_file.write_text(body, encoding="utf-8")
return mod_file


def test_ds41_row_shard_patch_finder_chains_with_downstream_meta_path_finder(tmp_path, monkeypatch):
target_name = "_sr_chain_ds41_pkg.target_mod"
_write_temp_module(tmp_path, target_name, "VALUE = 1\n")
fired: list[str] = []

def ds41_patch(module):
fired.append("ds41")
module.DS41_PATCHED = True

monkeypatch.syspath_prepend(str(tmp_path))
monkeypatch.setitem(ds41_row_shard._PATCHES, target_name, ds41_patch)
downstream = _make_recording_finder(target_name, "downstream", fired)
upstream = ds41_row_shard._PatchFinder()
monkeypatch.setattr(sys, "meta_path", [upstream, downstream, *sys.meta_path])
for name in ("_sr_chain_ds41_pkg", target_name):
sys.modules.pop(name, None)
try:
mod = importlib.import_module(target_name)
assert mod.VALUE == 1
assert getattr(mod, "downstream", False) is True
assert getattr(mod, "DS41_PATCHED", False) is True
assert fired == ["downstream", "ds41"]
finally:
for name in ("_sr_chain_ds41_pkg", target_name):
sys.modules.pop(name, None)


def test_qwen4_collectives_finder_chains_with_downstream_meta_path_finder(tmp_path, monkeypatch):
target_name = "_sr_chain_qwen4_coll_pkg.adapter_mod"
mod_file = _write_temp_module(tmp_path, target_name, "MARKER = 'orig'\n")
digest = hashlib.sha256(mod_file.read_bytes()).hexdigest()
fired: list[str] = []

monkeypatch.setenv("QWEN_DISPATCH_MODE", "both")
monkeypatch.setenv("QWEN_DISPATCH_AR_BYTES", "1024")
monkeypatch.setenv("QWEN_DISPATCH_TRACE", "0")
original_meta = list(sys.meta_path)
policy_path = ROOT / "integrations/vllm/qwen4_collectives/qwen38_collective_policy.py"
spec = importlib.util.spec_from_file_location("_qwen4_coll_chain_under_test", policy_path)
policy = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(policy)
# Remove the auto-inserted finder and test an explicit stacked pair [policy.Finder, downstream].
sys.meta_path[:] = original_meta
monkeypatch.setitem(policy.PATCHES, target_name, lambda mod: (fired.append("qwen4_coll"), setattr(mod, "QWEN_COLL", True)))
monkeypatch.setitem(policy.SOURCE_HASHES, target_name, digest)
monkeypatch.syspath_prepend(str(tmp_path))
downstream = _make_recording_finder(target_name, "downstream", fired)
upstream = policy.Finder()
monkeypatch.setattr(sys, "meta_path", [upstream, downstream, *original_meta])
for name in ("_sr_chain_qwen4_coll_pkg", target_name):
sys.modules.pop(name, None)
mod = importlib.import_module(target_name)
assert mod.MARKER == "orig"
assert getattr(mod, "downstream", False) is True
assert getattr(mod, "QWEN_COLL", False) is True
assert fired == ["downstream", "qwen4_coll"]
finally:
sys.meta_path[:] = original_meta
for name in ("_sr_chain_qwen4_coll_pkg", target_name):
sys.modules.pop(name, None)


def test_qwen4_prefill_finders_chain_with_downstream_meta_path_finders(tmp_path, monkeypatch):
for rel_path, env_flag, env_hash, tag in (
("integrations/vllm/qwen4_prefill/qwen4_hc_fusion.py", "QWEN_HC_FUSION", "QWEN_HC_SOURCE_SHA256", "hc"),
("integrations/vllm/qwen4_prefill/qwen4_mtp_gemm.py", "QWEN_MTP_TORCH_PREFILL", "QWEN_MTP_SOURCE_SHA256", "mtp"),
):
target_name = f"_sr_chain_qwen4_{tag}_pkg.target_mod"
mod_file = _write_temp_module(tmp_path, target_name, f"TAG = {tag!r}\n")
digest = hashlib.sha256(mod_file.read_bytes()).hexdigest()
fired: list[str] = []

monkeypatch.setenv(env_flag, "1")
monkeypatch.setenv(env_hash, digest)
original_meta = list(sys.meta_path)
mod_path = ROOT / rel_path
spec = importlib.util.spec_from_file_location(f"_qwen4_{tag}_chain_under_test", mod_path)
shim = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(shim)
sys.meta_path[:] = original_meta
monkeypatch.setattr(shim, "TARGET", target_name)
monkeypatch.setattr(shim, "EXPECTED", digest)
monkeypatch.setattr(shim, "patch", lambda mod, _t=tag: (fired.append(_t), setattr(mod, f"PATCHED_{_t}", True)))
monkeypatch.syspath_prepend(str(tmp_path))
downstream = _make_recording_finder(target_name, "downstream", fired)
upstream = shim.Finder()
monkeypatch.setattr(sys, "meta_path", [upstream, downstream, *original_meta])
for name in (f"_sr_chain_qwen4_{tag}_pkg", target_name):
sys.modules.pop(name, None)
mod = importlib.import_module(target_name)
assert mod.TAG == tag
assert getattr(mod, "downstream", False) is True
assert getattr(mod, f"PATCHED_{tag}", False) is True
assert fired == ["downstream", tag]
finally:
sys.meta_path[:] = original_meta
for name in (f"_sr_chain_qwen4_{tag}_pkg", target_name):
sys.modules.pop(name, None)


def test_glm_patch_on_import_finders_chain_without_clobbering_or_reentering(tmp_path, monkeypatch):
from integrations.vllm.glm53full_speedups import glm53full_speedups
from integrations.vllm.glm_dcp_decode_comm import glm_dcp_decode_comm
from integrations.vllm.glm_dsa_indexer_split import glm_dsa_indexer_split

target_name = "_sr_chain_glm_pkg.attention_mod"
_write_temp_module(tmp_path, target_name, "VALUE = 42\n")
fired: list[str] = []

f1 = glm53full_speedups.PatchOnImport({target_name: lambda m: (fired.append("speedups"), setattr(m, "F1", True))})
f2 = glm_dcp_decode_comm.PatchOnImport({target_name: lambda m: (fired.append("dcp"), setattr(m, "F2", True))})
f3 = glm_dsa_indexer_split.PatchOnImport({target_name: lambda m: (fired.append("indexer"), setattr(m, "F3", True))})
monkeypatch.syspath_prepend(str(tmp_path))
monkeypatch.setattr(sys, "meta_path", [f1, f2, f3, *sys.meta_path])
for name in ("_sr_chain_glm_pkg", target_name):
sys.modules.pop(name, None)
try:
mod = importlib.import_module(target_name)
assert mod.VALUE == 42
assert getattr(mod, "F1", False) is True
assert getattr(mod, "F2", False) is True
assert getattr(mod, "F3", False) is True
assert fired == ["indexer", "dcp", "speedups"]
finally:
for name in ("_sr_chain_glm_pkg", target_name):
sys.modules.pop(name, None)

Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,9 @@ def find_spec(self, fullname, path=None, target=None):
active.add(fullname)
try:
spec = None
for finder in list(sys.meta_path):
meta_path = list(sys.meta_path)
start = meta_path.index(self) + 1 if self in meta_path else 0
for finder in meta_path[start:]:
find_spec = getattr(finder, "find_spec", None)
if finder is self or find_spec is None:
continue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,9 @@ def find_spec(self, fullname, path=None, target=None):
active.add(fullname)
try:
spec = None
for finder in list(sys.meta_path):
meta_path = list(sys.meta_path)
start = meta_path.index(self) + 1 if self in meta_path else 0
for finder in meta_path[start:]:
find_spec = getattr(finder, "find_spec", None)
if finder is self or find_spec is None:
continue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,9 @@ def find_spec(self, fullname, path=None, target=None):
active.add(fullname)
try:
spec = None
for finder in list(sys.meta_path):
meta_path = list(sys.meta_path)
start = meta_path.index(self) + 1 if self in meta_path else 0
for finder in meta_path[start:]:
find_spec = getattr(finder, "find_spec", None)
if finder is self or find_spec is None:
continue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import json
import os
import sys
import threading
from pathlib import Path

MODE = os.environ.get("QWEN_DISPATCH_MODE")
Expand Down Expand Up @@ -153,10 +154,35 @@ def exec_module(self, module):


class Finder(importlib.abc.MetaPathFinder):
def __init__(self):
self._resolving = threading.local()

def _find_downstream_spec(self, fullname, path, target):
meta_path = list(sys.meta_path)
if self in meta_path:
candidates = meta_path[meta_path.index(self) + 1:]
else:
candidates = [f for f in meta_path if f is not self and not isinstance(f, type(self))]
for finder in candidates:
find_spec = getattr(finder, "find_spec", None)
if find_spec is None:
continue
spec = find_spec(fullname, path, target)
if spec is not None:
return spec
return None

def find_spec(self, fullname, path=None, target=None):
if fullname not in PATCHES:
return None
spec = importlib.machinery.PathFinder.find_spec(fullname, path)
active = self._resolving.__dict__.setdefault("names", set())
if fullname in active:
return None
active.add(fullname)
try:
spec = self._find_downstream_spec(fullname, path, target)
finally:
active.discard(fullname)
if spec is None or spec.loader is None:
raise SystemExit("Required Qwen dispatch module is missing: " + fullname)
if (
Expand Down
28 changes: 27 additions & 1 deletion integrations/vllm/qwen4_prefill/qwen4_hc_fusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import json
import os
import sys
import threading
from pathlib import Path

TARGET = "vllm.models.qwen4_exp.nvidia.hyperconnection"
Expand Down Expand Up @@ -184,10 +185,35 @@ def exec_module(self, module):


class Finder(importlib.abc.MetaPathFinder):
def __init__(self):
self._resolving = threading.local()

def _find_downstream_spec(self, fullname, path, target):
meta_path = list(sys.meta_path)
if self in meta_path:
candidates = meta_path[meta_path.index(self) + 1:]
else:
candidates = [f for f in meta_path if f is not self and not isinstance(f, type(self))]
for finder in candidates:
find_spec = getattr(finder, "find_spec", None)
if find_spec is None:
continue
spec = find_spec(fullname, path, target)
if spec is not None:
return spec
return None

def find_spec(self, fullname, path=None, target=None):
if fullname != TARGET:
return None
spec = importlib.machinery.PathFinder.find_spec(fullname, path)
active = self._resolving.__dict__.setdefault("names", set())
if fullname in active:
return None
active.add(fullname)
try:
spec = self._find_downstream_spec(fullname, path, target)
finally:
active.discard(fullname)
if (
spec is None
or spec.loader is None
Expand Down
Loading
Loading