diff --git a/src/tensorfold/cuda/comm.py b/src/tensorfold/cuda/comm.py index 9e9b16a1d6e..bc322252d13 100644 --- a/src/tensorfold/cuda/comm.py +++ b/src/tensorfold/cuda/comm.py @@ -72,6 +72,8 @@ def __init__(self, rank: int, world: int, master: str, port: int, *, timeout_s: ctypes.c_void_p] lib.ncclAllReduce.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] + lib.ncclReduceScatter.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, + ctypes.c_void_p, ctypes.c_void_p] self.store = TCPStore(master, port, world, rank == 0, timeout=timedelta(seconds=timeout_s)) uid = _UniqueId() if rank == 0: @@ -108,6 +110,15 @@ def all_reduce(self, value: torch.Tensor) -> None: self._check(self.lib.ncclAllReduce(value.data_ptr(), value.data_ptr(), value.numel(), _DTYPES[value.dtype], NCCL_SUM, self.comm, stream)) + def reduce_scatter(self, send: torch.Tensor, recv: torch.Tensor) -> None: + """recv [n] <- ncclSum over the ranks of their send's rank-th block (send [world * n]).""" + + if send.numel() != recv.numel() * self.world or send.dtype != recv.dtype: + raise ValueError("reduce_scatter: send must hold world x recv of the same dtype") + stream = torch.cuda.current_stream().cuda_stream + self._check(self.lib.ncclReduceScatter(send.data_ptr(), recv.data_ptr(), recv.numel(), _DTYPES[send.dtype], + NCCL_SUM, self.comm, stream)) + def ready(self, label: str, *, every: float = 60.0, timeout: float = 3600.0) -> None: """Every rank finishes ``label`` before any goes on; a rank missing after ``timeout`` s is named.""" diff --git a/src/tensorfold/families/deepseek_v41/cuda/engine.py b/src/tensorfold/families/deepseek_v41/cuda/engine.py index eaf124eb75a..17dd004bbba 100644 --- a/src/tensorfold/families/deepseek_v41/cuda/engine.py +++ b/src/tensorfold/families/deepseek_v41/cuda/engine.py @@ -72,7 +72,7 @@ def __init__(self, model_dir: Path, *, rank: int, world: int, master: str, port: from ..ops import compressed_token_map from .dspark import Drafter - from .model import Comm, Engram, Model + from .model import RS, Comm, Engram, Model from .weights import load torch.cuda.set_device(0) @@ -159,14 +159,14 @@ def __init__(self, model_dir: Path, *, rank: int, world: int, master: str, port: if nccl is not None: from . import markov - nccl.barrier() # the Markov switches set the drafter's gathers (count, size) - mine = torch.tensor([int(self.vcfg is not None), int(parallel), int(markov.ON), int(markov.SPLIT)], + nccl.barrier() # These settings choose collectives before warm-up. + mine = torch.tensor([int(self.vcfg is not None), int(parallel), int(markov.ON), int(markov.SPLIT), int(RS)], dtype=torch.int64, device="cuda") - every = torch.empty((world * 4,), dtype=torch.int64, device="cuda") + every = torch.empty((world * mine.numel(),), dtype=torch.int64, device="cuda") nccl.all_gather(mine, every) - flags = every.view(world, 4).tolist() + flags = every.view(world, mine.numel()).tolist() if any(f != flags[0] for f in flags): - raise ValueError("--vision, --parallel, TF_DS_MARKOV and TF_DS_MARKOV_SPLIT must be the same on every " + raise ValueError("--vision, --parallel, TF_DS_MARKOV, TF_DS_MARKOV_SPLIT and TF_DS_RS must match on every " f"rank (rank 0 and the workers run the same steps): {flags}") if WARM: self.warm() diff --git a/src/tensorfold/families/deepseek_v41/cuda/model.py b/src/tensorfold/families/deepseek_v41/cuda/model.py index c33ee49303c..df2cc88fe3f 100644 --- a/src/tensorfold/families/deepseek_v41/cuda/model.py +++ b/src/tensorfold/families/deepseek_v41/cuda/model.py @@ -21,6 +21,9 @@ RAW = 64 # per-position compressor inputs kept (a verify window rolls back by length alone) RING_EXTRA = 16 # window ring slots beyond the 128-token window (verify windows never clobber) KV_QUANT = os.environ.get("TF_DS_KV", "native") != "bf16" +# TF_DS_RS=1 (two ranks): a prompt chunk's attention and MoE partials reach the mHC post as bf16(p0 + p1), from an +# fp32 reduce-scatter and a bf16 all-gather (Comm.reduced). The same bits as the fp32 gather, 3/4 of its bytes. +RS = os.environ.get("TF_DS_RS", "0") == "1" KERNELS = os.environ.get("TF_DS_KERNELS", "1") != "0" # 0: the plain-torch phase-1 path (A/B and debugging) TIMING = os.environ.get("TF_DS_TIMING", "0") == "1" # per-section wall times (synchronizing; profiling only) # TF_DS_REPLAY_FLOOR=1: a prompt chunk of RING_EXTRA rows or fewer whose window reaches below the bounded replay's cut @@ -115,6 +118,21 @@ def gather(self, x: torch.Tensor) -> torch.Tensor: self.nccl.all_gather(x.view(-1), out.view(-1)) return out + def reduced(self, x: torch.Tensor) -> torch.Tensor: + """The partials [n, d] the mHC post takes: ``gather(x)`` [world, n, d], or TF_DS_RS on two ranks [1, n, d] + bf16 = bf16(p0 + p1) from an fp32 reduce-scatter and a bf16 all-gather (one fp32 add of two operands, the same + bits in either order: the same y from 3/4 of the bytes).""" + + rdma = getattr(self.nccl, "rdma", None) + if not (RS and self.world == 2 and x.shape[0] % 2 == 0 and x.dtype == F32) or (rdma and rdma.fits(x)): + return self.gather(x) + x = x.contiguous() + half = torch.empty((x.shape[0] // 2, *x.shape[1:]), dtype=F32, device=x.device) + self.nccl.reduce_scatter(x.view(-1), half.view(-1)) + y = torch.empty((1, *x.shape), dtype=BF16, device=x.device) + self.nccl.all_gather(half.to(BF16).view(-1), y.view(-1)) + return y + def sum(self, x: torch.Tensor) -> torch.Tensor: """Sum rank partials; NCCL can modify x, so callers must treat x as consumed.""" @@ -1377,7 +1395,7 @@ def _forward_k(self, sc, ids, start, all_logits, taps, h, pre, hashes, shared, r pa = self.attention_k(lay, x, sc, start, shared, pos, floor=floor, kv_done=kv_done and lay.idx == c.n_layers // 2) with _T("gather"): - g = self.comm.gather(pa) + g = self.comm.reduced(pa) with _T("hc"): fn, scale, base = lay.hc_ffn if hc_pf: @@ -1394,7 +1412,7 @@ def _forward_k(self, sc, ids, start, all_logits, taps, h, pre, hashes, shared, r with _T("moe"): pm = self.moe(lay, x, img=img) with _T("gather"): - g = self.comm.gather(pm) + g = self.comm.reduced(pm) with _T("hc"): K.hc_post(g, h, post, comb, h) pre, pre_f = pre_f, pre diff --git a/tests/test_dsv41_reduced.py b/tests/test_dsv41_reduced.py new file mode 100644 index 00000000000..ce712d8907e --- /dev/null +++ b/tests/test_dsv41_reduced.py @@ -0,0 +1,101 @@ +"""Comm.reduced (TF_DS_RS): two ranks get bf16(p0 + p1), the y the mHC post kernels form from the fp32 gather, and +the gather itself where the reduce-scatter does not apply.""" + +from __future__ import annotations + +import threading + +import pytest + +torch = pytest.importorskip("torch") +pytest.importorskip("triton") + +from tensorfold.families.deepseek_v41.cuda import model as M + + +class Link: + """Two ranks' collectives on the host: each call waits for both ranks' buffers, as NCCL does.""" + + def __init__(self): + self.barrier, self.sends, self.calls = threading.Barrier(2), [None, None], [] + + def swap(self, rank, send): + self.sends[rank] = send.clone() + self.barrier.wait() + both = list(self.sends) + self.barrier.wait() + return both + + +class Rank: + def __init__(self, link, rank, rdma=None): + self.link, self.rank, self.world = link, rank, 2 + if rdma is not None: + self.rdma = rdma + + def reduce_scatter(self, send, recv): + a, b = self.link.swap(self.rank, send) + self.link.calls.append(("reduce_scatter", self.rank)) + recv.copy_((a + b).view(2, -1)[self.rank]) # ncclSum of two operands + + def all_gather(self, send, recv): + a, b = self.link.swap(self.rank, send) + self.link.calls.append(("all_gather", send.dtype)) + recv.copy_(torch.cat([a, b])) + + +class Fits: + def fits(self, x): + return True + + +def both_ranks(p0, p1, rdma=None): + """Comm.reduced on two threads, one a rank: (rank 0's result, rank 1's result, the calls).""" + + link, out = Link(), [None, None] + + def run(rank, mine): + c = M.Comm.__new__(M.Comm) + c.nccl, c.world, c._buf = Rank(link, rank, rdma), 2, {} + out[rank] = c.reduced(mine) + + ts = [threading.Thread(target=run, args=(r, p)) for r, p in ((0, p0), (1, p1))] + for t in ts: + t.start() + for t in ts: + t.join() + return out[0], out[1], link.calls + + +def parts(n=8, d=64, seed=0): + g = torch.Generator().manual_seed(seed) + return torch.randn((n, d), generator=g) * 3, torch.randn((n, d), generator=g) * 1e-3 + + +def test_both_ranks_get_the_posts_y(monkeypatch): + monkeypatch.setattr(M, "RS", True) + p0, p1 = parts() + y0, y1, calls = both_ranks(p0, p1) + want = (p0 + p1).to(torch.bfloat16)[None] # what _hc_post forms from the gather, before the mix + for y in (y0, y1): + assert y.dtype == torch.bfloat16 and torch.equal(y.view(torch.int16), want.view(torch.int16)) + assert sorted(c[0] for c in calls) == ["all_gather", "all_gather", "reduce_scatter", "reduce_scatter"] + assert all(c[1] == torch.bfloat16 for c in calls if c[0] == "all_gather") + + +@pytest.mark.parametrize("case", ["off", "odd rows", "rdma holds it"]) +def test_falls_back_to_the_gather(monkeypatch, case): + monkeypatch.setattr(M, "RS", case != "off") + p0, p1 = parts(n=7 if case == "odd rows" else 8) + y0, y1, calls = both_ranks(p0, p1, Fits() if case == "rdma holds it" else None) + for y in (y0, y1): + assert y.dtype == torch.float32 and torch.equal(y, torch.stack([p0, p1])) + assert [c[0] for c in calls] == ["all_gather", "all_gather"] + + +def test_one_rank_is_the_gather(monkeypatch): + monkeypatch.setattr(M, "RS", True) + c = M.Comm.__new__(M.Comm) + c.nccl, c.world, c._buf = None, 1, {} + p0, _ = parts() + assert torch.equal(c.reduced(p0), p0[None]) diff --git a/tests/test_dsv41_reduced_cpu.py b/tests/test_dsv41_reduced_cpu.py new file mode 100644 index 00000000000..9e051b8587b --- /dev/null +++ b/tests/test_dsv41_reduced_cpu.py @@ -0,0 +1,232 @@ +"""Check the exact communicator source with CPU collectives and no Triton import.""" +from __future__ import annotations + +import ast +import os +import sys +import threading +from pathlib import Path +from types import ModuleType, SimpleNamespace + +import pytest + +torch = pytest.importorskip("torch") + +from tensorfold.cuda.comm import NCCL, NCCL_SUM, _DTYPES +from tensorfold.cuda.rdma import Hybrid, RdmaGather + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture +def model_comm(): + source = ROOT / "src/tensorfold/families/deepseek_v41/cuda/model.py" + tree = ast.parse(source.read_text()) + node = next(item for item in tree.body if isinstance(item, ast.ClassDef) and item.name == "Comm") + module = ModuleType("reduced_cpu_contract") + module.__dict__.update(torch=torch, F32=torch.float32, BF16=torch.bfloat16, RS=True, os=os) + exec(compile(ast.Module(body=[node], type_ignores=[]), str(source), "exec"), module.__dict__) + return module + + +class Link: + def __init__(self): + self.barrier = threading.Barrier(2, timeout=3) + self.sends, self.calls = [None, None], [] + + def swap(self, rank, send): + self.sends[rank] = send.clone() + self.barrier.wait() + both = list(self.sends) + self.barrier.wait() + return both + + +class Rank: + def __init__(self, link, rank): + self.link, self.rank, self.world = link, rank, 2 + + def reduce_scatter(self, send, recv): + a, b = self.link.swap(self.rank, send) + self.link.calls.append(("reduce_scatter", send.dtype)) + recv.copy_((a + b).reshape(2, -1)[self.rank]) + + def all_gather(self, send, recv): + a, b = self.link.swap(self.rank, send) + self.link.calls.append(("all_gather", send.dtype)) + recv.copy_(torch.cat([a, b])) + + +class SmallRdma: + fits = RdmaGather.fits + + def __init__(self, nccl, max_bytes): + self.nccl, self.max_bytes = nccl, max_bytes + + def all_gather(self, send, recv): + self.nccl.link.calls.append(("rdma", send.dtype)) + self.nccl.all_gather(send, recv) + + +def both_ranks(module, p0, p1, rdma_bytes=None): + link, outputs, errors = Link(), [None, None], [] + + def run(rank, partial): + try: + comm = module.Comm.__new__(module.Comm) + nccl = Rank(link, rank) + comm.nccl = nccl if rdma_bytes is None else Hybrid(nccl, SmallRdma(nccl, rdma_bytes)) + comm.world, comm._buf = 2, {} + outputs[rank] = comm.reduced(partial) + except BaseException as error: + errors.append(error) + link.barrier.abort() + + threads = [threading.Thread(target=run, args=pair, daemon=True) for pair in ((0, p0), (1, p1))] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=5) + assert not any(thread.is_alive() for thread in threads) + if errors: + raise errors[0] + return outputs, link.calls + + +@pytest.mark.parametrize("strided", [False, True]) +def test_reduced_partials_keep_exact_bf16_bits(model_comm, strided): + generator = torch.Generator().manual_seed(41) + parts = [torch.randn((8, 128), generator=generator) for _ in range(2)] + if strided: + parts = [part[:, ::2] for part in parts] + assert not parts[0].is_contiguous() + outputs, calls = both_ranks(model_comm, *parts) + expected = (parts[0] + parts[1]).to(torch.bfloat16)[None] + for output in outputs: + assert torch.equal(output.view(torch.int16), expected.view(torch.int16)) + assert sorted(name for name, dtype in calls) == ["all_gather", "all_gather", "reduce_scatter", "reduce_scatter"] + assert all(dtype == torch.bfloat16 for name, dtype in calls if name == "all_gather") + + +def test_rounding_boundaries_cancellation_and_large_values(model_comm): + values = torch.tensor([0.0, -0.0, 2**-126, -2**-126, 1.00390625, 1.00390625 + 2**-23, + 2**100, -2**100, 3.4e38, -3.4e38], dtype=torch.float32) + p0 = values.repeat(4).reshape(4, 10) + p1 = values.flip(0).repeat(4).reshape(4, 10) + outputs, _ = both_ranks(model_comm, p0, p1) + expected = (p0 + p1).to(torch.bfloat16)[None] + assert all(torch.equal(output.view(torch.int16), expected.view(torch.int16)) for output in outputs) + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float64]) +def test_other_dtypes_use_the_unchanged_gather(model_comm, dtype): + p0 = torch.arange(32, dtype=dtype).reshape(4, 8) + p1 = p0 + 1 + outputs, calls = both_ranks(model_comm, p0, p1) + assert all(torch.equal(output, torch.stack([p0, p1])) for output in outputs) + assert [name for name, dtype in calls] == ["all_gather", "all_gather"] + + +@pytest.mark.parametrize("rows,enabled", [(7, True), (8, False)]) +def test_odd_rows_and_disabled_mode_use_the_gather(model_comm, rows, enabled): + model_comm.RS = enabled + p0 = torch.arange(rows * 8, dtype=torch.float32).reshape(rows, 8) + p1 = p0 + 1 + outputs, calls = both_ranks(model_comm, p0, p1) + assert all(torch.equal(output, torch.stack([p0, p1])) for output in outputs) + assert [name for name, dtype in calls] == ["all_gather", "all_gather"] + + +@pytest.mark.parametrize("rdma_bytes,expected_path", [(64, "reduce_scatter"), (4096, "rdma")]) +def test_real_hybrid_dispatch_respects_the_rdma_dtype_gate(model_comm, rdma_bytes, expected_path): + p0 = torch.arange(64, dtype=torch.float32).reshape(8, 8) + p1 = -p0 + 1 + outputs, calls = both_ranks(model_comm, p0, p1, rdma_bytes) + if expected_path == "rdma": + assert all(torch.equal(output, torch.stack([p0, p1])) for output in outputs) + assert ("rdma", torch.float32) in calls + assert not any(name == "reduce_scatter" for name, dtype in calls) + else: + expected = (p0 + p1).to(torch.bfloat16)[None] + assert all(torch.equal(output.view(torch.int16), expected.view(torch.int16)) for output in outputs) + assert not any(name == "rdma" for name, dtype in calls) + + +@pytest.mark.parametrize("world", [1, 3]) +def test_other_world_sizes_keep_gather_layout(model_comm, world): + partial = torch.arange(32, dtype=torch.float32).reshape(4, 8) + comm = model_comm.Comm.__new__(model_comm.Comm) + comm.world, comm._buf = world, {} + + def gather(send, recv): + recv.copy_(torch.cat([send + rank for rank in range(world)])) + + comm.nccl = SimpleNamespace(all_gather=gather) + assert torch.equal(comm.reduced(partial), torch.stack([partial + rank for rank in range(world)])) + + +def test_nccl_wrapper_uses_receive_count_and_current_stream(monkeypatch): + calls = [] + comm = NCCL.__new__(NCCL) + comm.world, comm.comm = 2, object() + comm.lib = SimpleNamespace(ncclReduceScatter=lambda *args: calls.append(args) or 0) + monkeypatch.setattr(torch.cuda, "current_stream", lambda: SimpleNamespace(cuda_stream=123)) + send, receive = torch.arange(12, dtype=torch.float32), torch.empty(6, dtype=torch.float32) + comm.reduce_scatter(send, receive) + assert calls == [(send.data_ptr(), receive.data_ptr(), 6, _DTYPES[torch.float32], NCCL_SUM, comm.comm, 123)] + + +@pytest.mark.parametrize("receive", [torch.empty(5), torch.empty(6, dtype=torch.bfloat16)]) +def test_nccl_wrapper_rejects_bad_count_or_dtype_before_launch(receive): + comm = NCCL.__new__(NCCL) + comm.world = 2 + with pytest.raises(ValueError, match="send must hold world"): + comm.reduce_scatter(torch.arange(12, dtype=torch.float32), receive) + + +@pytest.mark.parametrize("switches", [(False, False), (True, True), (False, True)]) +def test_startup_agrees_reducer_mode_before_warmup(monkeypatch, switches): + source = ROOT / "src/tensorfold/families/deepseek_v41/cuda/engine.py" + tree = ast.parse(source.read_text()) + engine = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "DsEngine") + init = next(node for node in engine.body if isinstance(node, ast.FunctionDef) and node.name == "__init__") + packet = next(node for node in init.body if isinstance(node, ast.If) + and ast.unparse(node.test) == "nccl is not None") + warm = next(node for node in init.body if isinstance(node, ast.If) and ast.unparse(node.test) == "WARM") + assert init.body.index(packet) < init.body.index(warm) + wrapper = ast.parse("def agree(self, nccl, parallel, world):\n pass\n") + wrapper.body[0].body = [packet] + markov = ModuleType("tensorfold.families.deepseek_v41.cuda.markov") + markov.ON, markov.SPLIT = True, True + monkeypatch.setitem(sys.modules, markov.__name__, markov) + cpu_torch = SimpleNamespace(int64=torch.int64, + tensor=lambda values, **kwargs: torch.tensor(values, dtype=kwargs["dtype"]), + empty=lambda shape, **kwargs: torch.empty(shape, dtype=kwargs["dtype"])) + link, errors, warmed = Link(), [], [] + + class Flags(Rank): + def barrier(self): + self.link.barrier.wait() + + def start(rank): + namespace = {"__package__": "tensorfold.families.deepseek_v41.cuda", "torch": cpu_torch, + "RS": switches[rank]} + try: + exec(compile(wrapper, str(source), "exec"), namespace) + namespace["agree"](SimpleNamespace(vcfg=None), Flags(link, rank), 4, 2) + warmed.append(rank) + except BaseException as error: + errors.append(error) + link.barrier.abort() + + threads = [threading.Thread(target=start, args=(rank,), daemon=True) for rank in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=5) + assert not any(thread.is_alive() for thread in threads) + if switches[0] == switches[1]: + assert errors == [] and sorted(warmed) == [0, 1] + else: + assert warmed == [] and len(errors) == 2 + assert all(isinstance(error, ValueError) and "TF_DS_RS" in str(error) for error in errors) diff --git a/tests/test_dsv41_tool_comm_cpu.py b/tests/test_dsv41_tool_comm_cpu.py new file mode 100644 index 00000000000..349b875c76e --- /dev/null +++ b/tests/test_dsv41_tool_comm_cpu.py @@ -0,0 +1,102 @@ +"""Tool communicators keep gather layout in the model's CPU-dispatched prefill.""" +from __future__ import annotations + +import ast +from contextlib import nullcontext +import importlib.util +from pathlib import Path +from types import SimpleNamespace + +import pytest + +torch = pytest.importorskip("torch") + +from test_dsv41_reduced_cpu import model_comm # noqa: F401 + +ROOT = Path(__file__).resolve().parents[1] + + +def source_class(path, name): + return next(node for node in ast.walk(ast.parse(path.read_text())) + if isinstance(node, ast.ClassDef) and node.name == name) + + +@pytest.fixture(params=["small_bench", "grouped_model_check"]) +def tool_comm(request, model_comm): + path = ROOT / "tools/dsv41" / (request.param + ".py") + if request.param == "small_bench": + spec = importlib.util.spec_from_file_location("small_bench_cpu_contract", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + comm = module.FakeComm() + else: + namespace = {"M": SimpleNamespace(Comm=model_comm.Comm), "torch": torch} + node = source_class(path, "Repeat") + exec(compile(ast.Module(body=[node], type_ignores=[]), str(path), "exec"), namespace) + comm = namespace["Repeat"]() + assert comm.world == 2 and comm.nccl is None + return comm, model_comm + + +def same_bits(left, right): + assert left.shape == right.shape and left.dtype == right.dtype + assert torch.equal(left.contiguous().view(torch.uint8), right.contiguous().view(torch.uint8)) + + +@pytest.mark.parametrize("enabled", [False, True], ids=["rs0", "rs1"]) +@pytest.mark.parametrize("dtype,rows,strided", [(torch.float32, 4, True), (torch.bfloat16, 3, False)], + ids=["even-fp32-strided", "odd-bf16"]) +def test_tool_reduced_keeps_legacy_gather(tool_comm, monkeypatch, enabled, dtype, rows, strided): + comm, module = tool_comm + monkeypatch.setenv("TF_DS_RS", "1" if enabled else "0") + module.RS = enabled + partial = torch.arange(rows * 16, dtype=dtype).reshape(rows, 16) + partial = partial[:, ::2] if strided else partial + before = partial.clone() + same_bits(comm.reduced(partial), torch.stack([partial, partial])) + same_bits(partial, before) + + +@pytest.mark.parametrize("enabled", [False, True], ids=["rs0", "rs1"]) +def test_actual_prefill_dispatch_accepts_tool_communicators(tool_comm, monkeypatch, enabled): + comm, module = tool_comm + monkeypatch.setenv("TF_DS_RS", "1" if enabled else "0") + module.RS = enabled + path = ROOT / "src/tensorfold/families/deepseek_v41/cuda/model.py" + model = source_class(path, "Model") + forward = next(node for node in model.body if isinstance(node, ast.FunctionDef) and node.name == "_forward_k") + partials = [torch.arange(32, dtype=torch.float32).reshape(4, 8), + -torch.arange(32, dtype=torch.float32).reshape(4, 8)] + posts = [] + kernels = SimpleNamespace(HC_BLOCKS=1, on=lambda name: False, hc_pre=lambda *args: None, + hc_post=lambda gathered, *args: posts.append(gathered.clone()), + collapse_norm=lambda h, *args: h[:, 0].float()) + namespace = {"torch": torch, "F32": torch.float32, "BF16": torch.bfloat16, "K": kernels, + "_T": lambda name: nullcontext(), "mm": lambda head, x, dtype: x.to(dtype)} + exec(compile(ast.Module(body=[forward], type_ignores=[]), str(path), "exec"), namespace) + layer = SimpleNamespace(hc_attn=(None, None, None), hc_ffn=(None, None, None), attn_norm=None, + ffn_norm=None, comp_wkv=None, idx_wq_b=None) + cfg = SimpleNamespace(dim=8, hc=1, eps=1e-6, hc_eps=1e-6, hc_iters=1) + model = SimpleNamespace(cfg=cfg, w=SimpleNamespace(layers=[layer], norm=None, head=None), comm=comm, + attention_k=lambda *args, **kwargs: partials[0], moe=lambda *args, **kwargs: partials[1]) + cache = SimpleNamespace(length=0) + output = namespace["_forward_k"](model, cache, torch.arange(4), 0, True, None, + torch.zeros((4, 1, 8), dtype=torch.bfloat16), + torch.zeros((4, 1)), None, None) + assert cache.length == 4 and output.shape == (4, 16) + assert len(posts) == 2 + for actual, partial in zip(posts, partials): + same_bits(actual, torch.stack([partial, partial])) + + +def test_small_prompt_check_uses_the_same_benchmark_loader(): + path = ROOT / "tools/dsv41/small_prompt_check.py" + tree = ast.parse(path.read_text()) + assert any(isinstance(node, ast.ImportFrom) and node.module == "small_bench" + and any(alias.name == "load_model" for alias in node.names) for node in tree.body) + assert any(isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "load_model" + for node in ast.walk(tree)) + bench = ast.parse((ROOT / "tools/dsv41/small_bench.py").read_text()) + loader = next(node for node in bench.body if isinstance(node, ast.FunctionDef) and node.name == "load_model") + assert any(isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "FakeComm" + for node in ast.walk(loader)) diff --git a/tools/dsv41/grouped_model_check.py b/tools/dsv41/grouped_model_check.py index 274e3393c29..48b48989179 100644 --- a/tools/dsv41/grouped_model_check.py +++ b/tools/dsv41/grouped_model_check.py @@ -55,6 +55,11 @@ def gather(self, x): x = x.contiguous() return torch.stack([x, x]) + def reduced(self, x): + """Keep the local gather layout; this stand-in has no NCCL reducer.""" + + return self.gather(x) + w = load(a.model, 0, 2, n_layers=a.layers, dspark=True) m = M.Model(w, Repeat()) m.rope_cap = 8192 diff --git a/tools/dsv41/small_bench.py b/tools/dsv41/small_bench.py index 84597e0774a..940834f4d5e 100644 --- a/tools/dsv41/small_bench.py +++ b/tools/dsv41/small_bench.py @@ -41,6 +41,11 @@ def sum(self, x): acc += g[1] return acc + def reduced(self, x): + """Keep the local gather layout; this stand-in has no NCCL reducer.""" + + return self.gather(x) + def load_model(model_dir, n_layers, donors, rank=0, world=2): from tensorfold.families.deepseek_v41.config import Cfg