From 1dca62b0b48a763d2c55d4ed530f7c38675ac284 Mon Sep 17 00:00:00 2001 From: Tarek Ziade Date: Wed, 25 Nov 2026 07:49:20 +0100 Subject: [PATCH] serve: fall back to sequential generation for models continuous batching can't run --- src/transformers/cli/serving/utils.py | 14 +++++--- .../generation/continuous_batching/cache.py | 15 ++++++-- tests/cli/test_serve.py | 36 +++++++++++++++++++ 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/src/transformers/cli/serving/utils.py b/src/transformers/cli/serving/utils.py index 609e6dbb4bf7..13abcf2100d9 100644 --- a/src/transformers/cli/serving/utils.py +++ b/src/transformers/cli/serving/utils.py @@ -1108,13 +1108,19 @@ def use_continuous_batching(self, model: "PreTrainedModel", modality: Modality) """ if not self._continuous_batching: return False - can = hasattr(model, "init_continuous_batching") and modality == Modality.LLM - if not can: + from transformers.generation.continuous_batching.cache import unsupported_layer_types + + reason = None + if not hasattr(model, "init_continuous_batching") or modality != Modality.LLM: + reason = "it is not a text-only language model" + elif unsupported := unsupported_layer_types(model.config): + reason = f"its {', '.join(unsupported)} layers have no continuous batching cache" + if reason is not None: logger.warning_once( - f"{model.__class__.__name__} does not support continuous batching. " + f"{model.__class__.__name__} does not support continuous batching: {reason}. " "Falling back to sequential generation." ) - return can + return reason is None def get_manager(self, model_id: str, use_cb: bool = False) -> BaseGenerateManager: """Return a per-model generation manager, lazily created on first request. diff --git a/src/transformers/generation/continuous_batching/cache.py b/src/transformers/generation/continuous_batching/cache.py index 42277f54591f..cafcb027838f 100644 --- a/src/transformers/generation/continuous_batching/cache.py +++ b/src/transformers/generation/continuous_batching/cache.py @@ -41,6 +41,13 @@ } +def unsupported_layer_types(config: PreTrainedConfig) -> list[str]: + """The layer types of ``config`` that continuous batching has no cache for (e.g. ``linear_attention``), in order of + first appearance. Empty if the model can run with continuous batching.""" + layer_types = getattr(config, "layer_types", None) or [] + return list(dict.fromkeys(t for t in layer_types if t not in ATTN_TYPE_TO_ALLOCATOR)) + + def group_layers_by_attn_type(config: PreTrainedConfig) -> dict[str, list[int]]: """Groups layers depending on their attention type. @@ -59,10 +66,14 @@ def group_layers_by_attn_type(config: PreTrainedConfig) -> dict[str, list[int]]: return {FULL_ATTENTION: list(range(config.num_hidden_layers))} # Otherwise simply count the number of layers of each type, making sure they are supported at the same time + unsupported = unsupported_layer_types(config) + if unsupported: + raise ValueError( + f"Continuous batching does not support {', '.join(unsupported)} layers " + f"(supported: {', '.join(ATTN_TYPE_TO_ALLOCATOR)})" + ) layer_counts = {} for i, layer_type in enumerate(layer_types): - if layer_type not in ATTN_TYPE_TO_ALLOCATOR: - raise ValueError(f"Invalid layer type: {layer_type}") layer_counts[layer_type] = layer_counts.get(layer_type, []) + [i] return layer_counts diff --git a/tests/cli/test_serve.py b/tests/cli/test_serve.py index 3f58bec57c34..4d28ceca5baf 100644 --- a/tests/cli/test_serve.py +++ b/tests/cli/test_serve.py @@ -3105,3 +3105,39 @@ def test_request_cancellation(self): max_output_tokens=10, ) self.assertTrue(len(resp.output[0].content[0].text) > 0) + + +class TestContinuousBatchingFallback(unittest.TestCase): + """Serve falls back to sequential generation for models continuous batching can't run, instead of failing.""" + + # MIC fixtures (https://huggingface.co/huggingface-mic): small models with the real checkpoints' architecture + MOE = ("huggingface-mic/Qwen3-30B-A3B-mic", "770fd1fa927f6e229fb86961c631c85d24350419") + HYBRID = ("huggingface-mic/Qwen3-Next-80B-A3B-Instruct-mic", "7eb57dd61582f58fc530063458ea6b53fc2e21a9") + + @staticmethod + def _model(fixture): + from transformers import AutoModelForCausalLM + + model_id, revision = fixture + return AutoModelForCausalLM.from_pretrained(model_id, revision=revision).eval() + + def test_moe_model_uses_continuous_batching(self): + from transformers.cli.serving.utils import GenerationState + + model = self._model(self.MOE) + self.assertTrue(GenerationState(continuous_batching=True).use_continuous_batching(model, Modality.LLM)) + self.assertFalse(GenerationState().use_continuous_batching(model, Modality.LLM)) # not asked for + + def test_linear_attention_model_falls_back(self): + from transformers.cli.serving.utils import GenerationState + from transformers.generation.continuous_batching.cache import unsupported_layer_types + + model = self._model(self.HYBRID) + self.assertEqual(unsupported_layer_types(model.config), ["linear_attention"]) + self.assertFalse(GenerationState(continuous_batching=True).use_continuous_batching(model, Modality.LLM)) + + def test_vlm_falls_back(self): + from transformers.cli.serving.utils import GenerationState + + model = self._model(self.MOE) + self.assertFalse(GenerationState(continuous_batching=True).use_continuous_batching(model, Modality.VLM))