Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
24edc8b
fix torch.cuda.graph should operate in thread_local mode
Qubitium Mar 22, 2026
1f641ac
fix tie_weights skipping logic is not thread-safe
Qubitium Mar 22, 2026
34050ec
doc
Qubitium Mar 22, 2026
f9234af
cleanup
Qubitium Mar 22, 2026
6aba984
Merge branch 'main' into continuos-batching-paged-attention-threads
Qubitium Mar 23, 2026
c9c81f6
Merge branch 'main' into continuos-batching-paged-attention-threads
Qubitium Mar 23, 2026
030340c
revert tie_weight() concurrency bug fix. push to another pr
Qubitium Mar 23, 2026
b4e846c
Merge branch 'main' into continuos-batching-paged-attention-threads
Qubitium Mar 23, 2026
bdeb503
Merge branch 'main' into continuos-batching-paged-attention-threads
Qubitium Mar 23, 2026
9bf1782
Merge branch 'main' into continuos-batching-paged-attention-threads
Qubitium Mar 23, 2026
0bf8b6a
cleanup unit test to only check for `thread_local` error_mode
Qubitium Mar 23, 2026
48d8a30
Merge branch 'main' into continuos-batching-paged-attention-threads
Qubitium Mar 23, 2026
5f27b40
add true model test
Qubitium Mar 23, 2026
19255c3
Merge branch 'continuos-batching-paged-attention-threads' of https://…
Qubitium Mar 23, 2026
4ab6fff
Merge branch 'main' into continuos-batching-paged-attention-threads
Qubitium Mar 23, 2026
b9cf5c0
remove error_mode set unit test
Qubitium Mar 23, 2026
7ac4b32
Merge branch 'continuos-batching-paged-attention-threads' of https://…
Qubitium Mar 23, 2026
e348311
Merge branch 'main' into continuos-batching-paged-attention-threads
Qubitium Mar 23, 2026
a1057a9
remove unit test
Qubitium Mar 23, 2026
f5accd9
Merge branch 'continuos-batching-paged-attention-threads' of https://…
Qubitium Mar 23, 2026
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
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,15 @@ def _generation_step(self, model: nn.Module, logit_processor: LogitsProcessorLis
# torch.cuda.current_stream().wait_stream(compute_stream)
# Capture
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, stream=compute_stream, pool=self.graph_pool):
# Continuous batching can run multiple manager threads concurrently in one process.
# PyTorch's default capture mode ("global") errors on CUDA actions from other threads,
# which invalidates unrelated captures even when each manager uses a different device.
with torch.cuda.graph(
graph,
stream=compute_stream,
pool=self.graph_pool,
capture_error_mode="thread_local",
):
forward_fn(
model, batch_data, logit_processor, do_sample, carry_over_ids, prev_output_ids, output_ids
)
Expand Down
85 changes: 85 additions & 0 deletions tests/generation/test_continuous_batching.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
import gc
import itertools
import unittest
from contextlib import contextmanager
from types import SimpleNamespace
from unittest.mock import patch

import torch
Expand Down Expand Up @@ -112,6 +114,89 @@ def wrapper(*args, **kwargs):


class ContinuousBatchingNoAcceleratorTest(unittest.TestCase):
def test_generation_step_uses_thread_local_cuda_graph_capture_mode(self):
"""Regression test for concurrent manager threads using CUDA graphs.

The behavior under test is specifically that CUDA graph capture opts into
`capture_error_mode="thread_local"` instead of PyTorch's default
process-global mode.
"""
graph_capture_calls = []

@contextmanager
def fake_stream(stream):
self.assertEqual(stream, "compute-stream")
yield

@contextmanager
def fake_graph(*args, **kwargs):
self.assertEqual(args, ("graph-object",))
graph_capture_calls.append(dict(kwargs))
yield

class FakeInputsAndOutputs:
def __init__(self) -> None:
self.use_block_table = False
self.compute_stream = "compute-stream"
self.stored_graph = None
self.retrieve_called = False

def get_model_kwargs(self, use_padding: bool):
self.use_padding = use_padding
return {"input_ids": torch.tensor([[1]], dtype=torch.long)}

