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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/transformers/cli/serving/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 13 additions & 2 deletions src/transformers/generation/continuous_batching/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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

Expand Down
36 changes: 36 additions & 0 deletions tests/cli/test_serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Loading