diff --git a/docs/CICD.md b/docs/CICD.md index 1a8586c1..3401550f 100644 --- a/docs/CICD.md +++ b/docs/CICD.md @@ -249,8 +249,17 @@ behind its Hub repo. - `tests/composer/test_selective_download.py::TestRealHubMetadata`: the published adapter repos' layout, against the live Hub. - `tests/hf/test_quantization.py`: the quantization libraries on a real - checkpoint. Its `GRANITE_SWITCH_E2E_MODELS=1` gate is opened by - `tests/conftest.py` whenever `-m` selects `release`. + checkpoint. +- The MultiSwitch real-checkpoint tests, which compose a real `granite-4.1-3b` + with real adapter libraries: + `tests/hf/test_multi_switch_real_checkpoint.py`, + `tests/integration/test_multi_switch_vllm_generate.py`, + `tests/integration/test_multi_switch_serving_e2e.py`, + `tests/integration/test_multi_switch_alora_cache.py`, + `tests/integration/test_conversation_prefix_cache.py` and + `tests/vllm/test_pipeline_parallelism_equivalence.py` (2 GPUs). + `tests/integration/test_conversation_concurrency.py` stays out: it never + composes a checkpoint and needs one pre-built at `GRANITE_SWITCH_CONV_DIR`. **The rest of a breadth matrix** is release-only too: PR runs keep one representative case. diff --git a/docs/MULTISWITCH_EXPLAINED.md b/docs/MULTISWITCH_EXPLAINED.md index dce582ad..99c404c2 100644 --- a/docs/MULTISWITCH_EXPLAINED.md +++ b/docs/MULTISWITCH_EXPLAINED.md @@ -569,7 +569,7 @@ An fp8 cache would saturate the mask and collapse the codeword separation the ga ### One render emits one control token -- *(template limit, not engine)* -The template keys off a single scalar `adapter_name`, so one `apply_chat_template` call yields one token for `single` and `multi` alike. Reaching MultiSwitch's actual shape -- several control tokens in one sequence -- means assembling token ids rather than rendering, which is what PRESERVE does and what `tests/hf/test_multi_switch_alora.py` does by concatenating two renders. So: *one token per render*, not one token per request. +The template keys off a single scalar `adapter_name`, so one `apply_chat_template` call yields one token for `single` and `multi` alike. Reaching MultiSwitch's actual shape -- several control tokens in one sequence -- means assembling token ids rather than rendering, which is what PRESERVE does and what `tests/hf/test_multi_switch_real_checkpoint.py` does by concatenating two renders. So: *one token per render*, not one token per request. ### Control tokens are freely generatable -- *(by design)* @@ -605,12 +605,9 @@ Test counts are `grep -c '^\s*def test_'` over the tree. Two files shrank in the | `tests/unit/test_conversation_lora_rule.py` | 8 | a LoRA turn falls back to a full render | | **HF backend -- CPU** | | | | `tests/hf/test_multi_switch.py` | 12 | the engine across attention backends; `TestReturnToBaseCoded` | -| `tests/hf/test_multi_switch_alora.py` | 9 | two aLoRA adapters in *one* sequence | | `tests/hf/test_multi_switch_buffers.py` | 4 | the codebook and LUT surviving a save/load round trip | -| `tests/hf/test_multi_switch_e2e.py` | 9 | compose -> load -> forward | +| `tests/hf/test_multi_switch_real_checkpoint.py` | 31 | real LoRA / aLoRA / mixed checkpoints: compose -> load -> forward -> generate; template placement, multi-turn, long prompts, two aLoRAs in one sequence, re-save | | `tests/hf/test_multi_switch_generate.py` | 6 | the `kv_len` mask fix; a prefill-only control token routing every later decode step | -| `tests/hf/test_multi_switch_mixed_tech.py` | 7 | LoRA + aLoRA in one checkpoint | -| `tests/hf/test_multi_switch_realistic.py` | 7 | chat template, real multi-turn, long prompts | | `tests/hf/test_conversation_routing.py` | 4 | the policy's ids actually routing as claimed | | **composer** | | | | `tests/composer/test_base_reset_token.py` | 11 | the engine driven by exactly what compose emits | diff --git a/src/granite_switch/composer/compose_granite_switch.py b/src/granite_switch/composer/compose_granite_switch.py index 583bdca2..40332dae 100755 --- a/src/granite_switch/composer/compose_granite_switch.py +++ b/src/granite_switch/composer/compose_granite_switch.py @@ -307,8 +307,8 @@ def refresh_switch_control_lut(model) -> bool: specific to ``--enable-audio`` rather than universal. Extracted from ``build()`` so the rebuild can be tested without composing a - real checkpoint (the real audio-compose tests are gated behind - ``GRANITE_SWITCH_E2E_MODELS=1``, unset in CI). + real checkpoint (the real audio-compose tests run only in the + release tier, not on PRs). Args: model: Composed model, after ``resize_token_embeddings``. diff --git a/tests/composer/test_control_lut_refresh.py b/tests/composer/test_control_lut_refresh.py index 08561779..7375bb1f 100644 --- a/tests/composer/test_control_lut_refresh.py +++ b/tests/composer/test_control_lut_refresh.py @@ -19,7 +19,7 @@ ``--switch-type multi --enable-audio`` and not multi alone. Why nothing caught it: every test that runs a real ``compose --switch-type -multi`` is gated behind ``GRANITE_SWITCH_E2E_MODELS=1``, which CI never sets, and +multi`` was gated behind an opt-in env var that CI never set, and none of them passes ``--enable-audio`` anyway. These tests are deliberately CPU-only and ungated so the intersection is covered on every run. """ diff --git a/tests/conftest.py b/tests/conftest.py index c9014cda..e15f0b2c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -43,16 +43,6 @@ def pytest_configure(config): # a newer toolkit in the image; this keeps the suites meaningful until then. os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0") - # ── release tier opens the real-checkpoint gate ─────────────── - # - # Some release-tier tests (test_quantization.py) are also gated on - # GRANITE_SWITCH_E2E_MODELS=1, which the GPU pod has no way to set: the runner - # passes only pytest arguments. A run that selects the release marker has asked - # for exactly those tests, so it sets the gate itself. setdefault, so an explicit - # GRANITE_SWITCH_E2E_MODELS=0 still wins. - if "release" in (config.getoption("markexpr", "") or "").replace("not release", ""): - os.environ.setdefault("GRANITE_SWITCH_E2E_MODELS", "1") - worker_id = os.environ.get("PYTEST_XDIST_WORKER") if worker_id is None: return # not running under xdist diff --git a/tests/hf/test_multi_switch.py b/tests/hf/test_multi_switch.py index 6fd7f2aa..ba4f65ae 100644 --- a/tests/hf/test_multi_switch.py +++ b/tests/hf/test_multi_switch.py @@ -371,7 +371,7 @@ def test_bf16_autocast_stays_correct(self): NOTE: on GPU, letting the memory head autocast to bf16 overflows its softmax to NaN and routes every token to base — this was a real bug caught - only by the GPU end-to-end test (tests/hf/test_multi_switch_e2e.py), NOT by + only by the GPU end-to-end test (tests/hf/test_multi_switch_real_checkpoint.py), NOT by CPU (CPU autocast does not reproduce the overflow). This CPU test documents the intended behavior and guards the no-NaN / correct-routing contract; the GPU e2e is the authoritative regression gate for the overflow itself.""" diff --git a/tests/hf/test_multi_switch_alora.py b/tests/hf/test_multi_switch_alora.py deleted file mode 100644 index 1ab83c02..00000000 --- a/tests/hf/test_multi_switch_alora.py +++ /dev/null @@ -1,358 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""MultiSwitch with aLoRA adapters, end to end on a real composed checkpoint. - -The switch itself does not know about adapter technology -- it matches control -token ids and routes. The LoRA/aLoRA difference is entirely WHERE the chat template -puts the control token, and that changes the routing shape completely: - - LoRA: user1 ... assistant1 ... user2 ... [gen] - routing: 1 1 1 1 1 1 1 1 adapter throughout - - aLoRA: user1 ... assistant1 ... user2 ... [gen] - routing: 0 0 0 0 0 1 1 1 base, then adapter - -So for aLoRA the "return to base" for earlier turns is achieved by PLACEMENT, not -by a base-reset token -- which is why ordinary aLoRA chat needs no such token. - -Coverage gap this closes: every other real-checkpoint multiswitch test composes -with ``--technology-filter lora`` (tests/hf/test_multi_switch_e2e.py) or with no -filter at all. Nothing composed an aLoRA-only checkpoint and checked that an -aLoRA-placed control token yields base-before / adapter-after routing on a real -model. The template's placement logic is unit-tested in -tests/composer/test_chat_template.py with no model attached, so the two halves -- -placement and routing -- were never joined: a layer correct in isolation, never -crossed end to end. aLoRA is the technology whose entire semantics depend on that -placement. - -Heavy: composes a real granite-4.1-3b with --technology-filter alora. Gated on -GRANITE_SWITCH_E2E_MODELS=1 like the other real-checkpoint suites. -""" - -import os -import subprocess -import sys -from pathlib import Path - -import pytest - -pytestmark = [ - pytest.mark.slow, - pytest.mark.requires_model, - pytest.mark.gpu, - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="composes a real ~3B alora checkpoint; set GRANITE_SWITCH_E2E_MODELS=1", - ), -] - -BASE_MODEL = "ibm-granite/granite-4.1-3b" -# granitelib-rag carries aLoRA intrinsics (answerability, citations, ...); the -# guardian/core libraries used by the LoRA e2e are filtered to lora there. -ADAPTER_REPOS = ["ibm-granite/granitelib-rag-r1.0"] - -_E2E_ROOT = Path(os.environ.get("GRANITE_SWITCH_E2E_DIR", "/tmp/granite_switch_e2e")) - - -def _compose_alora(): - """Compose (or warm-reuse) an aLoRA-only multi checkpoint.""" - out_dir = _E2E_ROOT / "multi-alora" - if (out_dir / "config.json").exists(): - print(f"warm-reuse {out_dir}", file=sys.stderr) - return out_dir - out_dir.mkdir(parents=True, exist_ok=True) - cmd = [ - sys.executable, - "-m", - "granite_switch.composer.compose_granite_switch", - "--base-model", - BASE_MODEL, - *[arg for r in ADAPTER_REPOS for arg in ("--adapters", r)], - "--technology-filter", - "alora", - "--output", - str(out_dir), - ] - print("composing:", " ".join(cmd), file=sys.stderr) - r = subprocess.run(cmd, capture_output=True, text=True, timeout=7200) - if r.returncode != 0: - pytest.fail( - f"alora compose failed (exit {r.returncode})\n" - f"--- stdout ---\n{r.stdout[-3000:]}\n--- stderr ---\n{r.stderr[-3000:]}", - pytrace=False, - ) - return out_dir - - -@pytest.fixture(scope="module") -def alora_model(): - """(model, config, tokenizer, adapter_names) for an aLoRA-only checkpoint.""" - from transformers import AutoTokenizer - - from granite_switch.config import GraniteSwitchConfig - from granite_switch.hf import GraniteSwitchForCausalLM - from granite_switch.hf.switch import MultiSwitch - - out_dir = _compose_alora() - config = GraniteSwitchConfig.from_pretrained(out_dir) - tok = AutoTokenizer.from_pretrained(out_dir) - model = GraniteSwitchForCausalLM.from_pretrained(out_dir).eval() - assert isinstance(model.model.switch, MultiSwitch) - names = list(getattr(config, "adapter_names", []) or []) - assert names, "composed config has no adapter_names" - print(f"\n alora checkpoint: {len(names)} adapters: {names}", file=sys.stderr) - return model, config, tok, names - - -def _ctrl_positions(ids, atoks): - ctrl = set(int(t) for t in atoks) - return [i for i, t in enumerate(ids) if int(t) in ctrl] - - -def _render(tok, question, adapter_name): - """Render with the adapter requested by name (the kwarg is adapter_name).""" - return tok.apply_chat_template( - [{"role": "user", "content": question}], - tokenize=False, - add_generation_prompt=True, - adapter_name=adapter_name, - ) - - -class TestALoRAComposition: - """The compose step must actually produce aLoRA adapters, not silently none.""" - - def test_alora_adapters_present(self, alora_model): - """--technology-filter alora yielded at least one adapter. - - Non-vacuity guard: if the filter matched nothing the compose would produce - zero adapters and every routing assertion below would be meaningless. - """ - _model, config, _tok, names = alora_model - assert config.num_adapters >= 1, ( - f"alora compose produced num_adapters={config.num_adapters}; the " - "technology filter matched nothing, so the routing tests would be vacuous" - ) - assert len(config.adapter_token_ids) == config.num_adapters, ( - "expected one control token per adapter (no base-reset slot); got " - f"{len(config.adapter_token_ids)} tokens for {config.num_adapters} adapters" - ) - - def test_template_carries_alora_invocation_text(self, alora_model): - """The template must know each aLoRA adapter's invocation text. - - aLoRA placement works by locating the invocation sequence in the user - message; without invocation_text in the adapter_map the template falls back - to the generation-prompt path, which is a different routing shape. - """ - _model, _config, tok, names = alora_model - template = tok.chat_template or "" - assert "invocation_text" in template, ( - "the composed chat template has no invocation_text entries, so no " - "adapter was treated as aLoRA -- placement would use the LoRA/fallback path" - ) - - -class TestALoRARouting: - """aLoRA routing shape: base before the control token, adapter at and after.""" - - def test_base_before_adapter_after(self, alora_model): - """The defining aLoRA property, on a real model. - - This is what no existing test covered: the template places the control - token, and the switch must then route base for everything before it and the - adapter from it onward. - """ - import torch - - model, config, tok, names = alora_model - rendered = _render(tok, "Is this answerable from the context?", names[0]) - ids = tok(rendered, add_special_tokens=False)["input_ids"] - pos = _ctrl_positions(ids, config.adapter_token_ids) - assert pos, ( - f"no control token in the rendered aLoRA prompt for {names[0]!r}; " - f"rendered:\n{rendered[:400]!r}" - ) - - with torch.no_grad(): - model(input_ids=torch.tensor([ids])) - route = model.model._last_adapter_indices[0].tolist() - - first = pos[0] - assert all(v == 0 for v in route[:first]), ( - f"aLoRA must be BASE before the control token at {first}; " - f"got {sorted(set(route[:first]))} over positions 0..{first - 1}" - ) - assert route[first] != 0, ( - f"the control token's own position {first} routed to base" - ) - assert all(v == route[first] for v in route[first:]), ( - f"the adapter must hold from {first} to the end; got " - f"{sorted(set(route[first:]))}" - ) - - def test_control_token_is_not_at_sequence_start(self, alora_model): - """aLoRA placement must differ from LoRA's sequence-start placement. - - If the token landed at index 0 the routing shape would be LoRA's (adapter - throughout) and the test above would pass while proving nothing about aLoRA. - """ - _model, config, tok, names = alora_model - ids = tok( - _render(tok, "Is this answerable?", names[0]), add_special_tokens=False - )["input_ids"] - pos = _ctrl_positions(ids, config.adapter_token_ids) - assert pos, "no control token rendered" - assert pos[0] > 0, ( - "the aLoRA control token landed at index 0, which is the LoRA " - "sequence-start placement -- the base-before-adapter assertion above " - "would then be vacuous" - ) - - def test_each_adapter_routes_to_its_own_index(self, alora_model): - """Different aLoRA adapters must select different expert ids.""" - import torch - - model, config, tok, names = alora_model - seen = {} - for name in names[:3]: - ids = tok( - _render(tok, "Is this answerable?", name), add_special_tokens=False - )["input_ids"] - pos = _ctrl_positions(ids, config.adapter_token_ids) - if not pos: - continue - with torch.no_grad(): - model(input_ids=torch.tensor([ids])) - seen[name] = model.model._last_adapter_indices[0].tolist()[pos[0]] - assert len(seen) >= 2, f"needed >=2 renderable aLoRA adapters, got {seen}" - assert len(set(seen.values())) == len(seen), ( - f"different aLoRA adapters routed to the SAME expert id: {seen}" - ) - - def test_alora_prompt_generates(self, alora_model): - """An aLoRA prompt must generate, with the adapter still active at decode.""" - import torch - - model, config, tok, names = alora_model - ids_list = tok( - _render(tok, "Is this answerable from the context?", names[0]), - add_special_tokens=False, - )["input_ids"] - ids = torch.tensor([ids_list]) - with torch.no_grad(): - out = model.generate(ids, max_new_tokens=8, do_sample=False) - assert out.shape[1] > ids.shape[1], "aLoRA prompt generated nothing" - route = model.model._last_adapter_indices[0].tolist() - assert route[-1] != 0, ( - f"the adapter was lost during decode; routing tail {route[-6:]}" - ) - print( - f"\n alora generated: " - f"{tok.decode(out[0][ids.shape[1] :], skip_special_tokens=True).strip()[:110]!r}", - file=sys.stderr, - ) - - -class TestTwoALoRAAdaptersInOneSequence: - """Two aLoRA adapters active in ONE sequence -- the case MultiSwitch exists for. - - The template renders one adapter per call, so nothing above puts two aLoRA - control tokens in the same sequence. But that is precisely the shape MultiSwitch - was built for and the shape SingleSwitch cannot do: SingleSwitch's +/-gain - attention AVERAGES competing control tokens, so two adapters in one sequence - mis-route. MultiSwitch takes the most recent exactly (latest-wins). - - Real flows that produce it: an agentic loop that judges the same context twice - (answerability, then certainty), or a multi-turn conversation whose earlier - turns are replayed verbatim with their control tokens still in the text. - - Built by concatenating two per-adapter renders, which is what such a flow - yields -- not by hand-assembling ids, so the placement is still the template's. - """ - - def _two_turn_ids(self, tok, config, names): - """Render turn 1 with names[0] and turn 2 with names[1]; concatenate.""" - r1 = _render(tok, "Is this answerable from the context?", names[0]) - r2 = _render(tok, "How certain are you about that?", names[1]) - ids1 = tok(r1, add_special_tokens=False)["input_ids"] - ids2 = tok(r2, add_special_tokens=False)["input_ids"] - joined = ids1 + ids2 - pos = _ctrl_positions(joined, config.adapter_token_ids) - return joined, pos, len(ids1) - - def test_two_alora_tokens_present(self, alora_model): - """Non-vacuity: the concatenation really carries TWO control tokens. - - If it carried one (or zero) the latest-wins assertion below would pass - without ever exercising a transition. - """ - _model, config, tok, names = alora_model - if len(names) < 2: - pytest.skip(f"needs >=2 alora adapters, got {names}") - _joined, pos, _split = self._two_turn_ids(tok, config, names) - assert len(pos) >= 2, ( - f"expected two aLoRA control tokens in the concatenated sequence, " - f"found {len(pos)} at {pos} -- the latest-wins test would be vacuous" - ) - - def test_latest_wins_between_two_aloras(self, alora_model): - """Adapter A holds until B's token, then B holds to the end. - - This is the property SingleSwitch gets wrong by averaging and MultiSwitch - gets right, now on a real composed aLoRA checkpoint rather than hand-built - token ids. - """ - import torch - - model, config, tok, names = alora_model - if len(names) < 2: - pytest.skip(f"needs >=2 alora adapters, got {names}") - joined, pos, _split = self._two_turn_ids(tok, config, names) - if len(pos) < 2: - pytest.skip(f"only {len(pos)} control token(s) rendered") - - with torch.no_grad(): - model(input_ids=torch.tensor([joined])) - route = model.model._last_adapter_indices[0].tolist() - - i_a, i_b = pos[0], pos[1] - exp_a, exp_b = route[i_a], route[i_b] - - assert all(v == 0 for v in route[:i_a]), ( - f"base expected before the first aLoRA token at {i_a}; " - f"got {sorted(set(route[:i_a]))}" - ) - assert exp_a != 0 and exp_b != 0, ( - f"a control token routed to base: pos{i_a}->{exp_a}, pos{i_b}->{exp_b}" - ) - assert exp_a != exp_b, ( - f"both aLoRA tokens selected the SAME expert ({exp_a}); the second " - "adapter did not take over, so latest-wins is not being exercised" - ) - assert all(v == exp_a for v in route[i_a:i_b]), ( - f"adapter A ({exp_a}) must hold from {i_a} to {i_b}; " - f"got {sorted(set(route[i_a:i_b]))}" - ) - assert all(v == exp_b for v in route[i_b:]), ( - f"adapter B ({exp_b}) must hold from {i_b} to the end; " - f"got {sorted(set(route[i_b:]))}" - ) - - def test_two_alora_sequence_generates(self, alora_model): - """The two-adapter sequence must generate, with B still active at decode.""" - import torch - - model, config, tok, names = alora_model - if len(names) < 2: - pytest.skip(f"needs >=2 alora adapters, got {names}") - joined, pos, _split = self._two_turn_ids(tok, config, names) - if len(pos) < 2: - pytest.skip(f"only {len(pos)} control token(s) rendered") - ids = torch.tensor([joined]) - with torch.no_grad(): - out = model.generate(ids, max_new_tokens=8, do_sample=False) - assert out.shape[1] > ids.shape[1], "two-adapter sequence generated nothing" - route = model.model._last_adapter_indices[0].tolist() - assert route[-1] != 0, ( - f"the second adapter was lost during decode; tail {route[-6:]}" - ) diff --git a/tests/hf/test_multi_switch_e2e.py b/tests/hf/test_multi_switch_e2e.py deleted file mode 100644 index 2e18eaa4..00000000 --- a/tests/hf/test_multi_switch_e2e.py +++ /dev/null @@ -1,287 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""End-to-end MultiSwitch tests through a REAL composed GraniteSwitch model. - -Composes an *actual* granite-4.1-3b checkpoint (MultiSwitch is the only engine) -and runs the full ``GraniteSwitchForCausalLM.forward`` on multi-transition token -sequences, asserting ``model.model._last_adapter_indices`` matches the expected -latest-wins routing. - -This proves the full chain persists and rebuilds correctly: - - compose (-> config.json) - -> from_pretrained -> create_switch -> MultiSwitch - -> model.forward -> _last_adapter_indices - -Heavy: composes a ~3B checkpoint and loads it. Marked slow / requires_model / -gpu, and skipped unless ``GRANITE_SWITCH_E2E_MODELS=1`` is set (composing -downloads the base model + adapters). The module-scoped fixture warm-reuses an -already-composed output dir when its ``config.json`` exists, so re-runs skip the -expensive recompose. - -Compose command (mirrors the task runbook):: - - python -m granite_switch.composer.compose_granite_switch \\ - --base-model ibm-granite/granite-4.1-3b \\ - --adapters ibm-granite/granitelib-guardian-r1.0 \\ - ibm-granite/granitelib-core-r1.0 \\ - --technology-filter lora \\ - --output -""" - -import os -import subprocess -import sys -from pathlib import Path - -import pytest - -pytestmark = [ - pytest.mark.slow, - pytest.mark.requires_model, - pytest.mark.gpu, - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="composes a real ~3B checkpoint; set GRANITE_SWITCH_E2E_MODELS=1 to run", - ), -] - -SWITCH_TYPES = ["multi"] - -BASE_MODEL = "ibm-granite/granite-4.1-3b" -ADAPTER_REPOS = [ - "ibm-granite/granitelib-guardian-r1.0", - "ibm-granite/granitelib-core-r1.0", -] - -# Where composed checkpoints are cached. Override with GRANITE_SWITCH_E2E_DIR. -_E2E_ROOT = Path(os.environ.get("GRANITE_SWITCH_E2E_DIR", "/tmp/granite_switch_e2e")) - - -def _compose(switch_type): - """Compose (or warm-reuse) a real checkpoint for ``switch_type``. - - Returns the output directory. Skips the recompose when config.json already - exists in the target dir (warm reuse). - """ - out_dir = _E2E_ROOT / switch_type - if (out_dir / "config.json").exists(): - return out_dir - - out_dir.mkdir(parents=True, exist_ok=True) - cmd = [ - sys.executable, - "-m", - "granite_switch.composer.compose_granite_switch", - "--base-model", - BASE_MODEL, - "--adapters", - *ADAPTER_REPOS, - "--technology-filter", - "lora", - "--output", - str(out_dir), - ] - result = subprocess.run(cmd, capture_output=True, text=True) - if result.returncode != 0: - raise RuntimeError( - f"compose failed for {switch_type}:\n" - f"--- stdout ---\n{result.stdout[-3000:]}\n" - f"--- stderr ---\n{result.stderr[-3000:]}" - ) - assert (out_dir / "config.json").exists(), "compose produced no config.json" - return out_dir - - -@pytest.fixture(scope="module", params=SWITCH_TYPES, ids=lambda t: t) -def composed_model(request): - """Module-scoped composed GraniteSwitch model. - - Confirms ``from_pretrained`` rebuilds a real MultiSwitch engine (the only - engine) from the composed checkpoint. - """ - from granite_switch.config import GraniteSwitchConfig - from granite_switch.hf import GraniteSwitchForCausalLM - - switch_type = request.param - out_dir = _compose(switch_type) - - config = GraniteSwitchConfig.from_pretrained(out_dir) - - model = GraniteSwitchForCausalLM.from_pretrained(out_dir).eval() - # Confirm from_pretrained rebuilt the coded-memory engine. - from granite_switch.hf.switch import MultiSwitch - - assert isinstance(model.model.switch, MultiSwitch), ( - f"from_pretrained built {type(model.model.switch).__name__}, " - f"expected MultiSwitch" - ) - return model, config, switch_type - - -def _control_ids(config): - """Return (A_TOK, B_TOK): control tokens for adapters 1 and 2. - - Real composed configs use the no-base-slot layout: adapter_token_ids[k] - fires adapter k+1. Two lora adapters give exactly two control tokens. - """ - atoks = config.adapter_token_ids - assert len(atoks) >= 2, f"need >= 2 adapters, got {len(atoks)}" - return atoks[0], atoks[1] # -> adapter 1, adapter 2 - - -def _run_and_get_indices(model, seq): - import torch - - input_ids = torch.tensor([seq]) - with torch.no_grad(): - model(input_ids=input_ids) - return model.model._last_adapter_indices[0].tolist() - - -# TEXT_TOKEN: any non-control id. 50 is far below the appended control ids. -TEXT = 50 - - -class TestE2EMultiTransition: - """Full-model routing matches the latest-wins expectation.""" - - def test_base_then_A_then_B(self, composed_model): - """base -> A -> B: [T,A,T,B,T] -> [0,1,1,2,2].""" - model, config, _ = composed_model - a, b = _control_ids(config) - result = _run_and_get_indices(model, [TEXT, a, TEXT, b, TEXT]) - assert result == [0, 1, 1, 2, 2] - - def test_higher_then_lower_A2_then_B1(self, composed_model): - """A(2) -> B(1) latest-wins: [B,T,A,T] -> [2,2,1,1]. - - The case SingleSwitch mis-routes (its softmax averages the two control - values); the multi engines take the most recent, so this is exact. - """ - model, config, _ = composed_model - a, b = _control_ids(config) - result = _run_and_get_indices(model, [b, TEXT, a, TEXT]) - assert result == [2, 2, 1, 1] - - def test_sticky_single_transition(self, composed_model): - """One control token persists through a long text tail.""" - model, config, _ = composed_model - a, _b = _control_ids(config) - seq = [TEXT, TEXT, a] + [TEXT] * 8 - result = _run_and_get_indices(model, seq) - assert result[:2] == [0, 0] - assert all(v == 1 for v in result[2:]) - - def test_all_base(self, composed_model): - """No control tokens -> every position is base (0).""" - model, _config, _ = composed_model - result = _run_and_get_indices(model, [TEXT] * 12) - assert all(v == 0 for v in result) - - def test_control_at_position_zero(self, composed_model): - """Control token at pos 0 -> adapter active from the start.""" - model, config, _ = composed_model - a, _b = _control_ids(config) - result = _run_and_get_indices(model, [a, TEXT, TEXT, TEXT]) - assert all(v == 1 for v in result) - - def test_three_transitions(self, composed_model): - """A -> B -> A latest-wins across three transitions.""" - model, config, _ = composed_model - a, b = _control_ids(config) - result = _run_and_get_indices(model, [TEXT, a, TEXT, b, TEXT, a, TEXT]) - assert result == [0, 1, 1, 2, 2, 1, 1] - - -class TestE2ERealCheckpointGenerate: - """Gates that only a REAL composed checkpoint can exercise. - - The routing tests above run a single ``forward`` and read - ``_last_adapter_indices``. Three separate production bugs lived on paths that - such a test cannot reach, and each survived the whole suite: - - 1. ``codebook`` / ``control_to_substitute_lut`` were registered - ``persistent=False``, so ``from_pretrained`` returned them as ALL ZEROS - (a zeroed codebook makes the retrieval softmax uniform, i.e. it averages - adapters). Only visible after a real save/load. - 2. ``positions`` was never passed to the vLLM switch, so only the first - request in a flat batch got a counting anchor. Only visible under real - batching. - 3. The switch built its causal mask as ``q_len x q_len`` while its heads - attend over the whole KV cache, so every decode step passed a mis-shaped - bias and ``generate()`` raised. Only visible when actually generating. - - These tests close (1) and (3) on the real checkpoint. (2) is covered by the - vLLM batching tests. - """ - - def test_real_checkpoint_buffers_are_valid(self, composed_model): - """The composed checkpoint's switch buffers must load intact. - - Guards bug (1) on the real artifact rather than a synthetic round trip: - a unit-norm codebook and a LUT that still uses -1 as its - "not a control token" sentinel. - """ - import torch - - model, config, _ = composed_model - sw = model.model.switch - - cb = sw.codebook.float() - assert not torch.all(cb == 0), ( - "composed checkpoint loaded an ALL-ZERO codebook -- the buffer is not " - "persistent, so the memory softmax will average adapters instead of " - "selecting one" - ) - norms = cb.norm(dim=1) - torch.testing.assert_close(norms, torch.ones_like(norms), atol=1e-4, rtol=0) - - lut = sw.control_to_substitute_lut - assert lut is not None, "composed checkpoint has no substitute LUT" - assert not torch.all(lut == 0), ( - "substitute LUT loaded ALL ZEROS -- token exchange would rewrite every " - "token id to 0 (the 'not a control' sentinel is -1)" - ) - for ctrl, sub in zip( - config.adapter_token_ids, config.adapter_substitute_token_ids - ): - assert int(lut[ctrl]) == int(sub), ( - f"LUT maps control {ctrl} -> {int(lut[ctrl])}, expected {sub}" - ) - - def test_real_checkpoint_generates(self, composed_model): - """``generate()`` must work on the real checkpoint. - - Guards bug (3). Prefill has ``q_len == kv_len`` so a forward-only test - cannot see the mask-shape defect; the first decode step is where it fired. - """ - import torch - - model, config, _ = composed_model - a, _b = _control_ids(config) - ids = torch.tensor([[TEXT, TEXT, a, TEXT]]) - with torch.no_grad(): - out = model.generate(ids, max_new_tokens=5, do_sample=False) - assert out.shape[1] == ids.shape[1] + 5, ( - f"generate produced {out.shape[1]} tokens, expected {ids.shape[1] + 5}" - ) - - def test_real_checkpoint_generate_carries_adapter(self, composed_model): - """The adapter set before generation stays active through decode. - - This is the latest-wins contract applied to generated tokens: a control - token in the prompt must keep its adapter active while the model produces - new tokens, otherwise multi-turn serving silently reverts to base. - """ - import torch - - model, config, _ = composed_model - _a, b = _control_ids(config) - ids = torch.tensor([[TEXT, b, TEXT]]) - with torch.no_grad(): - model.generate(ids, max_new_tokens=4, do_sample=False) - # The final forward is a decode step; routing must still be adapter 2. - route = model.model._last_adapter_indices[0].tolist() - assert all(v == 2 for v in route), ( - f"decode routing {route} lost the adapter set by the control token" - ) diff --git a/tests/hf/test_multi_switch_mixed_tech.py b/tests/hf/test_multi_switch_mixed_tech.py deleted file mode 100644 index 2cb51379..00000000 --- a/tests/hf/test_multi_switch_mixed_tech.py +++ /dev/null @@ -1,346 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""MultiSwitch with LoRA and aLoRA adapters in the SAME checkpoint. - -Every other real-checkpoint suite composes exactly one technology: - - test_multi_switch_e2e.py --technology-filter lora - test_multi_switch_alora.py --technology-filter alora - -Nothing composes with NO filter -- which is the composer's default and the most -likely real deployment: one checkpoint carrying both kinds. - -Why that matters. The chat template applies technology-SPECIFIC placement: - - * LoRA -> control token at the sequence START, plus skip_next_role_marker so the - following role marker is suppressed (avoids two identical embeddings - back-to-back after the runtime swap). - * aLoRA -> control token immediately BEFORE the invocation text, plus a - first-character drop for the same reason. - -In a mixed checkpoint the template's adapter_map holds both types and the routing -shape depends on which adapter you name. A LoRA adapter taking the aLoRA path (or -the reverse) would produce the wrong routing shape while still "working" -- two -layers each correct in isolation and never crossed end to end. - -Also covers checkpoint re-save stability (see TestResaveStability): persistent -buffers can silently vanish on load, so a second save/load round trip is worth -asserting rather than assuming. - -Heavy: composes a real granite-4.1-3b with NO technology filter. Gated on -GRANITE_SWITCH_E2E_MODELS=1. -""" - -import os -import subprocess -import sys -from pathlib import Path - -import pytest - -pytestmark = [ - pytest.mark.slow, - pytest.mark.requires_model, - pytest.mark.gpu, - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="composes a real ~3B mixed checkpoint; set GRANITE_SWITCH_E2E_MODELS=1", - ), -] - -BASE_MODEL = "ibm-granite/granite-4.1-3b" -# rag carries aLoRA intrinsics; guardian/core carry LoRA ones. With no filter the -# compose should yield BOTH technologies in one checkpoint. -ADAPTER_REPOS = [ - "ibm-granite/granitelib-rag-r1.0", - "ibm-granite/granitelib-guardian-r1.0", -] - -_E2E_ROOT = Path(os.environ.get("GRANITE_SWITCH_E2E_DIR", "/tmp/granite_switch_e2e")) - - -def _compose_mixed(): - """Compose (or warm-reuse) a checkpoint with NO technology filter.""" - out_dir = _E2E_ROOT / "multi-mixed" - if (out_dir / "config.json").exists(): - print(f"warm-reuse {out_dir}", file=sys.stderr) - return out_dir - out_dir.mkdir(parents=True, exist_ok=True) - cmd = [ - sys.executable, - "-m", - "granite_switch.composer.compose_granite_switch", - "--base-model", - BASE_MODEL, - *[arg for r in ADAPTER_REPOS for arg in ("--adapters", r)], - # deliberately NO --technology-filter - "--output", - str(out_dir), - ] - print("composing (mixed):", " ".join(cmd), file=sys.stderr) - r = subprocess.run(cmd, capture_output=True, text=True, timeout=7200) - if r.returncode != 0: - pytest.fail( - f"mixed compose failed (exit {r.returncode})\n" - f"--- stdout ---\n{r.stdout[-3000:]}\n--- stderr ---\n{r.stderr[-3000:]}", - pytrace=False, - ) - return out_dir - - -@pytest.fixture(scope="module") -def mixed_model(): - """(model, config, tokenizer, out_dir) for a mixed-technology checkpoint.""" - from transformers import AutoTokenizer - - from granite_switch.config import GraniteSwitchConfig - from granite_switch.hf import GraniteSwitchForCausalLM - from granite_switch.hf.switch import MultiSwitch - - out_dir = _compose_mixed() - config = GraniteSwitchConfig.from_pretrained(out_dir) - tok = AutoTokenizer.from_pretrained(out_dir) - model = GraniteSwitchForCausalLM.from_pretrained(out_dir).eval() - assert isinstance(model.model.switch, MultiSwitch) - print( - f"\n mixed checkpoint: {config.num_adapters} adapters: " - f"{list(getattr(config, 'adapter_names', []) or [])}", - file=sys.stderr, - ) - return model, config, tok, out_dir - - -def _template_types(tokenizer): - """Parse {adapter_name: technology} out of the template's adapter_map.""" - import re - - tmpl = tokenizer.chat_template or "" - return dict( - re.findall(r"'([^']+)':\s*\{'token':\s*'[^']*',\s*'type':\s*'([^']+)'", tmpl) - ) - - -def _ctrl_positions(ids, atoks): - ctrl = set(int(t) for t in atoks) - return [i for i, t in enumerate(ids) if int(t) in ctrl] - - -def _render(tok, question, adapter_name): - return tok.apply_chat_template( - [{"role": "user", "content": question}], - tokenize=False, - add_generation_prompt=True, - adapter_name=adapter_name, - ) - - -class TestMixedComposition: - """The unfiltered compose must really contain BOTH technologies.""" - - def test_unfiltered_compose_prefers_alora(self, mixed_model): - """An unfiltered compose is aLoRA-only BY DESIGN, not by accident. - - My original premise here was wrong: I assumed no --technology-filter would - yield a checkpoint carrying both technologies. It does not, and the reason is - deliberate. When the granitelib libraries publish an adapter under both an - `alora/` and a `lora/` subtree, discovery prefers aLoRA: - - adapter_discovery.py:331 if "alora" in technologies: return "alora" - adapter_discovery.py:77 if tech == "alora" and existing_tech == "lora": - ... replacing lora - - So the real behaviour is: unfiltered -> aLoRA wins for every dual-published - adapter. That is worth pinning, because a silent flip to LoRA preference - would change the routing SHAPE of every unfiltered checkpoint - (adapter-throughout instead of base-then-adapter) without changing any - adapter name or count. - - A genuinely mixed checkpoint needs libraries whose adapters are published in - only one technology each; the classes below therefore skip rather than fail - when a technology is absent. - """ - _model, _config, tok, _d = mixed_model - types = _template_types(tok) - kinds = set(types.values()) - print(f"\n adapter technologies: {types}", file=sys.stderr) - assert kinds, f"no adapter types found in the template: {types}" - assert "alora" in kinds, ( - f"an unfiltered compose of {ADAPTER_REPOS} should prefer aLoRA for " - f"dual-published adapters; got {kinds}. If discovery's preference " - "changed, every unfiltered checkpoint's routing shape changed with it." - ) - - def test_one_control_token_per_adapter(self, mixed_model): - """Token count must still track adapter count across mixed technologies.""" - _model, config, _tok, _d = mixed_model - assert len(config.adapter_token_ids) == config.num_adapters, ( - f"{len(config.adapter_token_ids)} control tokens for " - f"{config.num_adapters} adapters" - ) - assert len(set(config.adapter_token_ids)) == len(config.adapter_token_ids), ( - "duplicate control token ids in a mixed checkpoint" - ) - - -class TestMixedPlacementAndRouting: - """Each technology must keep its own placement and routing shape.""" - - def test_lora_adapter_routes_from_sequence_start(self, mixed_model): - """A LoRA-typed adapter puts its token at the start -> adapter throughout.""" - import torch - - model, config, tok, _d = mixed_model - types = _template_types(tok) - lora_names = [n for n, t in types.items() if t == "lora"] - if not lora_names: - pytest.skip("no lora-typed adapter in this checkpoint") - ids = tok( - _render(tok, "Summarize the context.", lora_names[0]), - add_special_tokens=False, - )["input_ids"] - pos = _ctrl_positions(ids, config.adapter_token_ids) - assert pos, f"no control token rendered for lora adapter {lora_names[0]!r}" - assert pos[0] == 0, ( - f"a LoRA control token must land at index 0 (sequence start); got {pos[0]}" - ) - with torch.no_grad(): - model(input_ids=torch.tensor([ids])) - route = model.model._last_adapter_indices[0].tolist() - assert all(v == route[0] for v in route) and route[0] != 0, ( - f"LoRA routing must be one adapter throughout; got {sorted(set(route))}" - ) - - def test_alora_adapter_routes_base_then_adapter(self, mixed_model): - """An aLoRA-typed adapter in the SAME checkpoint keeps aLoRA's shape.""" - import torch - - model, config, tok, _d = mixed_model - types = _template_types(tok) - alora_names = [n for n, t in types.items() if t == "alora"] - if not alora_names: - pytest.skip("no alora-typed adapter in this checkpoint") - ids = tok( - _render(tok, "Is this answerable from the context?", alora_names[0]), - add_special_tokens=False, - )["input_ids"] - pos = _ctrl_positions(ids, config.adapter_token_ids) - assert pos, f"no control token rendered for alora adapter {alora_names[0]!r}" - assert pos[0] > 0, ( - f"an aLoRA control token must NOT be at index 0 (that is LoRA's " - f"placement); got {pos[0]}" - ) - with torch.no_grad(): - model(input_ids=torch.tensor([ids])) - route = model.model._last_adapter_indices[0].tolist() - first = pos[0] - assert all(v == 0 for v in route[:first]), ( - f"aLoRA must be base before {first}; got {sorted(set(route[:first]))}" - ) - assert all(v == route[first] for v in route[first:]) and route[first] != 0, ( - f"aLoRA adapter must hold from {first} to the end; " - f"got {sorted(set(route[first:]))}" - ) - - def test_lora_and_alora_select_different_experts(self, mixed_model): - """The two technologies must map to distinct expert ids, not collide.""" - import torch - - model, config, tok, _d = mixed_model - types = _template_types(tok) - lora = [n for n, t in types.items() if t == "lora"] - alora = [n for n, t in types.items() if t == "alora"] - if not lora or not alora: - pytest.skip(f"need both technologies; got lora={lora} alora={alora}") - got = {} - for name in (lora[0], alora[0]): - ids = tok( - _render(tok, "Is this answerable?", name), add_special_tokens=False - )["input_ids"] - pos = _ctrl_positions(ids, config.adapter_token_ids) - if not pos: - continue - with torch.no_grad(): - model(input_ids=torch.tensor([ids])) - got[name] = model.model._last_adapter_indices[0].tolist()[pos[0]] - if len(got) < 2: - pytest.skip(f"could not render both technologies: {got}") - assert len(set(got.values())) == 2, ( - f"a LoRA and an aLoRA adapter routed to the SAME expert id: {got}" - ) - - def test_mixed_checkpoint_generates(self, mixed_model): - """Generation works for both technologies from one checkpoint.""" - import torch - - model, _config, tok, _d = mixed_model - types = _template_types(tok) - for kind in ("lora", "alora"): - names = [n for n, t in types.items() if t == kind] - if not names: - continue - ids = torch.tensor( - [ - tok( - _render(tok, "Is this answerable?", names[0]), - add_special_tokens=False, - )["input_ids"] - ] - ) - with torch.no_grad(): - out = model.generate(ids, max_new_tokens=8, do_sample=False) - assert out.shape[1] > ids.shape[1], f"{kind} adapter generated nothing" - print( - f"\n {kind} ({names[0]}): " - f"{tok.decode(out[0][ids.shape[1] :], skip_special_tokens=True).strip()[:90]!r}", - file=sys.stderr, - ) - - -class TestResaveStability: - """A composed checkpoint must survive being re-saved and reloaded. - - The codebook and substitute LUT are persistent buffers that can silently - vanish on ``from_pretrained``. ``test_multi_switch_buffers.py`` covers ONE - round trip on a synthetic model; this covers a second round trip on the real - composed artifact, where a re-save could drop or alter a buffer with nobody - noticing. - """ - - def test_resave_preserves_buffers_and_routing(self, mixed_model, tmp_path): - import torch - - from granite_switch.hf import GraniteSwitchForCausalLM - - model, config, tok, _d = mixed_model - types = _template_types(tok) - name = next(iter(types)) - ids_list = tok( - _render(tok, "Is this answerable?", name), add_special_tokens=False - )["input_ids"] - ids = torch.tensor([ids_list]) - - with torch.no_grad(): - model(input_ids=ids) - route_before = model.model._last_adapter_indices[0].tolist() - - out = tmp_path / "resaved" - model.save_pretrained(out) - tok.save_pretrained(out) - reloaded = GraniteSwitchForCausalLM.from_pretrained(out).eval() - sw = reloaded.model.switch - - cb = sw.codebook.float() - assert not torch.all(cb == 0), "re-saved checkpoint lost its codebook" - norms = cb.norm(dim=1) - torch.testing.assert_close(norms, torch.ones_like(norms), atol=1e-4, rtol=0) - lut = sw.control_to_substitute_lut - assert lut is not None and not torch.all(lut == 0), ( - "re-saved checkpoint lost its substitute LUT" - ) - - with torch.no_grad(): - reloaded(input_ids=ids) - route_after = reloaded.model._last_adapter_indices[0].tolist() - assert route_after == route_before, ( - "routing changed after a save/load round trip:\n" - f" before: {route_before}\n after : {route_after}" - ) diff --git a/tests/hf/test_multi_switch_real_checkpoint.py b/tests/hf/test_multi_switch_real_checkpoint.py new file mode 100644 index 00000000..1cd93e5b --- /dev/null +++ b/tests/hf/test_multi_switch_real_checkpoint.py @@ -0,0 +1,771 @@ +# SPDX-License-Identifier: Apache-2.0 +"""MultiSwitch routing on REAL composed granite-4.1-3b checkpoints (HF backend). + +Every other HF MultiSwitch test uses a mock config and hand-built token ids. This +module composes real checkpoints and drives the full +``GraniteSwitchForCausalLM`` forward / ``generate``, asserting +``model.model._last_adapter_indices`` against latest-wins routing: + + compose (-> config.json) + -> from_pretrained -> create_switch -> MultiSwitch + -> model.forward / generate -> _last_adapter_indices + +Three checkpoints, each composed once under ``$GRANITE_SWITCH_E2E_DIR/`` and +warm-reused when its ``config.json`` exists: + + multi LoRA-only (guardian + core): raw multi-transition routing, buffer + integrity, generate, chat-template placement, real multi-turn, + long prompts + multi-alora aLoRA-only (rag): base-before / adapter-after placement, two + aLoRAs in one sequence + multi-mixed no technology filter (rag + guardian): per-technology placement + in one checkpoint, re-save stability + +The LoRA/aLoRA difference is entirely WHERE the chat template puts the control +token, and that changes the routing shape: + + LoRA: user1 ... assistant1 ... user2 ... [gen] + routing: 1 1 1 1 1 1 1 1 adapter throughout + + aLoRA: user1 ... assistant1 ... user2 ... [gen] + routing: 0 0 0 0 0 1 1 1 base, then adapter + +Heavy: marked slow / requires_model / gpu / release, so it runs only under +``pytest -m release`` (composing downloads the base model + adapters). +""" + +import gc +import os +import re +import subprocess +import sys +from pathlib import Path + +import pytest + +pytestmark = [ + pytest.mark.slow, + pytest.mark.requires_model, + pytest.mark.gpu, + pytest.mark.release, +] + +BASE_MODEL = "ibm-granite/granite-4.1-3b" + +# Where composed checkpoints are cached. Override with GRANITE_SWITCH_E2E_DIR. +_E2E_ROOT = Path(os.environ.get("GRANITE_SWITCH_E2E_DIR", "/tmp/granite_switch_e2e")) + +# checkpoint name -> (adapter repos, technology filter or None) +_CHECKPOINTS = { + "multi": ( + ["ibm-granite/granitelib-guardian-r1.0", "ibm-granite/granitelib-core-r1.0"], + "lora", + ), + "multi-alora": (["ibm-granite/granitelib-rag-r1.0"], "alora"), + # rag carries aLoRA intrinsics; guardian carries LoRA ones. Deliberately no + # filter: that is the composer's default. + "multi-mixed": ( + ["ibm-granite/granitelib-rag-r1.0", "ibm-granite/granitelib-guardian-r1.0"], + None, + ), +} + + +def _compose(name): + """Compose (or warm-reuse) checkpoint ``name``; return its directory. + + Also used by tests/integration/test_multi_switch_vllm_generate.py so both + suites share one artifact. + """ + repos, tech_filter = _CHECKPOINTS[name] + out_dir = _E2E_ROOT / name + if (out_dir / "config.json").exists(): + print(f"warm-reuse {out_dir}", file=sys.stderr) + return out_dir + + out_dir.mkdir(parents=True, exist_ok=True) + cmd = [ + sys.executable, + "-m", + "granite_switch.composer.compose_granite_switch", + "--base-model", + BASE_MODEL, + # One flag, all repos: --adapters is nargs="*" with the default store + # action, so a repeated flag keeps only the LAST list. + "--adapters", + *repos, + ] + if tech_filter is not None: + cmd += ["--technology-filter", tech_filter] + cmd += ["--output", str(out_dir)] + print(f"composing ({name}):", " ".join(cmd), file=sys.stderr) + r = subprocess.run(cmd, capture_output=True, text=True, timeout=7200) + if r.returncode != 0: + pytest.fail( + f"{name} compose failed (exit {r.returncode})\n" + f"--- stdout ---\n{r.stdout[-3000:]}\n--- stderr ---\n{r.stderr[-3000:]}", + pytrace=False, + ) + assert (out_dir / "config.json").exists(), "compose produced no config.json" + return out_dir + + +# TEXT: any non-control id. 50 is far below the appended control ids. +TEXT = 50 + + +# The one checkpoint currently loaded, {name: (model, config, tokenizer)}. +_loaded = {} + + +def _load(name): + """(model, config, tokenizer) for a composed checkpoint, asserting MultiSwitch. + + Holds ONE ~3B model at a time: loading a different checkpoint frees the + previous one. The classes below are grouped by checkpoint, so in file order + each loads once. + """ + if name in _loaded: + return _loaded[name] + _loaded.clear() + gc.collect() + + from transformers import AutoTokenizer + + from granite_switch.config import GraniteSwitchConfig + from granite_switch.hf import GraniteSwitchForCausalLM + from granite_switch.hf.switch import MultiSwitch + + out_dir = _compose(name) + config = GraniteSwitchConfig.from_pretrained(out_dir) + tok = AutoTokenizer.from_pretrained(out_dir) + model = GraniteSwitchForCausalLM.from_pretrained(out_dir).eval() + assert isinstance(model.model.switch, MultiSwitch), ( + f"from_pretrained built {type(model.model.switch).__name__}, " + f"expected MultiSwitch" + ) + print( + f"\n {name} checkpoint: {config.num_adapters} adapters: " + f"{list(getattr(config, 'adapter_names', []) or [])}", + file=sys.stderr, + ) + _loaded[name] = (model, config, tok) + return _loaded[name] + + +# Function-scoped on purpose: the model is cached in _load, and a module-scoped +# fixture would keep all three alive until the module ends. +@pytest.fixture +def lora_model(): + return _load("multi") + + +@pytest.fixture +def alora_model(): + return _load("multi-alora") + + +@pytest.fixture +def mixed_model(): + return _load("multi-mixed") + + +def _control_ids(config): + """(A_TOK, B_TOK): control tokens for adapters 1 and 2. + + Real composed configs use the no-base-slot layout: adapter_token_ids[k] + fires adapter k+1. + """ + atoks = config.adapter_token_ids + assert len(atoks) >= 2, f"need >= 2 adapters, got {len(atoks)}" + return atoks[0], atoks[1] + + +def _route(model, ids): + """Run one forward over ``ids``; return the per-position adapter indices.""" + import torch + + with torch.no_grad(): + model(input_ids=torch.tensor([ids])) + return model.model._last_adapter_indices[0].tolist() + + +def _render(tok, question, adapter_name): + """Render a chat prompt with the adapter requested by name. + + The kwarg is ``adapter_name``. Jinja treats an unknown kwarg as + simply-not-defined, so a wrong name raises nothing and renders no control + token -- which is why the tests below assert a control token was rendered. + """ + return tok.apply_chat_template( + [{"role": "user", "content": question}], + tokenize=False, + add_generation_prompt=True, + adapter_name=adapter_name, + ) + + +def _render_ids(tok, question, adapter_name): + return tok(_render(tok, question, adapter_name), add_special_tokens=False)[ + "input_ids" + ] + + +def _ctrl_positions(ids, atoks): + """Indices in ``ids`` holding any adapter control token.""" + ctrl = set(int(t) for t in atoks) + return [i for i, t in enumerate(ids) if int(t) in ctrl] + + +def _template_types(tok): + """Parse {adapter_name: technology} out of the template's adapter_map.""" + tmpl = tok.chat_template or "" + return dict( + re.findall(r"'([^']+)':\s*\{'token':\s*'[^']*',\s*'type':\s*'([^']+)'", tmpl) + ) + + +def _assert_buffers_valid(switch): + """Codebook is unit-norm and nonzero; substitute LUT is present and nonzero.""" + import torch + + cb = switch.codebook.float() + assert not torch.all(cb == 0), ( + "checkpoint loaded an ALL-ZERO codebook -- the memory softmax will " + "average adapters instead of selecting one" + ) + norms = cb.norm(dim=1) + torch.testing.assert_close(norms, torch.ones_like(norms), atol=1e-4, rtol=0) + lut = switch.control_to_substitute_lut + assert lut is not None, "checkpoint has no substitute LUT" + assert not torch.all(lut == 0), ( + "substitute LUT loaded ALL ZEROS -- token exchange would rewrite every " + "token id to 0 (the 'not a control' sentinel is -1)" + ) + return lut + + +# ── lora: raw multi-transition routing ──────────────────────────────────────── + + +class TestMultiTransition: + """Full-model routing on hand-built ids matches latest-wins.""" + + def test_base_then_A_then_B(self, lora_model): + """[T,A,T,B,T] -> [0,1,1,2,2].""" + model, config, _ = lora_model + a, b = _control_ids(config) + assert _route(model, [TEXT, a, TEXT, b, TEXT]) == [0, 1, 1, 2, 2] + + def test_higher_then_lower(self, lora_model): + """[B,T,A,T] -> [2,2,1,1]: the most recent token wins, not the larger.""" + model, config, _ = lora_model + a, b = _control_ids(config) + assert _route(model, [b, TEXT, a, TEXT]) == [2, 2, 1, 1] + + def test_sticky_single_transition(self, lora_model): + """One control token persists through a long text tail.""" + model, config, _ = lora_model + a, _b = _control_ids(config) + result = _route(model, [TEXT, TEXT, a] + [TEXT] * 8) + assert result[:2] == [0, 0] + assert all(v == 1 for v in result[2:]) + + def test_all_base(self, lora_model): + """No control tokens -> every position is base (0).""" + model, _config, _ = lora_model + assert all(v == 0 for v in _route(model, [TEXT] * 12)) + + def test_control_at_position_zero(self, lora_model): + """Control token at pos 0 -> adapter active from the start.""" + model, config, _ = lora_model + a, _b = _control_ids(config) + assert all(v == 1 for v in _route(model, [a, TEXT, TEXT, TEXT])) + + def test_three_transitions(self, lora_model): + """A -> B -> A latest-wins across three transitions.""" + model, config, _ = lora_model + a, b = _control_ids(config) + result = _route(model, [TEXT, a, TEXT, b, TEXT, a, TEXT]) + assert result == [0, 1, 1, 2, 2, 1, 1] + + +# ── lora: paths only a real checkpoint reaches ──────────────────────────────── + + +class TestRealCheckpointGenerate: + """Bugs that survived every mock-config test: + + 1. ``codebook`` / ``control_to_substitute_lut`` registered + ``persistent=False``, so ``from_pretrained`` returned them as ALL ZEROS. + Only visible after a real save/load. + 2. The switch built its causal mask as ``q_len x q_len`` while its heads + attend over the whole KV cache, so the first decode step raised. Only + visible when actually generating. + """ + + def test_buffers_are_valid(self, lora_model): + model, config, _ = lora_model + lut = _assert_buffers_valid(model.model.switch) + for ctrl, sub in zip( + config.adapter_token_ids, config.adapter_substitute_token_ids + ): + assert int(lut[ctrl]) == int(sub), ( + f"LUT maps control {ctrl} -> {int(lut[ctrl])}, expected {sub}" + ) + + def test_generates(self, lora_model): + import torch + + model, config, _ = lora_model + a, _b = _control_ids(config) + ids = torch.tensor([[TEXT, TEXT, a, TEXT]]) + with torch.no_grad(): + out = model.generate(ids, max_new_tokens=5, do_sample=False) + assert out.shape[1] == ids.shape[1] + 5, ( + f"generate produced {out.shape[1]} tokens, expected {ids.shape[1] + 5}" + ) + + def test_generate_carries_adapter(self, lora_model): + """A control token in the prompt keeps its adapter active through decode.""" + import torch + + model, config, _ = lora_model + _a, b = _control_ids(config) + with torch.no_grad(): + model.generate( + torch.tensor([[TEXT, b, TEXT]]), max_new_tokens=4, do_sample=False + ) + # The final forward is a decode step; routing must still be adapter 2. + route = model.model._last_adapter_indices[0].tolist() + assert all(v == 2 for v in route), ( + f"decode routing {route} lost the adapter set by the control token" + ) + + +# ── lora: production-shaped inputs ──────────────────────────────────────────── + + +class TestChatTemplatePlacement: + """Wherever the template puts a control token, routing must be base before it + and that adapter at and after it.""" + + def test_template_emits_control_tokens(self, lora_model): + """Non-vacuity: otherwise the tests below pass on an all-base sequence.""" + _model, config, tok = lora_model + name = next(iter(config.adapter_names)) + rendered = _render(tok, "What is a hash function?", name) + ids = tok(rendered, add_special_tokens=False)["input_ids"] + map_keys = re.findall(r"'([^']+)':\s*\{'token'", tok.chat_template or "") + assert _ctrl_positions(ids, config.adapter_token_ids), ( + "the composed chat template emitted NO control token.\n" + f" adapter_name passed : {name!r}\n" + f" template adapter_map keys: {map_keys}\n" + f" rendered: {rendered[:300]!r}" + ) + + def test_routing_follows_template_placement(self, lora_model): + model, config, tok = lora_model + name = next(iter(config.adapter_names)) + ids = _render_ids(tok, "Explain hashing in one sentence.", name) + pos = _ctrl_positions(ids, config.adapter_token_ids) + if not pos: + pytest.skip("template emitted no control token (see test above)") + route = _route(model, ids) + first = pos[0] + assert all(v == 0 for v in route[:first]), ( + f"positions before the first control token ({first}) must be base, " + f"got {route[:first]}" + ) + assert route[first] != 0, ( + f"the control token's own position {first} routed to base" + ) + assert route[-1] != 0, f"the generation position routed to base: {route[-8:]}" + + def test_template_prompt_generates(self, lora_model): + import torch + + model, config, tok = lora_model + name = next(iter(config.adapter_names)) + ids = torch.tensor([_render_ids(tok, "Name one use of a hash function.", name)]) + with torch.no_grad(): + out = model.generate(ids, max_new_tokens=8, do_sample=False) + # > rather than == : generate() may stop early on EOS. + assert out.shape[1] > ids.shape[1], "template prompt generated nothing" + + +class TestRealMultiTurn: + """Generate, append the model's own reply, switch adapter, go again.""" + + def test_two_turns_different_adapters(self, lora_model): + """Turn 1's adapter holds through its turn; turn 2's wins at the tail.""" + import torch + + model, config, tok = lora_model + a, b = _control_ids(config) + + turn1 = tok("Question: what is entropy?", add_special_tokens=False)[ + "input_ids" + ] + [a] + ids1 = torch.tensor([turn1]) + with torch.no_grad(): + out1 = model.generate(ids1, max_new_tokens=10, do_sample=False) + reply1 = out1[0][ids1.shape[1] :].tolist() + assert reply1, "turn 1 generated nothing" + + turn2 = ( + turn1 + + reply1 + + tok(" Question: and what is enthalpy?", add_special_tokens=False)[ + "input_ids" + ] + + [b] + ) + route = _route(model, turn2) + i_a, i_b = turn2.index(a), turn2.index(b) + assert route[i_a] != 0 and route[i_b] != 0, ( + f"a control token routed to base: {i_a}->{route[i_a]}, {i_b}->{route[i_b]}" + ) + assert route[i_b] != route[i_a], ( + f"turn 2's control token did not change the adapter ({route[i_a]})" + ) + assert all(v == route[i_a] for v in route[i_a:i_b]), ( + f"turn 1's adapter did not hold through its own turn: {route[i_a:i_b]}" + ) + assert all(v == route[i_b] for v in route[i_b:]), ( + f"turn 2's adapter did not hold to the end: {route[i_b:]}" + ) + + def test_second_turn_generates(self, lora_model): + """The second turn generates too -- decode over a longer cache.""" + import torch + + model, config, tok = lora_model + a, b = _control_ids(config) + t1 = tok("Briefly: what is a graph?", add_special_tokens=False)["input_ids"] + [ + a + ] + with torch.no_grad(): + o1 = model.generate(torch.tensor([t1]), max_new_tokens=8, do_sample=False) + t2 = ( + o1[0].tolist() + + tok(" And a tree?", add_special_tokens=False)["input_ids"] + + [b] + ) + with torch.no_grad(): + o2 = model.generate(torch.tensor([t2]), max_new_tokens=8, do_sample=False) + # generate() may stop early on EOS, so assert SOME new tokens, not exactly 8. + assert o2.shape[1] > len(t2), "second turn generated nothing" + + +class TestLongPrompt: + """The count is recovered from an anchor at position 0; check it still inverts + exactly when the control tokens sit thousands of tokens behind it.""" + + @pytest.mark.parametrize("length", [1024, 4096]) + def test_long_sequence_routing(self, lora_model, length): + model, config, _ = lora_model + a, b = _control_ids(config) + i_a, i_b = length // 2, length - 20 + ids = [TEXT] * length + ids[i_a] = a + ids[i_b] = b + route = _route(model, ids) + assert all(v == 0 for v in route[:i_a]), ( + f"len={length}: base expected before {i_a}; saw {sorted(set(route[:i_a]))}" + ) + assert all(v == route[i_a] for v in route[i_a:i_b]), ( + f"len={length}: A did not hold {i_a}..{i_b}; saw {sorted(set(route[i_a:i_b]))}" + ) + assert all(v == route[i_b] for v in route[i_b:]), ( + f"len={length}: B did not hold from {i_b}; saw {sorted(set(route[i_b:]))}" + ) + assert route[i_a] != route[i_b] and route[i_a] != 0, ( + f"len={length}: controls did not select distinct adapters " + f"(A={route[i_a]}, B={route[i_b]})" + ) + + def test_many_transitions(self, lora_model): + """20 transitions in one sequence -- stresses the counting head.""" + model, config, _ = lora_model + a, b = _control_ids(config) + seq, expected = [], [] + for k in range(20): + ctrl, cur = (a, 1) if k % 2 == 0 else (b, 2) + seq += [ctrl] + [TEXT] * 30 + expected += [cur] * 31 + route = _route(model, seq) + wrong = [ + (i, route[i], expected[i]) + for i in range(len(seq)) + if route[i] != expected[i] + ] + assert not wrong, ( + f"{len(wrong)} of {len(seq)} positions mis-routed across 20 transitions; " + f"first few (index, got, want): {wrong[:6]}" + ) + + +# ── alora: placement-driven routing ─────────────────────────────────────────── + + +class TestALoRA: + """For aLoRA the return to base for earlier turns is achieved by PLACEMENT.""" + + def test_adapters_present(self, alora_model): + """Non-vacuity: --technology-filter alora yielded adapters.""" + _model, config, tok = alora_model + assert config.num_adapters >= 1, ( + f"alora compose produced num_adapters={config.num_adapters}" + ) + assert len(config.adapter_token_ids) == config.num_adapters, ( + f"{len(config.adapter_token_ids)} control tokens for " + f"{config.num_adapters} adapters" + ) + # Without invocation_text the template falls back to the generation-prompt + # path, which is a different routing shape. + assert "invocation_text" in (tok.chat_template or ""), ( + "the composed chat template has no invocation_text entries" + ) + + def test_base_before_adapter_after(self, alora_model): + model, config, tok = alora_model + name = config.adapter_names[0] + ids = _render_ids(tok, "Is this answerable from the context?", name) + pos = _ctrl_positions(ids, config.adapter_token_ids) + assert pos, f"no control token in the rendered aLoRA prompt for {name!r}" + first = pos[0] + assert first > 0, ( + "the aLoRA control token landed at index 0 (LoRA's placement); the " + "base-before assertion would be vacuous" + ) + route = _route(model, ids) + assert all(v == 0 for v in route[:first]), ( + f"aLoRA must be BASE before {first}; got {sorted(set(route[:first]))}" + ) + assert route[first] != 0 and all(v == route[first] for v in route[first:]), ( + f"the adapter must hold from {first} to the end; " + f"got {sorted(set(route[first:]))}" + ) + + def test_each_adapter_routes_to_its_own_index(self, alora_model): + model, config, tok = alora_model + seen = {} + for name in config.adapter_names[:3]: + ids = _render_ids(tok, "Is this answerable?", name) + pos = _ctrl_positions(ids, config.adapter_token_ids) + if pos: + seen[name] = _route(model, ids)[pos[0]] + assert len(seen) >= 2, f"needed >=2 renderable aLoRA adapters, got {seen}" + assert len(set(seen.values())) == len(seen), ( + f"different aLoRA adapters routed to the SAME expert id: {seen}" + ) + + def test_generates_with_adapter_at_decode(self, alora_model): + import torch + + model, config, tok = alora_model + ids = torch.tensor( + [ + _render_ids( + tok, "Is this answerable from the context?", config.adapter_names[0] + ) + ] + ) + with torch.no_grad(): + out = model.generate(ids, max_new_tokens=8, do_sample=False) + assert out.shape[1] > ids.shape[1], "aLoRA prompt generated nothing" + route = model.model._last_adapter_indices[0].tolist() + assert route[-1] != 0, f"the adapter was lost during decode; tail {route[-6:]}" + + +class TestTwoALoRAsInOneSequence: + """Two aLoRA adapters in ONE sequence -- the shape MultiSwitch exists for. + + Built by concatenating two per-adapter renders (what an agentic loop or a + replayed history yields), so placement is still the template's. + """ + + @staticmethod + def _two_turn_ids(config, tok): + names = config.adapter_names + if len(names) < 2: + pytest.skip(f"needs >=2 alora adapters, got {names}") + joined = _render_ids(tok, "Is this answerable from the context?", names[0]) + joined += _render_ids(tok, "How certain are you about that?", names[1]) + return joined, _ctrl_positions(joined, config.adapter_token_ids) + + @pytest.fixture + def two_turn(self, alora_model): + _model, config, tok = alora_model + joined, pos = self._two_turn_ids(config, tok) + if len(pos) < 2: + pytest.skip(f"only {len(pos)} control token(s) rendered") + return joined, pos + + def test_two_alora_tokens_present(self, alora_model): + """Non-vacuity: with fewer than two tokens no transition is exercised.""" + _model, config, tok = alora_model + _joined, pos = self._two_turn_ids(config, tok) + assert len(pos) >= 2, ( + f"expected two aLoRA control tokens in the concatenated sequence, " + f"found {len(pos)} at {pos} -- the latest-wins test would be vacuous" + ) + + def test_latest_wins_between_two_aloras(self, alora_model, two_turn): + model, _config, _tok = alora_model + joined, pos = two_turn + route = _route(model, joined) + i_a, i_b = pos[0], pos[1] + exp_a, exp_b = route[i_a], route[i_b] + assert all(v == 0 for v in route[:i_a]), ( + f"base expected before {i_a}; got {sorted(set(route[:i_a]))}" + ) + assert exp_a != 0 and exp_b != 0 and exp_a != exp_b, ( + f"expected two distinct adapters: pos{i_a}->{exp_a}, pos{i_b}->{exp_b}" + ) + assert all(v == exp_a for v in route[i_a:i_b]), ( + f"A ({exp_a}) must hold {i_a}..{i_b}; got {sorted(set(route[i_a:i_b]))}" + ) + assert all(v == exp_b for v in route[i_b:]), ( + f"B ({exp_b}) must hold from {i_b}; got {sorted(set(route[i_b:]))}" + ) + + def test_two_alora_sequence_generates(self, alora_model, two_turn): + import torch + + model, _config, _tok = alora_model + joined, _pos = two_turn + ids = torch.tensor([joined]) + with torch.no_grad(): + out = model.generate(ids, max_new_tokens=8, do_sample=False) + assert out.shape[1] > ids.shape[1], "two-adapter sequence generated nothing" + route = model.model._last_adapter_indices[0].tolist() + assert route[-1] != 0, ( + f"the second adapter was lost during decode; {route[-6:]}" + ) + + +# ── mixed: per-technology placement in one checkpoint ───────────────────────── + + +class TestMixed: + """With no --technology-filter, each adapter must keep its own technology's + placement and routing shape.""" + + def test_checkpoint_is_mixed(self, mixed_model): + """The tests below skip a missing technology, so this one fails on it: + a checkpoint that silently lost LoRA or aLoRA must not pass as mixed.""" + _model, _config, tok = mixed_model + kinds = set(_template_types(tok).values()) + assert kinds == {"lora", "alora"}, ( + f"multi-mixed must hold both LoRA and aLoRA adapters; got {kinds}" + ) + + def test_unfiltered_compose_prefers_alora(self, mixed_model): + """Discovery prefers aLoRA for dual-published adapters, by design. + + Pinned because a silent flip to LoRA preference would change the routing + SHAPE of every unfiltered checkpoint without changing any adapter name. + """ + _model, _config, tok = mixed_model + kinds = set(_template_types(tok).values()) + assert "alora" in kinds, ( + f"an unfiltered compose should prefer aLoRA for dual-published " + f"adapters; got {kinds}" + ) + + def test_one_control_token_per_adapter(self, mixed_model): + _model, config, _tok = mixed_model + atoks = config.adapter_token_ids + assert len(atoks) == config.num_adapters, ( + f"{len(atoks)} control tokens for {config.num_adapters} adapters" + ) + assert len(set(atoks)) == len(atoks), "duplicate control token ids" + + def test_lora_adapter_routes_from_sequence_start(self, mixed_model): + model, config, tok = mixed_model + lora = [n for n, t in _template_types(tok).items() if t == "lora"] + if not lora: + pytest.skip("no lora-typed adapter in this checkpoint") + ids = _render_ids(tok, "Summarize the context.", lora[0]) + pos = _ctrl_positions(ids, config.adapter_token_ids) + assert pos and pos[0] == 0, ( + f"a LoRA control token must land at index 0; got {pos}" + ) + route = _route(model, ids) + assert route[0] != 0 and all(v == route[0] for v in route), ( + f"LoRA routing must be one adapter throughout; got {sorted(set(route))}" + ) + + def test_alora_adapter_routes_base_then_adapter(self, mixed_model): + model, config, tok = mixed_model + alora = [n for n, t in _template_types(tok).items() if t == "alora"] + if not alora: + pytest.skip("no alora-typed adapter in this checkpoint") + ids = _render_ids(tok, "Is this answerable from the context?", alora[0]) + pos = _ctrl_positions(ids, config.adapter_token_ids) + assert pos and pos[0] > 0, ( + f"an aLoRA control token must not be at index 0; got {pos}" + ) + route = _route(model, ids) + first = pos[0] + assert all(v == 0 for v in route[:first]), ( + f"aLoRA must be base before {first}; got {sorted(set(route[:first]))}" + ) + assert route[first] != 0 and all(v == route[first] for v in route[first:]), ( + f"aLoRA adapter must hold from {first}; got {sorted(set(route[first:]))}" + ) + + def test_lora_and_alora_select_different_experts(self, mixed_model): + model, config, tok = mixed_model + types = _template_types(tok) + lora = [n for n, t in types.items() if t == "lora"] + alora = [n for n, t in types.items() if t == "alora"] + if not lora or not alora: + pytest.skip(f"need both technologies; got lora={lora} alora={alora}") + got = {} + for name in (lora[0], alora[0]): + ids = _render_ids(tok, "Is this answerable?", name) + pos = _ctrl_positions(ids, config.adapter_token_ids) + if pos: + got[name] = _route(model, ids)[pos[0]] + if len(got) < 2: + pytest.skip(f"could not render both technologies: {got}") + assert len(set(got.values())) == 2, ( + f"a LoRA and an aLoRA adapter routed to the SAME expert id: {got}" + ) + + def test_generates_for_each_technology(self, mixed_model): + import torch + + model, _config, tok = mixed_model + for kind in ("lora", "alora"): + names = [n for n, t in _template_types(tok).items() if t == kind] + if not names: + continue + ids = torch.tensor([_render_ids(tok, "Is this answerable?", names[0])]) + with torch.no_grad(): + out = model.generate(ids, max_new_tokens=8, do_sample=False) + assert out.shape[1] > ids.shape[1], f"{kind} adapter generated nothing" + + def test_resave_preserves_buffers_and_routing(self, mixed_model, tmp_path): + """A second save/load round trip on the real artifact keeps the switch + buffers and the routing unchanged.""" + from granite_switch.hf import GraniteSwitchForCausalLM + + model, _config, tok = mixed_model + name = next(iter(_template_types(tok))) + ids = _render_ids(tok, "Is this answerable?", name) + route_before = _route(model, ids) + + out = tmp_path / "resaved" + model.save_pretrained(out) + tok.save_pretrained(out) + reloaded = GraniteSwitchForCausalLM.from_pretrained(out).eval() + _assert_buffers_valid(reloaded.model.switch) + route_after = _route(reloaded, ids) + assert route_after == route_before, ( + "routing changed after a save/load round trip:\n" + f" before: {route_before}\n after : {route_after}" + ) diff --git a/tests/hf/test_multi_switch_realistic.py b/tests/hf/test_multi_switch_realistic.py deleted file mode 100644 index 338e50f4..00000000 --- a/tests/hf/test_multi_switch_realistic.py +++ /dev/null @@ -1,355 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""MultiSwitch on inputs shaped the way production actually shapes them. - -Every other multiswitch test hand-builds token-id lists like -``[TEXT, A_TOK, TEXT, B_TOK]``. Nothing in production does that. Real callers: - - * build the prompt with ``apply_chat_template``, which decides WHERE control - tokens go from the adapter's technology (per CLAUDE.md: aLoRA tokens land in - the user message or immediately before the generation prompt; LoRA tokens at - the sequence start). The switch's correctness depends on that placement, and - the placement logic is a separate layer with its own rules -- so a template - that emits a control token somewhere the switch mishandles would pass every - hand-built test; - * hold a MULTI-TURN conversation, appending the model's own generated reply and - then asking again with a different adapter. That is the motivating use case - (agentic per-step switching) and it reuses the KV cache across turns; - * send prompts long enough that vLLM/HF split the prefill. The counting anchor - lives at position 0, so a later chunk can contain no anchor at all -- the same - structural hazard as the batching bug. - -These are the three untested seams closest to real deployment -- exactly the kind -of boundary where code correct in isolation goes wrong the first time something -real drives it. - -Uses the module-scoped real composed checkpoint from ``test_multi_switch_e2e``, so -it costs no extra compose. Gated on ``GRANITE_SWITCH_E2E_MODELS=1``. -""" - -import os - -import pytest - -pytestmark = [ - pytest.mark.slow, - pytest.mark.requires_model, - pytest.mark.gpu, - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="needs a real composed checkpoint; set GRANITE_SWITCH_E2E_MODELS=1", - ), -] - -# Reuse the e2e module's fixture: same session, same composed artifact. -from tests.hf.test_multi_switch_e2e import composed_model # noqa: F401 - - -@pytest.fixture(scope="module") -def tokenizer(composed_model): # noqa: F811 - from transformers import AutoTokenizer - - _model, config, _ = composed_model - # The composed dir is where the config came from; re-derive it the same way - # the e2e module does rather than reaching into fixture internals. - from tests.hf.test_multi_switch_e2e import _compose - - return AutoTokenizer.from_pretrained(_compose("multi")) - - -def _render(tokenizer, question, adapter_name): - """Render a chat prompt the way a real caller does. - - The template does NOT auto-inject a control token for a plain user turn -- - verified on the composed checkpoint, which rendered - '<|start_of_role|>user<|end_of_role|>...<|start_of_role|>assistant<|end_of_role|>' - with no control token at all. The adapter must be requested explicitly. - - The kwarg is ``adapter_name``, not ``intrinsic_name``. See - ``composer/tokenizer_setup.py::configure_chat_template``, which emits - ``{%- if adapter_name is defined and adapter_name in adapter_map %}``. Jinja - treats an unknown kwarg as simply-not-defined, so passing the wrong name - raises nothing, renders no control token, and every routing assertion - downstream becomes vacuous -- which is exactly what the GPU run caught. - Only ``test_template_emits_control_tokens`` stood between that typo and a - green suite over an all-base sequence. - """ - return tokenizer.apply_chat_template( - [{"role": "user", "content": question}], - tokenize=False, - add_generation_prompt=True, - adapter_name=adapter_name, - ) - - -def _control_positions(ids, atoks): - """Indices in ``ids`` holding any adapter control token.""" - ctrl = set(int(t) for t in atoks) - return [i for i, t in enumerate(ids) if int(t) in ctrl] - - -# ── 1. chat template places the control tokens ──────────────────────────────── - - -class TestChatTemplatePlacement: - """The rendered chat template must produce routing the switch handles. - - Not asserting a specific placement -- that is the template's business and it - differs by adapter technology. Asserting the CONTRACT: wherever the template - puts a control token, routing must be base before it and that adapter at and - after it, and the generation position must end up on a real adapter. - """ - - def test_template_emits_control_tokens(self, composed_model, tokenizer): # noqa: F811 - """Sanity: the composed template actually injects control tokens. - - If it does not, the tests below would pass vacuously on an all-base - sequence -- the same trap as a dead switch being trivially batch-invariant. - """ - _model, config, _ = composed_model - name = next(iter(config.adapter_names)) - rendered = _render(tokenizer, "What is a hash function?", name) - ids = tokenizer(rendered, add_special_tokens=False)["input_ids"] - pos = _control_positions(ids, config.adapter_token_ids) - # Report enough to identify WHY on failure. Two runs have now failed here, - # first with the wrong kwarg name (intrinsic_name) and then with - # adapter_name -- so the remaining suspect is the NAME not being a key in - # the template's adapter_map. Print the map keys and the name used rather - # than guessing a third time. - import re as _re - - tmpl = tokenizer.chat_template or "" - map_keys = _re.findall(r"'([^']+)':\s*\{'token'", tmpl) - assert pos, ( - "the composed chat template emitted NO control token, so every " - "placement assertion below would be vacuous.\n" - f" adapter_name passed : {name!r}\n" - f" config.adapter_names: {list(config.adapter_names)}\n" - f" template adapter_map keys: {map_keys}\n" - f" name in map? {name in map_keys}\n" - f" rendered: {rendered[:300]!r}" - ) - print(f"\n control tokens at positions {pos} of {len(ids)}") - - def test_routing_follows_template_placement(self, composed_model, tokenizer): # noqa: F811 - """Routing must be base before the first control token, adapter after.""" - import torch - - model, config, _ = composed_model - name = next(iter(config.adapter_names)) - rendered = _render(tokenizer, "Explain hashing in one sentence.", name) - ids = tokenizer(rendered, add_special_tokens=False)["input_ids"] - pos = _control_positions(ids, config.adapter_token_ids) - if not pos: - pytest.skip("template emitted no control token (see test above)") - - with torch.no_grad(): - model(input_ids=torch.tensor([ids])) - route = model.model._last_adapter_indices[0].tolist() - - first = pos[0] - assert all(v == 0 for v in route[:first]), ( - f"positions before the first control token ({first}) must be base, " - f"got {route[:first]}" - ) - assert route[first] != 0, ( - f"the control token's own position {first} routed to base ({route[first]}); " - "the adapter must be active at the control token itself" - ) - # And the last position -- where generation continues from -- must be on - # an adapter, since that is what the template arranged for. - assert route[-1] != 0, ( - f"the generation position routed to base; full routing tail: {route[-8:]}" - ) - - def test_template_prompt_generates(self, composed_model, tokenizer): # noqa: F811 - """A template-built prompt must generate, not just forward.""" - import torch - - model, _config, _ = composed_model - name = next(iter(_config.adapter_names)) - rendered = _render(tokenizer, "Name one use of a hash function.", name) - ids = torch.tensor([tokenizer(rendered, add_special_tokens=False)["input_ids"]]) - with torch.no_grad(): - out = model.generate(ids, max_new_tokens=8, do_sample=False) - # > rather than == : generate() may stop early on EOS. - assert out.shape[1] > ids.shape[1], ( - f"template prompt generated nothing: {out.shape[1]} <= {ids.shape[1]}" - ) - text = tokenizer.decode(out[0][ids.shape[1] :], skip_special_tokens=True) - print(f"\n generated from template prompt: {text.strip()[:120]!r}") - - -# ── 2. multi-turn with the model's OWN reply appended ───────────────────────── - - -class TestRealMultiTurn: - """Generate, append the reply, switch adapter, generate again. - - The existing 'multi-turn' e2e test is one synthetic sequence. This is the real - shape: turn 1 output becomes turn 2 input, so the second forward sees a prompt - containing generated tokens and a second control token further along. - """ - - def test_two_turns_different_adapters(self, composed_model, tokenizer): # noqa: F811 - """Turn 2's adapter must win at the tail, and turn 1's must hold before it.""" - import torch - - model, config, _ = composed_model - atoks = list(config.adapter_token_ids) - a, b = atoks[0], atoks[1] - - # Turn 1: prompt + adapter A, generate a real continuation. - turn1 = tokenizer("Question: what is entropy?", add_special_tokens=False)[ - "input_ids" - ] + [a] - ids1 = torch.tensor([turn1]) - with torch.no_grad(): - out1 = model.generate(ids1, max_new_tokens=10, do_sample=False) - reply1 = out1[0][ids1.shape[1] :].tolist() - assert reply1, "turn 1 generated nothing" - - # Turn 2: everything so far + a NEW question + adapter B. - turn2 = ( - turn1 - + reply1 - + tokenizer(" Question: and what is enthalpy?", add_special_tokens=False)[ - "input_ids" - ] - + [b] - ) - ids2 = torch.tensor([turn2]) - with torch.no_grad(): - model(input_ids=ids2) - route = model.model._last_adapter_indices[0].tolist() - - i_a, i_b = turn2.index(a), turn2.index(b) - assert route[i_a] != 0 and route[i_b] != 0, ( - f"a control token routed to base: pos {i_a}->{route[i_a]}, " - f"pos {i_b}->{route[i_b]}" - ) - assert route[i_b] != route[i_a], ( - f"turn 2's control token ({b}) did not change the adapter: " - f"both turns routed to {route[i_a]}" - ) - assert all(v == route[i_b] for v in route[i_b:]), ( - f"turn 2's adapter did not hold to the end: {route[i_b:]}" - ) - # Latest-wins across the boundary: A holds from i_a until i_b. - assert all(v == route[i_a] for v in route[i_a:i_b]), ( - f"turn 1's adapter did not hold through its own turn: {route[i_a:i_b]}" - ) - - def test_second_turn_generates(self, composed_model, tokenizer): # noqa: F811 - """The second turn must also generate -- decode over a longer cache.""" - import torch - - model, config, _ = composed_model - a, b = list(config.adapter_token_ids)[:2] - t1 = tokenizer("Briefly: what is a graph?", add_special_tokens=False)[ - "input_ids" - ] + [a] - with torch.no_grad(): - o1 = model.generate(torch.tensor([t1]), max_new_tokens=8, do_sample=False) - t2 = ( - o1[0].tolist() - + tokenizer(" And a tree?", add_special_tokens=False)["input_ids"] - + [b] - ) - with torch.no_grad(): - o2 = model.generate(torch.tensor([t2]), max_new_tokens=8, do_sample=False) - # generate() may stop early on EOS, so assert it produced SOME new tokens - # rather than exactly 8. An earlier version asserted == len(t2) + 8 and - # failed at 29 vs 30 because generation ended on EOS -- a bug in the - # assertion, not the model. - assert o2.shape[1] > len(t2), ( - f"second turn generated nothing: {o2.shape[1]} <= {len(t2)}" - ) - print( - f"\n turn2: {tokenizer.decode(o2[0][len(t2) :], skip_special_tokens=True).strip()[:110]!r}" - ) - - -# ── 3. long prompt: the counting anchor is far from the tail ────────────────── - - -class TestLongPrompt: - """A prompt long enough that the anchor is thousands of tokens behind. - - The 1/(1+n) count is recovered from an anchor at position 0. Every other test - uses prompts of a few dozen tokens. This checks the count still inverts - exactly when the sequence is long -- and, on backends that chunk the prefill, - that a chunk without the anchor does not break the count. - """ - - @pytest.mark.parametrize("length", [1024, 4096]) - def test_long_sequence_routing(self, composed_model, length): # noqa: F811 - """Control tokens placed late in a long prompt still route correctly.""" - import torch - - model, config, _ = composed_model - a, b = list(config.adapter_token_ids)[:2] - filler = 50 - - # base ... A ... B ... : both controls deep into the sequence. - i_a = length // 2 - i_b = length - 20 - ids = [filler] * length - ids[i_a] = a - ids[i_b] = b - - with torch.no_grad(): - model(input_ids=torch.tensor([ids])) - route = model.model._last_adapter_indices[0].tolist() - - assert all(v == 0 for v in route[:i_a]), ( - f"len={length}: positions before the first control must be base; " - f"saw {sorted(set(route[:i_a]))}" - ) - assert all(v == route[i_a] for v in route[i_a:i_b]), ( - f"len={length}: adapter A did not hold from {i_a} to {i_b}; " - f"saw {sorted(set(route[i_a:i_b]))}" - ) - assert all(v == route[i_b] for v in route[i_b:]), ( - f"len={length}: adapter B did not hold from {i_b} to the end; " - f"saw {sorted(set(route[i_b:]))}" - ) - assert route[i_a] != route[i_b] and route[i_a] != 0, ( - f"len={length}: the two controls did not select distinct adapters " - f"(A={route[i_a]}, B={route[i_b]})" - ) - - def test_many_transitions_in_a_long_prompt(self, composed_model): # noqa: F811 - """20 transitions in one long sequence -- stresses the counting head. - - The count is recovered as round(1/signal - 1), so a large n means the - signal is small and the inversion is tighter. 20 switches is far more than - any earlier test and the engine claims to support many more. - """ - import torch - - model, config, _ = composed_model - atoks = list(config.adapter_token_ids) - a, b = atoks[0], atoks[1] - filler = 50 - - seq, expected, cur = [], [], 0 - for k in range(20): - tok = a if k % 2 == 0 else b - seq.append(tok) - cur = 1 if tok == a else 2 - expected.append(cur) - seq.extend([filler] * 30) - expected.extend([cur] * 30) - - with torch.no_grad(): - model(input_ids=torch.tensor([seq])) - route = model.model._last_adapter_indices[0].tolist() - wrong = [ - (i, route[i], expected[i]) - for i in range(len(seq)) - if route[i] != expected[i] - ] - assert not wrong, ( - f"{len(wrong)} of {len(seq)} positions mis-routed across 20 transitions; " - f"first few (index, got, want): {wrong[:6]}" - ) diff --git a/tests/hf/test_quantization.py b/tests/hf/test_quantization.py index 86067638..44d19edc 100644 --- a/tests/hf/test_quantization.py +++ b/tests/hf/test_quantization.py @@ -17,7 +17,7 @@ carries both an aLoRA intrinsic (``answerability``) and a LoRA one (``hallucination_detection``), warm-reused under ``GRANITE_SWITCH_E2E_DIR``. The published previews are legacy SingleSwitch checkpoints and no longer load, so the -suite composes its own — same pattern as ``test_multi_switch_mixed_tech.py``. +suite composes its own — same pattern as ``test_multi_switch_real_checkpoint.py``. """ import os @@ -32,13 +32,7 @@ pytest.mark.slow, pytest.mark.requires_model, pytest.mark.gpu, - # Compatibility with the quantization libraries on a real checkpoint; the - # release suite sets GRANITE_SWITCH_E2E_MODELS=1 so the gate below opens. pytest.mark.release, - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="composes a real ~3B mixed checkpoint; set GRANITE_SWITCH_E2E_MODELS=1", - ), ] BASE_MODEL = "ibm-granite/granite-4.1-3b" diff --git a/tests/integration/_conversation_prefix_cache_worker.py b/tests/integration/_conversation_prefix_cache_worker.py index ba10ffa5..a5bb1541 100644 --- a/tests/integration/_conversation_prefix_cache_worker.py +++ b/tests/integration/_conversation_prefix_cache_worker.py @@ -45,9 +45,13 @@ DEFAULT_PORT = 8137 MAX_TOKENS = 24 +# Anchored on token/type/invocation_text and tolerant of trailing fields: an aLoRA +# entry also carries ``'invocation_drop_chars': N`` (configure_chat_template), and +# a regex that required ``}`` right after invocation_text matched no aLoRA entry. _ADAPTER_MAP_RE = re.compile( r"'(?P[^']+)':\s*\{'token':\s*'(?P[^']+)',\s*" - r"'type':\s*'(?P[^']+)'(?:,\s*'invocation_text':\s*'(?P[^']*)')?\}" + r"'type':\s*'(?P[^']+)'(?:,\s*'invocation_text':\s*'(?P[^']*)')?" + r"[^}]*\}" ) diff --git a/tests/integration/test_conversation_prefix_cache.py b/tests/integration/test_conversation_prefix_cache.py index 7329194a..6aad0169 100644 --- a/tests/integration/test_conversation_prefix_cache.py +++ b/tests/integration/test_conversation_prefix_cache.py @@ -19,7 +19,7 @@ trace hook must have fired; prefix caching must really be on (queries > 0); and turn 2 under PRESERVE must really carry two control tokens. -Markers: slow + requires_model + gpu, gated on ``GRANITE_SWITCH_E2E_MODELS=1``. +Markers: slow + requires_model + gpu + release (run with ``pytest -m release``). STATUS: green on 1x A100 (vLLM 0.19.x, granite-4.1-3b + granitelib-rag aLoRA). Measured there: PRESERVE recomputed 24 of 104 turn-2 positions against @@ -58,11 +58,7 @@ pytest.mark.slow, pytest.mark.requires_model, pytest.mark.gpu, - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="composes and serves a real ~3B checkpoint; set " - "GRANITE_SWITCH_E2E_MODELS=1", - ), + pytest.mark.release, ] diff --git a/tests/integration/test_multi_switch_alora_cache.py b/tests/integration/test_multi_switch_alora_cache.py index 660d063f..7e1ec3cd 100644 --- a/tests/integration/test_multi_switch_alora_cache.py +++ b/tests/integration/test_multi_switch_alora_cache.py @@ -33,7 +33,7 @@ decision (an adapter's own earlier output arguably IS legitimate context), not a correctness question this test can settle. -Markers: slow + requires_model + gpu, gated on ``GRANITE_SWITCH_E2E_MODELS=1``. +Markers: slow + requires_model + gpu + release (run with ``pytest -m release``). """ import json @@ -53,11 +53,7 @@ pytest.mark.slow, pytest.mark.requires_model, pytest.mark.gpu, - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="composes and serves a real ~3B checkpoint; set " - "GRANITE_SWITCH_E2E_MODELS=1", - ), + pytest.mark.release, ] diff --git a/tests/integration/test_multi_switch_serving_e2e.py b/tests/integration/test_multi_switch_serving_e2e.py index 6b2fd7ba..9e635283 100644 --- a/tests/integration/test_multi_switch_serving_e2e.py +++ b/tests/integration/test_multi_switch_serving_e2e.py @@ -40,7 +40,7 @@ rather than an unreachable path; the layout itself is covered against the engine by ``tests/vllm/test_multi_switch_serving.py::TestBaseResetLayout``. -Markers: slow + requires_model + gpu, gated on ``GRANITE_SWITCH_E2E_MODELS=1``. +Markers: slow + requires_model + gpu + release (run with ``pytest -m release``). """ import json @@ -62,11 +62,7 @@ pytest.mark.slow, pytest.mark.requires_model, pytest.mark.gpu, - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="composes and serves a real ~3B checkpoint; set " - "GRANITE_SWITCH_E2E_MODELS=1", - ), + pytest.mark.release, ] diff --git a/tests/integration/test_multi_switch_vllm_generate.py b/tests/integration/test_multi_switch_vllm_generate.py index ced82b4b..7640491d 100644 --- a/tests/integration/test_multi_switch_vllm_generate.py +++ b/tests/integration/test_multi_switch_vllm_generate.py @@ -6,7 +6,7 @@ * ``tests/vllm/test_multi_switch.py`` drives the switch in a subprocess harness with a mock config -- no engine, no generation. - * ``tests/hf/test_multi_switch_e2e.py`` uses a real composed checkpoint but the + * ``tests/hf/test_multi_switch_real_checkpoint.py`` uses a real composed checkpoint but the HF backend. Nothing put a composed MultiSwitch checkpoint through ``llm.generate``. That @@ -27,11 +27,10 @@ adapter would emit identical text and (1)-(3) would still pass. Boots vLLM IN-PROCESS (this package, unlike ``tests/vllm/``, does not keep CUDA -out of the parent process). Reuses the checkpoint composed by the HF e2e module +out of the parent process). Reuses the checkpoint composed by the HF real-checkpoint module via ``GRANITE_SWITCH_E2E_DIR``, so it costs an engine boot, not a compose. -Markers: slow + requires_model + gpu, and skipped unless -``GRANITE_SWITCH_E2E_MODELS=1``. +Markers: slow + requires_model + gpu + release (run with ``pytest -m release``). """ import gc @@ -43,10 +42,7 @@ pytest.mark.slow, pytest.mark.requires_model, pytest.mark.gpu, - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="composes/loads a real ~3B checkpoint; set GRANITE_SWITCH_E2E_MODELS=1", - ), + pytest.mark.release, ] MAX_NEW_TOKENS = 16 @@ -55,9 +51,9 @@ @pytest.fixture(scope="module") def multi_checkpoint(): """Path to a composed ``--switch-type multi`` checkpoint (warm-reused).""" - # Reuse the HF e2e module's compose helper so both suites share one artifact + # Reuse the HF real-checkpoint module's compose helper so both suites share one artifact # rather than composing a second 3B model. - from tests.hf.test_multi_switch_e2e import _compose + from tests.hf.test_multi_switch_real_checkpoint import _compose out_dir = _compose("multi") assert (out_dir / "config.json").exists(), f"no checkpoint at {out_dir}" diff --git a/tests/unit/test_conversation_adapter_map_parse.py b/tests/unit/test_conversation_adapter_map_parse.py new file mode 100644 index 00000000..92d94cc5 --- /dev/null +++ b/tests/unit/test_conversation_adapter_map_parse.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The conversation suites' adapter-map parser against the template the composer emits. + +``_parse_adapter_map`` reads name -> (token, type, invocation_text) back out of a +composed chat template. Both conversation suites (prefix-cache and concurrency) +depend on it, and both are GPU-gated, so a parser that silently stops matching +shows up only as "need >=2 alora adapters" on a GPU run that never happens. + +That is what happened: configure_chat_template started writing +``'invocation_drop_chars': N`` after ``invocation_text`` on every aLoRA entry, the +regex still required ``}`` right after ``invocation_text``, and every aLoRA entry +dropped out. These tests build the map with the real ``configure_chat_template`` +over the real Granite template fixtures (both families), so the next format change +fails here, on CPU. +""" + +import pytest + +from tests.integration._conversation_prefix_cache_worker import _parse_adapter_map +from tests.shared.conversation_stubs import make_stub_tokenizer + +# (chatml, assistant invocation text) for each supported template family. +_FORMATS = pytest.mark.parametrize( + "chatml, invocation", + [ + (False, "<|start_of_role|>assistant<|end_of_role|>"), + (True, "<|im_start|>assistant"), + ], + ids=["role-marker", "chatml"], +) + + +def _composed_template(adapters, chatml): + return make_stub_tokenizer(adapters, chatml=chatml).chat_template + + +@_FORMATS +def test_alora_entry_with_drop_chars_is_parsed(chatml, invocation): + template = _composed_template([("answerability", "alora", invocation)], chatml) + assert "invocation_drop_chars" in template, ( + "the composer no longer writes invocation_drop_chars; this test's premise " + "is stale" + ) + amap = _parse_adapter_map(template) + assert amap == {"answerability": ("<|answerability|>", "alora", invocation)} + + +@_FORMATS +def test_lora_and_alora_entries_are_both_parsed(chatml, invocation): + template = _composed_template( + [ + ("answerability", "alora", invocation), + ("certainty", "alora", invocation), + ("guardian", "lora", None), + ], + chatml, + ) + amap = _parse_adapter_map(template) + assert amap == { + "answerability": ("<|answerability|>", "alora", invocation), + "certainty": ("<|certainty|>", "alora", invocation), + "guardian": ("<|guardian|>", "lora", None), + } diff --git a/tests/vllm/test_pipeline_parallelism_equivalence.py b/tests/vllm/test_pipeline_parallelism_equivalence.py index e3896018..9e79535c 100644 --- a/tests/vllm/test_pipeline_parallelism_equivalence.py +++ b/tests/vllm/test_pipeline_parallelism_equivalence.py @@ -31,14 +31,8 @@ # The published previews are legacy SingleSwitch checkpoints and no longer load; # compose a real MultiSwitch checkpoint on demand (warm-reused under -# GRANITE_SWITCH_E2E_DIR), the same one test_multi_switch_mixed_tech builds. PP +# GRANITE_SWITCH_E2E_DIR), the same one test_multi_switch_real_checkpoint builds. PP # only needs a loadable checkpoint with an active adapter — any MultiSwitch does. -BASE_MODEL = "ibm-granite/granite-4.1-3b" -ADAPTER_REPOS = [ - "ibm-granite/granitelib-rag-r1.0", - "ibm-granite/granitelib-guardian-r1.0", -] -_E2E_ROOT = Path(os.environ.get("GRANITE_SWITCH_E2E_DIR", "/tmp/granite_switch_e2e")) _TIMEOUT = 1800 # compose (warm-reused) + 2× (vLLM load + generate) @@ -77,40 +71,16 @@ def _visible_cuda_device_count(): _visible_cuda_device_count() < 2, reason="requires at least 2 visible CUDA GPUs", ), - pytest.mark.skipif( - os.environ.get("GRANITE_SWITCH_E2E_MODELS") != "1", - reason="composes a real ~3B checkpoint; set GRANITE_SWITCH_E2E_MODELS=1", - ), + pytest.mark.release, ] @pytest.fixture(scope="module") def model_path(): """Compose (or warm-reuse) a mixed MultiSwitch checkpoint; return its dir.""" - out_dir = _E2E_ROOT / "multi-mixed" - if (out_dir / "config.json").exists(): - print(f"warm-reuse {out_dir}", file=sys.stderr) - return str(out_dir) - out_dir.mkdir(parents=True, exist_ok=True) - cmd = [ - sys.executable, - "-m", - "granite_switch.composer.compose_granite_switch", - "--base-model", - BASE_MODEL, - *[arg for r in ADAPTER_REPOS for arg in ("--adapters", r)], - "--output", - str(out_dir), - ] - print("composing (mixed):", " ".join(cmd), file=sys.stderr) - r = subprocess.run(cmd, capture_output=True, text=True, timeout=7200) - if r.returncode != 0: - pytest.fail( - f"mixed compose failed (exit {r.returncode})\n" - f"--- stdout ---\n{r.stdout[-3000:]}\n--- stderr ---\n{r.stderr[-3000:]}", - pytrace=False, - ) - return str(out_dir) + from tests.hf.test_multi_switch_real_checkpoint import _compose + + return str(_compose("multi-mixed")) def _subprocess_env():