def get_cb_kwargs(self):
return (
torch.tensor([0], dtype=torch.int32),
torch.tensor([0], dtype=torch.int32),
torch.tensor([0], dtype=torch.int32),
)

def get_graph(self):
return None

def set_graph(self, graph) -> None:
self.stored_graph = graph

def retrieve_device_outputs(self) -> None:
self.retrieve_called = True

inputs_and_outputs = FakeInputsAndOutputs()
forward_calls = []

def fake_forward_fn(
model, batch_data, logit_processor, do_sample, carry_over_ids, prev_output_ids, output_ids
):
del model, logit_processor, do_sample, carry_over_ids, prev_output_ids, output_ids
forward_calls.append(batch_data["input_ids"].clone())

processor = SimpleNamespace(
inputs_and_outputs=inputs_and_outputs,
_compiled_decode=None,
_compiled_varlen=None,
_forward_process_and_sample=fake_forward_fn,
use_cuda_graph=True,
graph_pool="graph-pool",
_pad_inputs=True,
)

with (
patch("transformers.generation.continuous_batching.continuous_api.torch.cuda.stream", fake_stream),
patch("transformers.generation.continuous_batching.continuous_api.torch.cuda.graph", fake_graph),
patch(
"transformers.generation.continuous_batching.continuous_api.torch.cuda.CUDAGraph",
return_value="graph-object",
),
):
ContinuousBatchProcessor._generation_step(processor, object(), LogitsProcessorList(), False)

self.assertEqual(len(graph_capture_calls), 1)
self.assertEqual(
graph_capture_calls[0]["capture_error_mode"],
"thread_local",
"CUDA graph capture must stay thread-local so concurrent manager threads do not invalidate each other.",
)

