diff --git a/tests/cpu/test_cake_mode_names.py b/tests/cpu/test_cake_mode_names.py new file mode 100644 index 00000000000..642cdee0660 --- /dev/null +++ b/tests/cpu/test_cake_mode_names.py @@ -0,0 +1,774 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright (c) 2026 by FlashInfer team +"""Self-test of the Cake mode-name checks (``tests/test_helpers/cake_mode_names.py``). + +The modules are synthetic, built here from source; the fresh-interpreter check +imports standard-library names and packages written to ``tmp_path``. No flashinfer +import, no GPU. +""" + +from __future__ import annotations + +import re +import textwrap +import types +from pathlib import Path + +import pytest + +from tests.test_helpers.cake_mode_names import ( + assert_cake_mode_module, + assert_mode_names, + assert_no_deterministic_keyword, + assert_old_names_fail, + assert_same_object_same_name, + public_names, +) + +pytestmark = pytest.mark.cpu_only + + +def _module(name: str, source: str = "", **attrs: object) -> types.ModuleType: + """A module ``name`` with ``attrs`` bound, then ``source`` run in it.""" + module = types.ModuleType(name) + vars(module).update(attrs) + exec(textwrap.dedent(source), vars(module)) + return module + + +DET_MODULE = "toy.cake_toy_det_train" +KCP_MODULE = "toy.cake_toy_nondet_train_kcp" + + +# Stands in for torch.autograd.Function, found by its module and name: its constructor +# is (*args, **kwargs), as torch's. +FUNCTION = """ +class Function: + def __init__(self, *args, **kwargs): + pass + + @classmethod + def apply(cls, *args): + return cls.forward(None, *args) + + +Function.__module__ = "torch.autograd.function" +""" + +# A det single-rank facade: constants, an autograd class, a context type, the autograd +# functional, a verb and the support query. +DET = ( + FUNCTION + + """ +ARCHES = ("sm_100a", "sm_103a") +SM_100A_TILE = 128 + + +class CakeToyDetFunction(Function): + @staticmethod + def forward(ctx, x, eps=1e-6): + return x + + @staticmethod + def backward(ctx, grad): + return grad, None + + +class CakeToyDetContext: + def __init__(self, rank, world_size): + self.rank, self.world_size = rank, world_size + + def split(self, n): + return n // self.world_size + + def options(self, **kwargs): + return kwargs + + +def cake_toy_det(x, eps=1e-6): + return CakeToyDetFunction.apply(x, eps) + + +def cake_toy_det_train_forward(x, *, workspace=None): + return x + + +def is_cake_toy_det_train_supported(device=None): + return True + + +__all__ = [ + "ARCHES", + "SM_100A_TILE", + "CakeToyDetContext", + "CakeToyDetFunction", + "cake_toy_det", + "cake_toy_det_train_forward", + "is_cake_toy_det_train_supported", +] +""" +) + +# A nondet facade with several autograd entries, one class per entry. +LM_HEAD = """ +DEFAULT_CHUNK = 4096 + + +class CakeLMHeadNondetLossFunction: + @staticmethod + def forward(ctx, hidden, weight, labels): + return hidden + + +class CakeLMHeadNondetLogprobFunction: + @staticmethod + def forward(ctx, hidden, weight, labels): + return hidden + + +def cake_lm_head_nondet_train_loss(hidden, weight, labels): + return hidden + + +def cake_lm_head_nondet_train_logprob(hidden, weight, labels): + return hidden + + +def is_cake_lm_head_nondet_train_supported(device=None): + return True + + +__all__ = [ + "DEFAULT_CHUNK", + "CakeLMHeadNondetLogprobFunction", + "CakeLMHeadNondetLossFunction", + "cake_lm_head_nondet_train_logprob", + "cake_lm_head_nondet_train_loss", + "is_cake_lm_head_nondet_train_supported", +] +""" + +# A nondet KCP facade. +KCP = """ +class CakeToyNondetKcpMultiFunction: + @staticmethod + def forward(ctx, xs, context): + return xs + + +class CakeToyNondetKcpRecomputeHandle: + pass + + +def cake_toy_nondet_kcp(x, context): + return x + + +def cake_toy_nondet_kcp_multi(xs, context): + return xs + + +def cake_toy_nondet_train_kcp_build_context(group): + return group + + +def is_cake_toy_nondet_train_kcp_supported(device=None): + return True + + +__all__ = [ + "CakeToyNondetKcpMultiFunction", + "CakeToyNondetKcpRecomputeHandle", + "cake_toy_nondet_kcp", + "cake_toy_nondet_kcp_multi", + "cake_toy_nondet_train_kcp_build_context", + "is_cake_toy_nondet_train_kcp_supported", +] +""" + +CONFORMING = { + DET_MODULE: DET, + "toy.cake_lm_head_nondet_train": LM_HEAD, + KCP_MODULE: KCP, +} + + +@pytest.mark.parametrize("name", sorted(CONFORMING)) +def test_conforming_module_passes(name: str) -> None: + module = _module(name, CONFORMING[name]) + assert public_names(module) == module.__all__ + assert_cake_mode_module(module) + + +@pytest.mark.parametrize( + "module_name, name, error", + [ + (DET_MODULE, "cake_toy_train_forward", "lacks the mode token 'det'"), + (DET_MODULE, "route_key", "lacks the mode token 'det'"), + (DET_MODULE, "cake_toy_deterministic", "lacks the mode token 'det'"), + (DET_MODULE, "CakeToyFunction", "lacks the mode part 'Det'"), + (DET_MODULE, "CakeToyDetermineFunction", "lacks the mode part 'Det'"), + (DET_MODULE, "Arches", "lacks the mode part 'Det'"), + (DET_MODULE, "cake_toy_nondet", "carries 'nondet'"), + (DET_MODULE, "CakeToyNondetFunction", "carries 'Nondet'"), + (KCP_MODULE, "cake_toy_kcp", "lacks the mode token 'nondet'"), + (KCP_MODULE, "CakeToyKcpContext", "lacks the mode part 'Nondet'"), + (KCP_MODULE, "cake_toy_det_kcp", "carries 'det'"), + (KCP_MODULE, "CakeToyDetKcpFunction", "carries 'Det'"), + ], +) +def test_name_without_the_mode_word_of_its_module_fails( + module_name: str, name: str, error: str +) -> None: + module = _module(module_name) + expected = re.escape(f"{module_name}.{name}: {error}") + with pytest.raises(AssertionError, match=expected): + assert_mode_names(module, names=[name]) + + +# CamelCase names of the target table, the mode part after an acronym (with digits +# too): each passes in its module, fails in the module of the other mode. +@pytest.mark.parametrize( + "leaf, mode, name", + [ + ("kda_{}_train_kcp", "det", "CakeKDADetKcpContext"), + ("moe_grouped_gemm_{}_train", "nondet", "CakeMoEGroupedGemmNondetFunction"), + ("rmsnorm_silu_gate_{}_train", "det", "CakeRMSNormSiLUGateDetFunction"), + ("mhc_head_{}_train", "det", "CakeMHCHeadDetFunction"), + ("gqa_{}_train", "nondet", "CakeGQANondetFunction"), + ("rmsnorm_fp8_{}_train", "det", "CakeRMSNormFP8DetFunction"), + ("gqa_hd256_{}_train", "nondet", "CakeGQAHD256NondetFunction"), + ], +) +def test_camel_case_mode_part_after_an_acronym(leaf: str, mode: str, name: str) -> None: + module_name = f"toy.cake_{leaf}" + assert_mode_names(_module(module_name.format(mode)), names=[name]) + other = module_name.format("nondet" if mode == "det" else "det") + error = f"{other}.{name}: carries {mode.capitalize()!r}, the word of the other mode" + with pytest.raises(AssertionError, match=re.escape(error)): + assert_mode_names(_module(other), names=[name]) + + +def test_all_caps_constants_are_exempt() -> None: + module = _module(DET_MODULE) + assert_mode_names(module, names=["ARCHES", "SM_100A_TILE", "WORKSPACE_BYTES", "X"]) + + +OUT_OF_ORDER = ( + "cake_toy_train_det_forward", + "toy_det_forward", + "is_toy_det_supported", + "CakeDetToyFunction", + "ToyDetFunction", +) + + +def test_mode_word_out_of_order_fails_unless_exempt() -> None: + module = _module(DET_MODULE) + with pytest.raises(AssertionError) as info: + assert_mode_names(module, names=OUT_OF_ORDER) + message = str(info.value) + assert message.startswith(f"{len(OUT_OF_ORDER)} "), message + for name in OUT_OF_ORDER: + assert f"cake_toy_det_train.{name}: does not start with" in message, name + assert_mode_names(module, names=OUT_OF_ORDER, stem=False) + assert_mode_names(module, names=OUT_OF_ORDER, stem_exceptions=OUT_OF_ORDER) + + +def test_mode_comes_from_the_module_name_or_the_argument() -> None: + other = _module("toy.helpers", '__all__ = ["cake_toy_det", "SCALE"]') + with pytest.raises(ValueError, match="pass mode"): + assert_mode_names(other) + with pytest.raises(ValueError, match="pass stem=False"): + assert_mode_names(other, "det") + assert_mode_names(other, "det", stem=False) + with pytest.raises(AssertionError, match="cake_toy_det: carries 'det'"): + assert_mode_names(other, "nondet", stem=False) + with pytest.raises(ValueError, match="a det module, not nondet"): + assert_mode_names(_module(DET_MODULE), "nondet") + + +def test_without_all_the_attributes_defined_in_the_module_are_public() -> None: + module = _module( + DET_MODULE, + """ + import json + from textwrap import dedent + + LIMIT = 3 + _private = 1 + + + def cake_toy_det(x): + return json.dumps(x) + + + def helper(x): + return dedent(x) + """, + ) + assert public_names(module) == ["LIMIT", "cake_toy_det", "helper"] + with pytest.raises(AssertionError) as info: + assert_mode_names(module) + message = str(info.value) + assert message.startswith("1 "), message + assert "toy.cake_toy_det_train.helper: lacks the mode token 'det'" in message + + +# Every callable here takes ``deterministic``, by name or through a ``**kwargs`` of an +# entry point; the constructor of the autograd class is torch's (*args, **kwargs). +DETERMINISTIC = ( + FUNCTION + + """ + +class CakeToyDetFunction(Function): + @staticmethod + def forward(ctx, x, deterministic=True): + return x + + @staticmethod + def backward(ctx, grad, **kwargs): + return grad, None + + +class CakeToyDetContext: + def __init__(self, world_size, deterministic=True): + self.world_size = world_size + + +class CakeToyDetOptions: + def __init__(self, **options): + self.options = options + + +class CakeToyDetPlan: + @classmethod + def build(cls, shape, *, deterministic=True): + return cls() + + +def cake_toy_det(x, deterministic=True): + return x + + +def cake_toy_det_train_forward(x, **kwargs): + return x +""" +) + + +@pytest.mark.parametrize( + "name, where, through", + [ + ("cake_toy_det", "cake_toy_det", ""), + ("cake_toy_det_train_forward", "cake_toy_det_train_forward", "**kwargs"), + ("CakeToyDetFunction", "CakeToyDetFunction.forward", ""), + ("CakeToyDetFunction", "CakeToyDetFunction.backward", "**kwargs"), + ("CakeToyDetContext", "CakeToyDetContext", ""), + ("CakeToyDetOptions", "CakeToyDetOptions", "**options"), + ("CakeToyDetPlan", "CakeToyDetPlan.build", ""), + ], +) +def test_deterministic_parameter_fails(name: str, where: str, through: str) -> None: + module = _module(DET_MODULE, DETERMINISTIC) + error = f"toy.cake_toy_det_train.{where}: takes a 'deterministic' parameter" + error += f" through {through}\n" if through else "\n" + for objs in (module, [getattr(module, name)]): + with pytest.raises(AssertionError) as info: + assert_no_deterministic_keyword(objs) + assert error in f"{info.value}\n", info.value + + +def test_deterministic_parameter_report_lists_every_entry() -> None: + module = _module(DET_MODULE, DETERMINISTIC) + with pytest.raises(AssertionError) as info: + assert_no_deterministic_keyword(module) + message = str(info.value) + assert message.startswith("7 "), message + # the constructor of the autograd class, (*args, **kwargs), is not an entry point + assert "toy.cake_toy_det_train.CakeToyDetFunction:" not in message + + +# A facade entry that wraps a backend function and adds ``deterministic``: the +# signature through ``__wrapped__`` hides it. +WRAPPER = """ +import functools + + +def backend_forward(x): + return x + + +@functools.wraps(backend_forward) +def cake_toy_det(x, deterministic=True): + return backend_forward(x) + + +__all__ = ["cake_toy_det"] +""" + + +def test_deterministic_parameter_of_a_wrapper_fails() -> None: + module = _module(DET_MODULE, WRAPPER) + error = "toy.cake_toy_det_train.cake_toy_det: takes a 'deterministic' parameter" + with pytest.raises(AssertionError, match=re.escape(error)): + assert_no_deterministic_keyword(module) + + +# A wrapper's own (*args, **kwargs): inspect.signature reads the function it wraps. +PLAIN_WRAPPER = """ +import functools + + +def backend_forward(x): + return x + + +@functools.wraps(backend_forward) +def cake_toy_det(*args, **kwargs): + return backend_forward(*args, **kwargs) + + +__all__ = ["cake_toy_det"] +""" + + +def test_callables_without_deterministic_parameter_pass() -> None: + module = _module(DET_MODULE, DET) + # the autograd constructor and the public method with **kwargs pass + assert_no_deterministic_keyword(module) + assert_no_deterministic_keyword([len, 3, "text", module.cake_toy_det]) + assert_no_deterministic_keyword(_module(DET_MODULE, PLAIN_WRAPPER)) + + +BACKEND = """ +class CakeToyDetFunction: + @staticmethod + def forward(ctx, x): + return x + + +def cake_toy_det_train_forward(x): + return x +""" + +# The facade re-exports the backend's class and wraps its function. +FACADE = """ +import functools + +CakeToyDetFunction = backend.CakeToyDetFunction + + +@functools.wraps(backend.cake_toy_det_train_forward) +def cake_toy_det_train_forward(x): + return backend.cake_toy_det_train_forward(x) + + +__all__ = ["CakeToyDetFunction", "cake_toy_det_train_forward"] +""" +BACKEND_NAME = "toy.experimental.cake.cake_toy_det_train.cake_backend" + + +def _facade_and_backend() -> tuple[types.ModuleType, types.ModuleType]: + backend = _module(BACKEND_NAME, BACKEND) + return _module(DET_MODULE, FACADE, backend=backend), backend + + +def test_namespaces_bind_the_module_objects_under_its_names() -> None: + facade, backend = _facade_and_backend() + top = _module( + "toy", + CakeToyDetFunction=facade.CakeToyDetFunction, + cake_toy_det_train_forward=facade.cake_toy_det_train_forward, + unrelated=len, + ) + assert_same_object_same_name(facade, [top, backend]) + + +def test_an_alias_in_any_namespace_fails() -> None: + facade, backend = _facade_and_backend() + backend.CakeToyFunction = backend.CakeToyDetFunction + # the function the facade entry wraps + backend.cake_toy_train_forward = backend.cake_toy_det_train_forward + backend._former = backend.cake_toy_det_train_forward # private: not checked + facade.cake_toy = facade.cake_toy_det_train_forward # not in __all__ + top = _module("toy", cake_toy_forward=facade.cake_toy_det_train_forward) + with pytest.raises(AssertionError) as info: + assert_same_object_same_name(facade, [top, backend]) + message = str(info.value) + assert message.startswith("4 "), message + for alias in ( + f"{BACKEND_NAME}.CakeToyFunction: binds", + f"{BACKEND_NAME}.cake_toy_train_forward: binds", + "toy.cake_toy_det_train.cake_toy: binds", + "toy.cake_toy_forward: binds", + ): + assert alias in message, alias + assert "_former" not in message + + +# A facade that serves its public names from the backend through a module +# ``__getattr__`` (nothing bound), an ALL_CAPS name for its function among them. +LAZY_FACADE = """ +def __getattr__(name): + if name == "TOY_FORWARD": + return backend.cake_toy_det_train_forward + if name in __all__: + return getattr(backend, name) + raise AttributeError(name) + + +__all__ = ["CakeToyDetFunction", "cake_toy_det_train_forward"] +""" + + +def test_lazy_public_names_of_the_module_are_seen() -> None: + backend = _module(BACKEND_NAME, BACKEND) + facade = _module(DET_MODULE, LAZY_FACADE, backend=backend) + top = _module("toy", CakeToyDetFunction=facade.CakeToyDetFunction) + assert_same_object_same_name(facade, [top, backend]) + assert "CakeToyDetFunction" not in vars(facade) + backend.CakeToyFunction = backend.CakeToyDetFunction + facade.__all__ = [*facade.__all__, "TOY_FORWARD"] + with pytest.raises(AssertionError) as info: + assert_same_object_same_name(facade, [top, backend]) + message = str(info.value) + assert message.startswith("2 "), message + for alias in ( + f"{BACKEND_NAME}.CakeToyFunction: binds {DET_MODULE}.CakeToyDetFunction", + f"{DET_MODULE}.TOY_FORWARD: binds {DET_MODULE}.cake_toy_det_train_forward", + ): + assert alias in message, alias + + +# The ``_LAZY_EXPORTS`` rows of the top level (``name -> (module, attribute)``, as in +# flashinfer/__init__.py) that serve the facade, its names and other modules. +LAZY_EXPORTS = { + "cake_toy_det_train_forward": ( + ".cake_toy_det_train", + "cake_toy_det_train_forward", + ), + "CakeToyDetFunction": ("toy.cake_toy_det_train", "CakeToyDetFunction"), + "cake_toy_det_train": (".cake_toy_det_train", None), + # private, other modules, a relative name above the top level: not checked + "_former": (".cake_toy_det_train", "cake_toy_det_train_forward"), + "cake_toy": (".cake_toy_train", "cake_toy"), + "toy_backend": (".experimental.cake.cake_toy_det_train", None), + "far": ("..cake_toy_det_train", None), +} + + +def test_lazy_export_rows_are_read_statically() -> None: + facade, backend = _facade_and_backend() + top = _module("toy", _LAZY_EXPORTS=dict(LAZY_EXPORTS)) + forward = "cake_toy_det_train_forward" + # relative to toy.sub, "." is toy.sub: a row of another module + sub = _module( + "toy.sub", _LAZY_EXPORTS={"cake_toy": (".cake_toy_det_train", forward)} + ) + namespaces = [top, sub, backend] + assert_same_object_same_name(facade, namespaces) + top._LAZY_EXPORTS.update( + cake_toy_forward=(".cake_toy_det_train", forward), + CakeToyFunction=("toy.cake_toy_det_train", "CakeToyDetFunction"), + cake_toy_train=(".cake_toy_det_train", None), + ) + # relative to toy.sub, ".." is toy + sub._LAZY_EXPORTS["cake_toy_fwd"] = ("..cake_toy_det_train", forward) + with pytest.raises(AssertionError) as info: + assert_same_object_same_name(facade, namespaces) + message = str(info.value) + assert message.startswith("4 "), message + for alias in ( + f"toy.cake_toy_forward: _LAZY_EXPORTS binds {DET_MODULE}.{forward} under " + "another name", + f"toy.CakeToyFunction: _LAZY_EXPORTS binds {DET_MODULE}.CakeToyDetFunction", + f"toy.cake_toy_train: _LAZY_EXPORTS binds the module {DET_MODULE} under", + f"toy.sub.cake_toy_fwd: _LAZY_EXPORTS binds {DET_MODULE}.{forward} under", + ): + assert alias in message, alias + # a row its first access has bound is reported once, as a binding + top.cake_toy_forward = facade.cake_toy_det_train_forward + with pytest.raises(AssertionError) as info: + assert_same_object_same_name(facade, namespaces) + message = str(info.value) + assert message.startswith("4 "), message + assert f"toy.cake_toy_forward: binds {DET_MODULE}.{forward} under" in message + assert "toy.cake_toy_forward: _LAZY_EXPORTS" not in message + + +# A facade that forwards to its backend by a call, importing it inside its functions +# (``backend`` stands in for that import): no attribute links the two. +CALLING_FACADE = """ +def cake_toy_det(x): + return backend.cake_toy_det(x) + + +def cake_toy_det_train_forward(x): + return backend.cake_toy_det_train_forward(x) + + +__all__ = ["cake_toy_det", "cake_toy_det_train_forward"] +""" +CALLED_BACKEND = """ +def cake_toy_det(x): + return x + + +def cake_toy_det_train_forward(x): + return x +""" + + +def test_forwards_tie_the_backend_objects_a_facade_calls() -> None: + backend = _module(BACKEND_NAME, CALLED_BACKEND) + facade = _module(DET_MODULE, CALLING_FACADE, backend=backend) + forward = "cake_toy_det_train_forward" + forwards = [ + ("cake_toy_det", backend.cake_toy_det), + (forward, getattr(backend, forward)), + ] + assert_same_object_same_name(facade, [backend], forwards=forwards) + # the backend keeps an old name of a function the facade calls + backend.cake_toy_train_forward = getattr(backend, forward) + top = _module("toy", cake_toy=backend.cake_toy_det) + # unseen without forwards + assert_same_object_same_name(facade, [top, backend]) + with pytest.raises(AssertionError) as info: + assert_same_object_same_name(facade, [top, backend], forwards=forwards) + message = str(info.value) + assert message.startswith("2 "), message + for alias in ( + f"{BACKEND_NAME}.cake_toy_train_forward: binds the backend object of " + f"{DET_MODULE}.{forward} under another name", + f"toy.cake_toy: binds the backend object of {DET_MODULE}.cake_toy_det under", + ): + assert alias in message, alias + with pytest.raises(ValueError, match="'cake_toy_fwd', not a public name"): + assert_same_object_same_name( + facade, [backend], forwards=[("cake_toy_fwd", backend.cake_toy_det)] + ) + + +def test_the_module_is_bound_only_under_its_last_name_part() -> None: + facade, backend = _facade_and_backend() + # importing the submodule binds it under its last name part + top = _module("toy", cake_toy_det_train=facade) + assert_same_object_same_name(facade, [top, backend]) + # from . import cake_toy_det_train as cake_toy_train + top.cake_toy_train = facade + with pytest.raises(AssertionError) as info: + assert_same_object_same_name(facade, [top, backend]) + message = str(info.value) + assert message.startswith("1 "), message + alias = f"toy.cake_toy_train: binds the module {DET_MODULE} under another name" + assert alias in message, message + + +def test_old_names_that_are_gone_pass() -> None: + assert_old_names_fail( + old_modules=( + "json.no_such_module_8928", + "no_such_module_8928", + "email.no_such_package_8928.child", + ), + old_names=( + ("json", "no_such_name_8928"), + ("json.decoder", "no_such_name_8928"), + # the module of the name, or a parent below the top-level package, is gone + ("json.no_such_module_8928", "name"), + ("email.no_such_package_8928.child", "name"), + ), + ) + + +def test_old_names_that_still_import_fail() -> None: + with pytest.raises(AssertionError) as info: + assert_old_names_fail( + old_modules=("json", "json.decoder", "no_such_package_8928.child"), + old_names=(("json", "dumps"), ("no_such_module_8928", "name")), + ) + message = str(info.value) + assert message.startswith("5 "), message + for failure in ( + "json: still imports", + "json.decoder: still imports", + "no_such_package_8928.child: ModuleNotFoundError for 'no_such_package_8928'", + "from json import dumps: still imports", + "from no_such_module_8928 import name: " + "the top-level module 'no_such_module_8928' is not found", + ): + assert failure in message, failure + + +def test_old_package_directories(tmp_path: Path) -> None: + package = tmp_path / "toy_8928" + (package / "stale" / "__pycache__").mkdir(parents=True) + (package / "stale" / "__pycache__" / "old.cpython-312.pyc").write_bytes(b"") + (package / "shim").mkdir() + (package / "shim" / "entry.py").write_text("") + (package / "__init__.py").write_text("") + (package / "moved.py").write_text('raise ImportError("moved to toy_8928.new")\n') + (package / "broken.py").write_text("import toy_8928.absent_8928\n") + # a directory a removed package left behind (no source) counts as gone + assert_old_names_fail(old_modules=("toy_8928.stale",), cwd=tmp_path) + with pytest.raises(AssertionError) as info: + assert_old_names_fail( + old_modules=("toy_8928.shim", "toy_8928.moved"), + # a module that imports a missing module other than itself or a parent + old_names=(("toy_8928.broken", "name"),), + cwd=tmp_path, + ) + message = str(info.value) + assert message.startswith("3 "), message + assert "toy_8928.shim: still imports" in message + assert "toy_8928.moved: raises ImportError: moved to toy_8928.new" in message + assert ( + "from toy_8928.broken import name: ModuleNotFoundError for " + "'toy_8928.absent_8928', not for toy_8928.broken or a parent" + ) in message + + +def test_a_timeout_is_one_failure_among_the_others(tmp_path: Path) -> None: + (tmp_path / "toy_8928_slow.py").write_text("import time\n\ntime.sleep(60)\n") + module = _module(DET_MODULE, '__all__ = ["route_key"]\nroute_key = len\n') + with pytest.raises(AssertionError) as info: + assert_cake_mode_module( + module, old_modules=("toy_8928_slow",), cwd=tmp_path, timeout=1 + ) + message = str(info.value) + assert message.startswith("2 "), message + assert "toy.cake_toy_det_train.route_key: lacks the mode token 'det'" in message + assert ( + "the fresh interpreter timed out after 1 s on " + "old_modules=['toy_8928_slow'], old_names=[]" + ) in message + + +def test_all_checks_report_together() -> None: + facade, backend = _facade_and_backend() + facade.__all__ = [*facade.__all__, "route_key", "cake_toy_det"] + facade.route_key = lambda deterministic=True: deterministic + backend.cake_toy_train_forward = backend.cake_toy_det_train_forward + # a facade function that calls a backend function kept under an old name + backend.cake_toy = lambda x: x + facade.cake_toy_det = lambda x: backend.cake_toy(x) + with pytest.raises(AssertionError) as info: + assert_cake_mode_module( + facade, + namespaces=[backend], + forwards=[("cake_toy_det", backend.cake_toy)], + old_modules=("json",), + old_names=(("json", "dumps"),), + ) + message = str(info.value) + assert message.startswith("6 "), message + for failure in ( + "toy.cake_toy_det_train.route_key: lacks the mode token 'det'", + "toy.cake_toy_det_train.route_key: takes a 'deterministic' parameter", + f"{BACKEND_NAME}.cake_toy_train_forward: binds", + f"{BACKEND_NAME}.cake_toy: binds the backend object of {DET_MODULE}.", + "json: still imports", + "from json import dumps: still imports", + ): + assert failure in message, failure diff --git a/tests/test_helpers/cake_mode_names.py b/tests/test_helpers/cake_mode_names.py new file mode 100644 index 00000000000..1f79aae596d --- /dev/null +++ b/tests/test_helpers/cake_mode_names.py @@ -0,0 +1,597 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright (c) 2026 by FlashInfer team +"""Mode names of the Cake training modules (flashinfer issue #8928). + +A Cake training module is ``flashinfer.cake___train[_kcp]``, its ``mode`` +``det`` or ``nondet``. Its public names are its ``__all__`` or, without one, the +public attributes defined in it (:func:`public_names`). The checks: + +* :func:`assert_mode_names`: every public name carries the mode word of the module, + the ``_``-delimited token ``det`` / ``nondet`` of a snake_case name or the part + ``Det`` / ``Nondet`` of a CamelCase name; the word of the other mode fails. + ALL_CAPS constants (:data:`CONSTANT`) are exempt. With ``stem=True`` the mode also + comes right after the op: a snake_case name starts with ``cake__`` (the + support query with ``is_``), a CamelCase name with ``Cake``. +* :func:`assert_no_deterministic_keyword`: no public callable accepts + ``deterministic``: ``inspect.signature(obj).bind_partial(deterministic=False)`` + raises ``TypeError`` (so a ``**kwargs`` fails too) for a function, the constructor + of a class and the ``forward`` / ``backward`` of a ``torch.autograd.Function`` + subclass, and no public method has a parameter named ``deterministic``. +* :func:`assert_same_object_same_name`: the module and the other namespaces given + (the ``flashinfer`` top level, the backend package or modules) bind the module, an + object of it or a backend object it forwards to (``forwards``) only under the name + the module gives it, so no alias of an old name is left. The module's lazy public + names and the rows of a ``_LAZY_EXPORTS`` table count too. +* :func:`assert_old_names_fail`: old module paths and old names fail at import, in a + fresh interpreter. + +:func:`assert_cake_mode_module` runs all of them for one module and reports every +failure in one ``AssertionError``. This module imports neither flashinfer nor torch: +a family's names test passes its modules in. + +Nothing here is keyed on the existence of ``flashinfer.experimental.cake.``: +no check looks a backend up by its path, so none skips silently when the path is +absent. Each family test passes its facade and, through ``namespaces``, its backend +package or modules explicitly (the conv1d KCP facade, for one, passes the ``kcp`` +module of the single-rank backend package). A call is not seen: a facade function +that calls its backend (the facade imports its backend inside its functions or its +``__getattr__``) ties the backend object to its name only through the +``(name, object)`` pair the family test lists in ``forwards``. +""" + +from __future__ import annotations + +import importlib.util +import inspect +import json +import re +import subprocess +import sys +from collections.abc import Iterable +from os import PathLike +from types import ModuleType + +MODES = ("det", "nondet") +# module constants: exempt from the mode word +CONSTANT = re.compile(r"^[A-Z][A-Z0-9_]*$") +# the last part of the name of a Cake training module +MODULE = re.compile(r"^cake_(?P[a-z0-9_]+?)_(?Pdet|nondet)_train(?:_kcp)?$") +# the parts of a CamelCase name: an acronym before a word (digits allowed: FP8, HD256), +# a word, a run of capitals +_CAMEL_PARTS = re.compile(r"[A-Z][A-Z0-9]*(?=[A-Z][a-z])|[A-Z]?[a-z0-9]+|[A-Z0-9]+") +# the line of the fresh interpreter's result (printed by _OLD_NAMES_SCRIPT) +_MARKER = "CAKE_OLD_NAMES " +_TIMEOUT = 600.0 +# torch.autograd.Function by module and qualified name: torch is not imported +_AUTOGRAD_FUNCTION = ("torch.autograd.function", "Function") + + +def public_names(module: ModuleType) -> list[str]: + """The ``__all__`` of ``module``; without one, its public attributes defined in it. + + "Defined in it" drops submodules and the objects whose ``__module__`` names another + module (imports); values without ``__module__`` (numbers, tuples) stay. + """ + exported = getattr(module, "__all__", None) + if exported is not None: + return list(exported) + return sorted( + name + for name, obj in vars(module).items() + if not name.startswith("_") + and not isinstance(obj, ModuleType) + and getattr(obj, "__module__", module.__name__) == module.__name__ + ) + + +def assert_mode_names( + module: ModuleType, + mode: str | None = None, + *, + names: Iterable[str] | None = None, + stem: bool = True, + stem_exceptions: Iterable[str] = (), +) -> None: + """Every public name of ``module`` carries the mode word, and (``stem``) in order. + + ``mode`` defaults to the mode in the module's name; ``names`` defaults to + :func:`public_names`. The order check needs a module named + ``cake___train[_kcp]``; pass ``stem=False`` for another module. The + names in ``stem_exceptions`` (exceptions a family documents) skip the order check + only, not the mode word. + """ + _raise(_mode_name_errors(module, mode, names, stem, stem_exceptions)) + + +def assert_no_deterministic_keyword(objs: ModuleType | Iterable[object]) -> None: + """No callable of ``objs`` (a module: its public names) takes ``deterministic``. + + An entry point fails when ``inspect.signature(entry).bind_partial( + deterministic=False)`` does not raise ``TypeError``, so a ``**kwargs`` fails too. + The entry points are a callable that is not a class, the constructor of a class, + and the ``forward`` and ``backward`` of a ``torch.autograd.Function`` subclass + (inherited ones included). Such a subclass is found by the module and name of + its base, torch not imported; its constructor is torch's ``(*args, **kwargs)``, + not an entry point. Each of these, the ``forward`` and ``backward`` of another + class and the public methods a class body defines also fail with a parameter + named ``deterministic``, in its own signature or in the one of the function it + wraps (``__wrapped__``). A callable without a Python signature (a builtin type) + is skipped. + """ + _raise(_deterministic_errors(objs)) + + +def assert_same_object_same_name( + module: ModuleType, + namespaces: Iterable[ModuleType] = (), + *, + forwards: Iterable[tuple[str, object]] = (), +) -> None: + """``module`` and ``namespaces`` bind ``module`` and each object of it only under + its name in ``module``. + + The module itself has the last part of its name (``flashinfer`` binds + ``cake_x_nondet_train`` under that name only, eagerly or lazily). The objects of + the module are its public callables, the functions they wrap (``__wrapped__``, as + :func:`functools.wraps` sets) and the object of each ``(name, obj)`` pair of + ``forwards``: the backend object that the public ``name`` of ``module`` calls, a + link no attribute shows. So a facade entry that wraps or calls a backend + function ties the backend's name for it too. A name of ``forwards`` that is not + a public name of ``module`` raises ``ValueError``. ALL_CAPS constants are left + out. Names starting with ``_`` are private and skipped. + + A namespace binds its attributes (``vars``); ``module`` also binds the public names + its module ``__getattr__`` serves lazily, resolved with ``getattr``. Another + namespace is read through ``vars`` only: pass a backend package that serves its + names through its own module ``__getattr__`` as the submodules it serves from + (the MoE grouped-GEMM backend package as its ``cake_backend`` and + ``cake_autograd``). A namespace that defines a dict ``_LAZY_EXPORTS`` + (``name -> (module, attribute)``, as in ``flashinfer/__init__.py``) has its rows + read statically, nothing imported: a row whose module is ``module`` serves + ``attribute`` under the same name, or with ``attribute`` None the module itself + under the last part of the module's name; another name is an alias. A relative + module name resolves against the namespace's ``__name__``, as + ``importlib.import_module(name, __name__)`` does; rows of other modules are + ignored. + """ + _raise(_same_object_errors(module, namespaces, forwards)) + + +def assert_old_names_fail( + old_modules: Iterable[str] = (), + old_names: Iterable[tuple[str, str]] = (), + *, + cwd: str | PathLike[str] | None = None, + timeout: float = _TIMEOUT, +) -> None: + """The old names fail at import, checked in a fresh ``sys.executable`` interpreter. + + Each path of ``old_modules`` raises ``ModuleNotFoundError`` for itself or for a + parent below the top-level package; a directory a removed package left behind + (a namespace package without a ``.py`` file) counts as gone. For each + ``(module, name)`` of ``old_names``, ``from module import name`` raises + ``ImportError``: the module imports without the name, or the module or a parent + of it below the top-level package is not found. The top-level package must + import, so a wrong ``sys.path`` does not pass. ``cwd`` is the working directory + of the interpreter (the first entry of its ``sys.path``); a ``timeout`` of the + interpreter is one failure. + """ + _raise(_old_name_errors(old_modules, old_names, cwd, timeout)) + + +def assert_cake_mode_module( + module: ModuleType, + mode: str | None = None, + *, + namespaces: Iterable[ModuleType] = (), + forwards: Iterable[tuple[str, object]] = (), + old_modules: Iterable[str] = (), + old_names: Iterable[tuple[str, str]] = (), + stem: bool = True, + stem_exceptions: Iterable[str] = (), + cwd: str | PathLike[str] | None = None, + timeout: float = _TIMEOUT, +) -> None: + """All the checks for one public facade module, every failure in one report. + + ``namespaces`` are the other modules that bind objects of ``module``: the + ``flashinfer`` top level and the backend package or modules the facade forwards + to or re-exports, each passed explicitly (nothing is found by path, see the + module docstring; a lazy backend package as the submodules it serves from). + ``forwards`` are the ``(public name, backend object)`` pairs of the facade + functions that call their backend. Both are those of + :func:`assert_same_object_same_name`. ``old_modules`` and ``old_names`` are the + module paths and the ``(module, name)`` pairs before the rename; ``cwd`` and + ``timeout`` are those of :func:`assert_old_names_fail`. + """ + _raise( + [ + *_mode_name_errors(module, mode, None, stem, stem_exceptions), + *_deterministic_errors(module), + *_same_object_errors(module, namespaces, forwards), + *_old_name_errors(old_modules, old_names, cwd, timeout), + ] + ) + + +def _raise(errors: list[str]) -> None: + if errors: + raise AssertionError( + f"{len(errors)} Cake mode-name failure(s):\n " + "\n ".join(errors) + ) + + +def _mode_name_errors( + module: ModuleType, + mode: str | None, + names: Iterable[str] | None, + stem: bool, + stem_exceptions: Iterable[str], +) -> list[str]: + leaf = module.__name__.rpartition(".")[2] + match = MODULE.match(leaf) + if match is not None: + if mode not in (None, match["mode"]): + raise ValueError( + f"{module.__name__} is a {match['mode']} module, not {mode}" + ) + mode = match["mode"] + if mode not in MODES: + raise ValueError( + f"{module.__name__} is not named cake___train[_kcp]: " + f"pass mode, one of {MODES}" + ) + if stem and match is None: + raise ValueError( + f"{module.__name__} is not named cake___train[_kcp]: " + "pass stem=False" + ) + prefix = f"cake_{match['op']}_{mode}" if stem else None + support = f"is_{leaf}" + exempt = set(stem_exceptions) + errors = [] + for name in public_names(module) if names is None else names: + if CONSTANT.match(name): + continue + skip_order = name in exempt + error = _name_error(name, mode, None if skip_order else prefix, support) + if error is not None: + errors.append(f"{module.__name__}.{name}: {error}") + return errors + + +def _name_error(name: str, mode: str, prefix: str | None, support: str) -> str | None: + """Why ``name`` breaks the rule of a ``mode`` module, or None. + + ``prefix`` is ``cake__`` (None: no order check) and ``support`` the + prefix ``is_`` of the support query. + """ + other = "nondet" if mode == "det" else "det" + camel = name[:1].isupper() + if camel: + words = _CAMEL_PARTS.findall(name) + own, wrong, kind = mode.capitalize(), other.capitalize(), "part" + else: + words = name.split("_") + own, wrong, kind = mode, other, "token" + if wrong in words: + return f"carries {wrong!r}, the word of the other mode" + if own not in words: + return f"lacks the mode {kind} {own!r}" + if prefix is None: + return None + if camel: + if not name.lower().startswith(prefix.replace("_", "")): + return f"does not start with Cake ({prefix!r} in CamelCase)" + elif not any(name == p or name.startswith(p + "_") for p in (prefix, support)): + return f"does not start with {prefix!r} (or {support!r} for the support query)" + return None + + +def _deterministic_errors(objs: ModuleType | Iterable[object]) -> list[str]: + if isinstance(objs, ModuleType): + items = [ + (f"{objs.__name__}.{name}", getattr(objs, name)) + for name in public_names(objs) + ] + else: + items = [(_label(obj), obj) for obj in objs] + errors = [] + for label, obj in items: + if not callable(obj): + continue + for where, target, entry in _signature_targets(label, obj): + error = _deterministic_error(target, entry) + if error is not None: + errors.append(f"{where}: {error}") + return errors + + +def _deterministic_error(target: object, entry: bool) -> str | None: + """Why ``target`` takes ``deterministic``, or None. + + The parameter names are read in its own signature and in the one of the function + it wraps (``__wrapped__``). An ``entry`` point also fails when the signature + ``inspect.signature`` gives binds ``deterministic=False`` (a ``**kwargs``). A + callable without a Python signature has none. + """ + names: set[str] = set() + signature = None + for follow_wrapped in (True, False): + try: + found = inspect.signature(target, follow_wrapped=follow_wrapped) + except (TypeError, ValueError): # no Python signature + continue + names.update(found.parameters) + if follow_wrapped: + signature = found + if "deterministic" in names: + return "takes a 'deterministic' parameter" + if not entry or signature is None: + return None + try: + signature.bind_partial(deterministic=False) + except TypeError: + return None + # no parameter has the name, so a **kwargs takes it + kwargs = next( + (p.name for p in signature.parameters.values() if p.kind is p.VAR_KEYWORD), + "kwargs", + ) + return f"takes a 'deterministic' parameter through **{kwargs}" + + +def _label(obj: object) -> str: + qualname = getattr(obj, "__qualname__", None) + if qualname is None: + return repr(obj) + return f"{getattr(obj, '__module__', '?')}.{qualname}" + + +def _signature_targets(label: str, obj: object) -> list[tuple[str, object, bool]]: + """``(label, callable, entry point)`` for ``obj`` and, for a class, its forward, + backward and public methods. + """ + if not inspect.isclass(obj): + return [(label, obj, True)] + autograd = _is_autograd_function(obj) + targets = [(label, obj, not autograd)] + attrs = {n for n in vars(obj) if not n.startswith("_")} + for attr in sorted(attrs | {"forward", "backward"}): + member = getattr(obj, attr, None) + if callable(member) and not inspect.isclass(member): + entry = autograd and attr in ("forward", "backward") + targets.append((f"{label}.{attr}", member, entry)) + return targets + + +def _is_autograd_function(cls: type) -> bool: + """``cls`` subclasses ``torch.autograd.Function``, found without importing torch.""" + return any( + (getattr(base, "__module__", None), base.__qualname__) == _AUTOGRAD_FUNCTION + for base in cls.__mro__ + ) + + +def _same_object_errors( + module: ModuleType, + namespaces: Iterable[ModuleType], + forwards: Iterable[tuple[str, object]], +) -> list[str]: + # the public names of the module, the lazy ones resolved by its __getattr__ + public = {name: getattr(module, name) for name in public_names(module)} + # id of an object of the module -> (the object, kept alive; the names it may be + # bound under; how a report shows it) + owned: dict[int, tuple[object, set[str], set[str]]] = {} + + def own(obj: object, name: str, shown: str) -> None: + entry = owned.setdefault(id(obj), (obj, set(), set())) + entry[1].add(name) + entry[2].add(shown) + + own(module, module.__name__.rpartition(".")[2], f"the module {module.__name__}") + for name, obj in public.items(): + if CONSTANT.match(name) or not callable(obj): + continue + for target in (obj, inspect.unwrap(obj)): + own(target, name, f"{module.__name__}.{name}") + for name, obj in forwards: + if name not in public: + raise ValueError( + f"forwards names {name!r}, not a public name of {module.__name__}" + ) + for target in (obj, inspect.unwrap(obj)): + own(target, name, f"the backend object of {module.__name__}.{name}") + errors = [] + seen: set[int] = set() + for namespace in (module, *namespaces): + if id(namespace) in seen: + continue + seen.add(id(namespace)) + bindings = dict(vars(namespace)) + if namespace is module: # its lazy public names too + for name, obj in public.items(): + bindings.setdefault(name, obj) + reported: set[str] = set() + for name, obj in bindings.items(): + entry = owned.get(id(obj)) + if name.startswith("_") or entry is None or name in entry[1]: + continue + shown = " / ".join(sorted(entry[2])) + errors.append( + f"{namespace.__name__}.{name}: binds {shown} under another name" + ) + reported.add(name) + # a lazy row already bound (and reported) above is reported once + errors.extend( + error + for name, error in _lazy_export_errors(module, namespace) + if name not in reported + ) + return errors + + +def _lazy_export_errors( + module: ModuleType, namespace: ModuleType +) -> list[tuple[str, str]]: + """``(name, error)`` for each row of the ``_LAZY_EXPORTS`` dict of ``namespace`` + that serves ``module`` or an attribute of it under another name. + + The table is read from ``vars`` and nothing is imported. + """ + table = vars(namespace).get("_LAZY_EXPORTS") + if not isinstance(table, dict): + return [] + leaf = module.__name__.rpartition(".")[2] + errors = [] + for name, (module_name, attribute) in table.items(): + if name.startswith("_"): + continue + try: + # as importlib.import_module(module_name, namespace.__name__) resolves it + target = importlib.util.resolve_name(module_name, namespace.__name__) + except ImportError: # a relative name above the top-level package + continue + expected = leaf if attribute is None else attribute + if target != module.__name__ or name == expected: + continue + if attribute is None: + bound = f"the module {module.__name__}" + else: + bound = f"{module.__name__}.{attribute}" + errors.append( + ( + name, + f"{namespace.__name__}.{name}: _LAZY_EXPORTS binds {bound} " + "under another name", + ) + ) + return errors + + +# Run by ``sys.executable -c`` with one argument, the JSON ``[old_modules, old_names]``; +# prints _MARKER and the JSON list of failures. +_OLD_NAMES_SCRIPT = r""" +import importlib +import json +import sys +from pathlib import Path + +modules, names = json.loads(sys.argv[1]) +failures = [] + + +def gone(path, error): + # the module, or a parent of it below the top-level package, is missing + missing = error.name or "" + return missing == path or ("." in missing and path.startswith(missing + ".")) + + +def stale(module): + # a namespace package without source: a directory a removed package left behind + paths = getattr(module, "__path__", None) + if getattr(module, "__file__", None) is not None or paths is None: + return False + return not any(next(Path(p).glob("*.py"), None) for p in paths) + + +for path in modules: + try: + module = importlib.import_module(path) + except ModuleNotFoundError as error: + if not gone(path, error): + failures.append( + f"{path}: ModuleNotFoundError for {error.name!r}, not for the module " + "or a parent below the top-level package" + ) + continue + except Exception as error: + failures.append( + f"{path}: raises {type(error).__name__}: {error}, " + "not ModuleNotFoundError" + ) + continue + if not stale(module): + failures.append(f"{path}: still imports ({getattr(module, '__file__', None)})") + +for path, name in names: + statement = f"from {path} import {name}" + try: + importlib.import_module(path) + except ModuleNotFoundError as error: + # the module, or a parent of it below the top-level package, is gone, so is + # the name; a missing top-level module proves nothing (a wrong sys.path) + missing = error.name or "" + if "." in missing and gone(path, error): + continue + if missing and "." not in missing: + reason = f"the top-level module {missing!r} is not found" + else: + reason = ( + f"ModuleNotFoundError for {error.name!r}, not for {path} or a parent" + ) + failures.append(f"{statement}: {reason}") + continue + except Exception as error: + failures.append( + f"{statement}: {path} does not import ({type(error).__name__}: {error})" + ) + continue + try: + exec(statement, {}) + except ModuleNotFoundError as error: + if error.name != f"{path}.{name}": + failures.append( + f"{statement}: ModuleNotFoundError for {error.name!r}, " + "not ImportError for the name" + ) + except ImportError: + pass + except Exception as error: + failures.append( + f"{statement}: raises {type(error).__name__}: {error}, not ImportError" + ) + else: + failures.append(f"{statement}: still imports") + +print("CAKE_OLD_NAMES " + json.dumps(failures)) +""" + + +def _old_name_errors( + old_modules: Iterable[str], + old_names: Iterable[tuple[str, str]], + cwd: str | PathLike[str] | None, + timeout: float, +) -> list[str]: + modules = list(old_modules) + names = [tuple(pair) for pair in old_names] + if not modules and not names: + return [] + try: + result = subprocess.run( + [sys.executable, "-c", _OLD_NAMES_SCRIPT, json.dumps([modules, names])], + capture_output=True, + text=True, + timeout=timeout, + cwd=cwd, + ) + except subprocess.TimeoutExpired as error: + # the output captured so far is bytes, text=True or not + captured = error.stderr or b"" + stderr = ( + captured.decode(errors="replace") + if isinstance(captured, bytes) + else captured + ) + return [ + f"the fresh interpreter timed out after {timeout:g} s on " + f"old_modules={modules!r}, old_names={names!r}: {stderr[-2000:]}" + ] + for line in reversed(result.stdout.splitlines()): + if line.startswith(_MARKER): + return json.loads(line[len(_MARKER) :]) + return [ + f"the fresh interpreter exited {result.returncode} without a result: " + f"{result.stderr[-2000:]}" + ]