@parameterized.expand(
[
(None, None, "0"),
Expand Down
223 changes: 223 additions & 0 deletions tests/generation/test_continuous_batching_llama32_nogil_repro.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
# Copyright 2026 The HuggingFace Team Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys
import sysconfig
import threading
import time
import traceback
import unittest
from dataclasses import dataclass

import torch

from transformers import AutoModelForCausalLM, AutoTokenizer, ContinuousBatchingConfig, GenerationConfig
from transformers.generation.continuous_batching.requests import GenerationOutput, RequestStatus
from transformers.utils import is_flash_attn_2_available, is_kernels_available


# This repro must be started with no-GIL settings already applied at interpreter startup, for example:
# PYTHON_GIL=0 /root/vm314t/bin/python -m unittest <test module>
# Setting this env var inside this script is too late for extension imports such as `tokenizers`, which can
# re-enable the GIL during import unless the interpreter itself starts with `PYTHON_GIL=0`.


MODEL_PATH = "/monster/data/model/Llama-3.2-1B-Instruct" # FIXME

@Qubitium Qubitium Mar 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@remi-or I have validated on my own end with 3.14t + 2 nvidia gpu + 2 threads + PYTHON_GIL=0 using this script. Please modify this unit test so that it:

  1. has proper access to llama 3.2 1b instruct or similar if you can reproduce the crash with another model (it should be model agnostic).
  2. fix/adpt this unit test for the circle system you guys run that I have no clue about. Since it needs to select 2 gpus, have fa2 available (maybe not need), and env needs 3.13t/3.14t.
  3. CI must set PYTHON_GIL=0 before python startup since tokenizer would override nogil without this env flag.
PYTHON_GIL=0 /root/vm314t/bin/python -m unittest \
tests.generation.test_continuous_batching_llama32_nogil_repro.ContinuousBatchingLlama32NogilReproTest.test_two_thread_llama32_continuous_batching_cuda_graph_repro

With the patch on the current branch:

Result: OK in 8.472s.

Without patch:

Result: FAILED in 5.554s.

2026-03-23 14:36:52,685 - ContinuousBatchingLogger - ERROR - Error in generation loop: CUDA error: operation not permitted when stream is capturing
 Traceback (most recent call last):
   File "/tmp/transformers-no-threadlocal-MxpTSt/src/transformers/generation/continuous_batching/continuous_api.py", line 843, in _run_generation_loop
     self._inner_generation_loop(batch_processor)
   File "/tmp/transformers-no-threadlocal-MxpTSt/src/transformers/generation/continuous_batching/continuous_api.py", line 863, in _inner_generation_loop
     self._generation_step()
   File "/tmp/transformers-no-threadlocal-MxpTSt/src/transformers/generation/continuous_batching/continuous_api.py", line 794, in _generation_step
     self.batch_processor._generation_step(self.model, self.logit_processor, self.do_sample)
   File "/tmp/transformers-no-threadlocal-MxpTSt/src/transformers/generation/continuous_batching/continuous_api.py", line 470, in _generation_step
     with torch.cuda.graph(
   File "/root/vm314t/lib/python3.14t/site-packages/torch/cuda/graphs.py", line 265, in __exit__
     self.cuda_graph.capture_end()
   File "/root/vm314t/lib/python3.14t/site-packages/torch/cuda/graphs.py", line 126, in capture_end
     super().capture_end()
 torch.AcceleratorError: CUDA error: operation not permitted when stream is capturing

 Then the second manager sees the invalidated capture:

 torch.AcceleratorError: CUDA error: operation failed due to a previous error during capture
 ...
   File "/tmp/transformers-no-threadlocal-MxpTSt/src/transformers/generation/continuous_batching/continuous_api.py", line 470, in _generation_step
     with torch.cuda.graph(
 ...
 torch.AcceleratorError: CUDA error: operation failed due to a previous error during capture

 And the test-level failure is:

 AssertionError: Repro failed on cuda:0, cuda:1:

 Traceback (most recent call last):
   File "/root/transformers/tests/generation/test_continuous_batching_llama32_nogil_repro.py", line 182, in worker
     self.assertEqual(output.status, RequestStatus.FINISHED)
 AssertionError: <RequestStatus.FAILED: 4> != <RequestStatus.FINISHED: 3>

DEVICES = ("cuda:0", "cuda:1")
MAX_NEW_TOKENS = 512
REQUEST_TIMEOUT_SECONDS = 600


def _nogil_is_enabled() -> tuple[bool, str]:
if os.environ.get("PYTHON_GIL") != "0":
return False, "Launch this test with PYTHON_GIL=0 before Python starts."

gil_flag = getattr(sys.flags, "gil", None)
if gil_flag is not None:
return gil_flag == 0, f"sys.flags.gil={gil_flag}"

is_gil_enabled = getattr(sys, "_is_gil_enabled", None)
if callable(is_gil_enabled):
gil_enabled = is_gil_enabled()
if gil_enabled:
return (
False,
"sys._is_gil_enabled()=True. On CPython free-threading builds, start the interpreter with "
"PYTHON_GIL=0 or -Xgil=0 so the GIL stays disabled.",
)
return not gil_enabled, f"sys._is_gil_enabled()={gil_enabled}"

py_gil_disabled = sysconfig.get_config_var("Py_GIL_DISABLED")
if py_gil_disabled == 1:
return True, "Detected a free-threaded Python build via Py_GIL_DISABLED=1."

abi_flags = getattr(sys, "abiflags", "")
if "t" in abi_flags:
return True, f"Detected free-threaded ABI flags: {abi_flags!r}"

return False, "Could not verify that this interpreter has the GIL disabled."


def _wait_for_terminal_output(
manager, request_id: str, timeout_seconds: float = REQUEST_TIMEOUT_SECONDS
) -> GenerationOutput:
deadline = time.perf_counter() + timeout_seconds
last_result = None

while time.perf_counter() < deadline:
result = manager.get_result(request_id=request_id, timeout=0.5)
if result is None:
if not manager.is_running():
break
continue

last_result = result
if result.status in (RequestStatus.FINISHED, RequestStatus.FAILED):
return result

if last_result is not None:
raise TimeoutError(
f"Timed out waiting for terminal output for {request_id}. Last status was {last_result.status.name}."
)
raise TimeoutError(f"Timed out waiting for any output for {request_id}.")


@dataclass
class WorkerResult:
device: str
request_id: str
output: GenerationOutput
decoded_text: str


class ContinuousBatchingLlama32NogilReproTest(unittest.TestCase):
def test_two_thread_llama32_continuous_batching_cuda_graph_repro(self) -> None:
"""Repro for two concurrent continuous-batching managers under a no-GIL interpreter."""
nogil_enabled, nogil_reason = _nogil_is_enabled()
self.assertTrue(
nogil_enabled,
f"This repro requires a no-GIL interpreter with GIL disabled. Details: {nogil_reason}",
)
self.assertEqual(os.environ.get("PYTHON_GIL"), "0")
self.assertTrue(torch.cuda.is_available(), "This repro requires CUDA.")
self.assertGreaterEqual(torch.cuda.device_count(), 2, "This repro requires at least 2 CUDA devices.")
self.assertTrue(os.path.isdir(MODEL_PATH), f"Model path not found: {MODEL_PATH}")
self.assertTrue(
is_flash_attn_2_available() or is_kernels_available(),
"This repro requires Flash Attention 2 support.",
)

barrier = threading.Barrier(len(DEVICES) + 1)
results: dict[str, WorkerResult] = {}
failures: dict[str, str] = {}

def worker(device: str, prompt: str) -> None:
try:
torch.cuda.set_device(device)

tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, padding_side="left")
if tokenizer.pad_token is None and tokenizer.eos_token is not None:
tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(
MODEL_PATH,
attn_implementation="paged|flash_attention_2",
torch_dtype="auto",
)
model = model.to(device).eval()
self.assertEqual(model.config._attn_implementation, "paged|flash_attention_2")

generation_config = GenerationConfig(
do_sample=False,
eos_token_id=-1,
max_new_tokens=MAX_NEW_TOKENS,
pad_token_id=tokenizer.pad_token_id,
)
continuous_batching_config = ContinuousBatchingConfig(
block_size=32,
num_blocks=64,
max_batch_tokens=1024,
allow_block_sharing=False,
use_async_batching=False,
use_cuda_graph=True,
)

messages = [{"role": "user", "content": prompt}]
input_ids = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt",
return_dict=False,
)[0].tolist()

with model.continuous_batching_context_manager(
generation_config=generation_config,
continuous_batching_config=continuous_batching_config,
) as manager:
self.assertEqual(manager.model.config._attn_implementation, "paged|flash_attention_2")

barrier.wait()

request_id = manager.add_request(
input_ids=input_ids,
max_new_tokens=MAX_NEW_TOKENS,
streaming=False,
eos_token_id=-1,
)
output = _wait_for_terminal_output(manager, request_id)

decoded_text = tokenizer.decode(output.generated_tokens, skip_special_tokens=True)
self.assertEqual(output.status, RequestStatus.FINISHED)
self.assertIsNone(output.error, output.error)
self.assertEqual(len(output.generated_tokens), MAX_NEW_TOKENS)
self.assertTrue(decoded_text.strip(), f"{device} produced empty decoded output.")

results[device] = WorkerResult(
device=device,
request_id=request_id,
output=output,
decoded_text=decoded_text,
)
except Exception:
failures[device] = traceback.format_exc()
finally:
if torch.cuda.is_available():
torch.cuda.empty_cache()

prompts = {
"cuda:0": "Write a long numbered outline about thread-local CUDA graph capture behavior. Keep going.",
"cuda:1": "Write a long numbered outline about isolated continuous batching managers on separate GPUs. Keep going.",
}
threads = [threading.Thread(target=worker, args=(device, prompts[device]), name=f"repro-{device}") for device in DEVICES]

for thread in threads:
thread.start()

barrier.wait()

for thread in threads:
thread.join(timeout=REQUEST_TIMEOUT_SECONDS)
self.assertFalse(thread.is_alive(), f"Worker thread {thread.name} did not finish.")

if failures:
devices = ", ".join(sorted(failures))
self.fail(f"Repro failed on {devices}:\n\n" + "\n".join(failures[device] for device in sorted(failures)))

self.assertEqual(set(results), set(DEVICES), f"Expected results for {DEVICES}, got {sorted(results)}")
for device in DEVICES:
result = results[device]
self.assertEqual(result.output.status, RequestStatus.FINISHED)
self.assertEqual(len(result.output.generated_tokens), MAX_NEW_TOKENS)
self.assertTrue(result.decoded_text.strip(), f"{device} produced empty decoded output.")