[Refactor] Replace and ban a few torch.cuda functions in favor of torch.accelerator replacements. (#3365)

Signed-off-by: Nick Cao <ncao@redhat.com>
This commit is contained in:
Nick Cao authored and GitHub committed 2026-05-07 23:23:59 +08:00
1 parent 54277a8dd0
commit e6466cf0e6
40 files changed
+98 -90

No files matched your search

@@ -57,7 +57,7 @@ DEPLOY_CONFIGS_DIR = Path(__file__).resolve().parent.parent.parent.parent / "vll
def _default_oom_device_spec() -> str:
"""Use currently visible CUDA ordinals to avoid invalid device index in sidecar."""
count = torch.cuda.device_count()
count = torch.accelerator.device_count()
if count <= 0:
return "0"
return ",".join(str(i) for i in range(count))
@@ -104,7 +104,7 @@ def _generate_image(omni, config: QualityTestConfig):
generator = torch.Generator(
device=current_omni_platform.device_type,
).manual_seed(config.seed)
torch.cuda.reset_peak_memory_stats()
torch.accelerator.reset_peak_memory_stats()
outputs = omni.generate(
{"prompt": config.prompt},
@@ -116,7 +116,7 @@ def _generate_image(omni, config: QualityTestConfig):
),
)
peak_mem = torch.cuda.max_memory_allocated() / (1024**3)
peak_mem = torch.accelerator.max_memory_allocated() / (1024**3)
first = outputs[0]
if hasattr(first, "images") and first.images:
return first.images[0], peak_mem
@@ -135,7 +135,7 @@ def _generate_video(omni, config: QualityTestConfig):
generator = torch.Generator(
device=current_omni_platform.device_type,
).manual_seed(config.seed)
torch.cuda.reset_peak_memory_stats()
torch.accelerator.reset_peak_memory_stats()
outputs = omni.generate(
{"prompt": config.prompt, "negative_prompt": ""},
@@ -148,7 +148,7 @@ def _generate_video(omni, config: QualityTestConfig):
),
)
peak_mem = torch.cuda.max_memory_allocated() / (1024**3)
peak_mem = torch.accelerator.max_memory_allocated() / (1024**3)
first = outputs[0]
if hasattr(first, "request_output") and isinstance(first.request_output, list):
inner = first.request_output[0]
@@ -190,8 +190,8 @@ def _unload(omni):
del omni
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
torch.accelerator.empty_cache()
torch.accelerator.synchronize()
# ---------------------------------------------------------------------------
+4 -4
View File
@@ -371,7 +371,7 @@ class TestCustomPipelineWorkerExtension:
def test_re_init_pipeline_basic(self, mocker: MockerFixture, mock_od_config):
"""Test basic re_init_pipeline functionality."""
mocker.patch("torch.cuda.empty_cache")
mocker.patch("torch.accelerator.empty_cache")
mocker.patch("gc.collect")
mocker.patch.object(DiffusionWorker, "__init__", return_value=None)
@@ -405,7 +405,7 @@ class TestCustomPipelineWorkerExtension:
def test_re_init_pipeline_cleanup(self, mocker: MockerFixture, mock_od_config):
"""Test that re_init_pipeline properly cleans up old pipeline."""
mock_gc_collect = mocker.patch("gc.collect")
mock_empty_cache = mocker.patch("torch.cuda.empty_cache")
mock_empty_cache = mocker.patch("torch.accelerator.empty_cache")
mocker.patch.object(DiffusionWorker, "__init__", return_value=None)
wrapper = WorkerWrapperBase(
@@ -434,7 +434,7 @@ class TestCustomPipelineWorkerExtension:
def test_re_init_pipeline_none_pipeline(self, mocker: MockerFixture, mock_od_config):
"""Test re_init_pipeline when pipeline is None."""
mocker.patch("torch.cuda.empty_cache")
mocker.patch("torch.accelerator.empty_cache")
mocker.patch("gc.collect")
mocker.patch.object(DiffusionWorker, "__init__", return_value=None)
@@ -510,7 +510,7 @@ class TestCustomPipelineWorkerExtension:
def test_re_init_pipeline_multiple_calls(self, mocker: MockerFixture, mock_od_config):
"""Test calling re_init_pipeline multiple times."""
mocker.patch("torch.cuda.empty_cache")
mocker.patch("torch.accelerator.empty_cache")
mocker.patch("gc.collect")
mocker.patch.object(DiffusionWorker, "__init__", return_value=None)
+1 -1
View File
@@ -230,7 +230,7 @@ def _build_accuracy_server_config(
run_level: str,
model_prefix: str,
) -> AccuracyServerConfig:
if torch.cuda.device_count() < 1:
if torch.accelerator.device_count() < 1:
pytest.skip("Need at least 1 CUDA GPU for accuracy benchmark smoke tests.")
if not generate_model:
@@ -160,7 +160,7 @@ def _run_diffusers_wan22_i2v(*, model: str, output_path: Path, conditioning_imag
del pipe
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
run_post_test_cleanup(enable_force=True)
@@ -240,7 +240,7 @@ def _run_diffusers_qwen_image(*, model: str, output_path: Path) -> tuple[Image.I
del pipe
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
run_post_test_cleanup(enable_force=True)
@@ -199,7 +199,7 @@ def _run_diffusers_baseline(model: str, output_dir: Path) -> list[Image.Image]:
del pipe
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
run_post_test_cleanup(enable_force=True)
@@ -278,7 +278,7 @@ def _run_with_custom_transformer(model: str, output_dir: Path) -> list[Image.Ima
del pipe, result, our_transformer
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
return frames
+1 -1
View File
@@ -98,7 +98,7 @@ def _run_diffusers_qwen_image(*, model: str, output_path: Path) -> Image.Image:
del pipe
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
run_post_test_cleanup(enable_force=True)
+1 -1
View File
@@ -109,7 +109,7 @@ def _run_diffusers_image_edit(
del pipe
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
run_post_test_cleanup(enable_force=True)
@@ -125,7 +125,7 @@ def _run_diffusers_qwen_image_layered(*, model: str, input_image: Image.Image, o
del pipe
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
run_post_test_cleanup(enable_force=True)
@@ -572,7 +572,7 @@ def test_wan22_i2v_online_serving_generates_video(
wan22_i2v_image_source: str | None,
wan22_i2v_online_timeout_seconds: int,
) -> None:
if not torch.cuda.is_available() or torch.cuda.device_count() < 2:
if not torch.cuda.is_available() or torch.accelerator.device_count() < 2:
pytest.skip("Wan2.2 I2V similarity e2e test requires >= 2 CUDA GPUs.")
_probe_binary("ffprobe")
@@ -597,7 +597,7 @@ def test_wan22_i2v_online_serving_generates_video(
def test_wan22_i2v_serving_matches_diffusers_video_similarity(
wan22_i2v_image_source: str | None,
) -> None:
if not torch.cuda.is_available() or torch.cuda.device_count() < 2:
if not torch.cuda.is_available() or torch.accelerator.device_count() < 2:
pytest.skip("Wan2.2 I2V similarity e2e test requires >= 2 CUDA GPUs.")
_probe_binary("ffmpeg")
@@ -327,7 +327,7 @@ def _generate_image(omni: Omni, use_system_prompt: str | None) -> Image.Image:
return _extract_generated_image(outputs)
@pytest.mark.skipif(torch.cuda.device_count() < 8, reason="Need at least 8 CUDA GPUs for this test.")
@pytest.mark.skipif(torch.accelerator.device_count() < 8, reason="Need at least 8 CUDA GPUs for this test.")
@pytest.mark.parametrize("system_prompt_name,use_system_prompt,expected_embedding", SYSTEM_PROMPT_CASES)
def test_system_prompt_scores(
omni: Omni,
@@ -26,7 +26,7 @@ def get_ack_info(ack, key, default=None):
def get_dynamic_devices(stage_idx, num_stages, tp_size):
total_gpus = torch.cuda.device_count()
total_gpus = torch.accelerator.device_count()
gpus_per_stage = tp_size
start_idx = stage_idx * gpus_per_stage
if start_idx + gpus_per_stage > total_gpus:
@@ -42,7 +42,7 @@ def get_dynamic_devices(stage_idx, num_stages, tp_size):
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=1)
@pytest.mark.asyncio
async def test_diffusion_model_sleep_tp(tp_size):
num_gpus = torch.cuda.device_count()
num_gpus = torch.accelerator.device_count()
if num_gpus < tp_size:
pytest.skip(f"Skipping TP={tp_size}")
@@ -88,7 +88,7 @@ async def test_diffusion_model_sleep_tp(tp_size):
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.asyncio
async def test_multistage_sleep_h100(tp_size):
num_gpus = torch.cuda.device_count()
num_gpus = torch.accelerator.device_count()
if num_gpus < tp_size * 2:
pytest.skip("Not enough GPUs")
@@ -67,7 +67,7 @@ def _generate_single_stage_image(
omni_kwargs["quantization"] = quantization
with OmniRunner(model, **omni_kwargs) as runner:
torch.cuda.reset_peak_memory_stats()
torch.accelerator.reset_peak_memory_stats()
generator = torch.Generator(device=current_omni_platform.device_type).manual_seed(seed)
outputs = runner.omni.generate(
@@ -81,7 +81,7 @@ def _generate_single_stage_image(
),
)
peak_mem = torch.cuda.max_memory_allocated() / (1024**3)
peak_mem = torch.accelerator.max_memory_allocated() / (1024**3)
first_output = outputs[0]
assert first_output.final_output_type == "image"
@@ -116,7 +116,7 @@ def _generate_bagel_image(
model_name = omni_kwargs.pop("model")
with OmniRunner(model_name, **omni_kwargs) as runner:
omni = runner.omni
torch.cuda.reset_peak_memory_stats()
torch.accelerator.reset_peak_memory_stats()
params_list = omni.default_sampling_params_list
if len(params_list) > 1:
@@ -134,7 +134,7 @@ def _generate_bagel_image(
)
)
peak_mem = torch.cuda.max_memory_allocated() / (1024**3)
peak_mem = torch.accelerator.max_memory_allocated() / (1024**3)
# Extract image
generated_image = None
@@ -190,7 +190,7 @@ def test_single_stage_zimage_fp8_uses_less_memory():
model="Tongyi-MAI/Z-Image-Turbo",
quantization=None,
)
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
_, mem_fp8 = _generate_single_stage_image(
model="Tongyi-MAI/Z-Image-Turbo",
@@ -241,7 +241,7 @@ def test_single_stage_flux_fp8_uses_less_memory():
width=512,
num_inference_steps=4,
)
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
_, mem_fp8 = _generate_single_stage_image(
model="black-forest-labs/FLUX.1-dev",
+8 -8
View File
@@ -33,16 +33,16 @@ def get_vram_info(device_id: int) -> dict:
"""Obtain a snapshot of the specified GPU's memory (GiB)."""
try:
if current_omni_platform.is_rocm():
num_gpus = torch.cuda.device_count()
num_gpus = torch.accelerator.device_count()
safe_id = device_id if device_id < num_gpus else 0
torch.cuda.synchronize(safe_id)
torch.accelerator.synchronize(safe_id)
return {
"reserved": torch.cuda.memory_reserved(safe_id) / 1024**3,
"allocated": torch.cuda.memory_allocated(safe_id) / 1024**3,
}
else:
with torch.cuda.device(device_id):
torch.cuda.synchronize()
torch.accelerator.synchronize()
return {
"reserved": torch.cuda.memory_reserved() / 1024**3,
"allocated": torch.cuda.memory_allocated() / 1024**3,
@@ -240,7 +240,7 @@ class TestOmniSleepMode:
await diffusion_engine.wake_up(stage_ids=[0])
get_vram_info(device_id)
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
await asyncio.sleep(2)
initial_vram = get_vram_info(device_id)["reserved"]
@@ -253,7 +253,7 @@ class TestOmniSleepMode:
await diffusion_engine.sleep(stage_ids=[0], level=2)
await asyncio.sleep(3.0)
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
final_vram = get_vram_info(device_id)["reserved"]
logger.info(f"GPU {device_id} Final VRAM after coordinated sleep: {final_vram:.2f} GiB")
@@ -276,7 +276,7 @@ class TestOmniSleepMode:
device_id = 1
try:
get_vram_info(device_id)
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
vram_initial = get_vram_info(device_id)["reserved"]
logger.info(f"Diffusion Initial VRAM: {vram_initial:.2f} GiB")
@@ -290,7 +290,7 @@ class TestOmniSleepMode:
await asyncio.sleep(2)
get_vram_info(device_id)
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
vram_sleeping = get_vram_info(device_id)["reserved"]
logger.info(f"External VRAM measurement during Sleep: {vram_sleeping:.2f} GiB")
@@ -305,7 +305,7 @@ class TestOmniSleepMode:
await asyncio.sleep(2)
get_vram_info(device_id)
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
vram_restored = get_vram_info(device_id)["reserved"]
logger.info(f"VRAM after Wake-up: {vram_restored:.2f} GiB")
+3 -3
View File
@@ -130,7 +130,7 @@ def wait_for_gpu_memory_to_clear(
)
gc.collect()
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
time.sleep(5)
@@ -244,7 +244,7 @@ def run_pre_test_cleanup(enable_force: bool = False) -> None:
print("Pre-test GPU status:")
num_gpus = torch.cuda.device_count()
num_gpus = torch.accelerator.device_count()
if num_gpus > 0:
try:
wait_for_gpu_memory_to_clear(
@@ -262,7 +262,7 @@ def run_post_test_cleanup(enable_force: bool = False) -> None:
if torch.cuda.is_available():
gc.collect()
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
print("Post-test GPU status:")
_print_gpu_processes()
+2 -2
View File
@@ -11,7 +11,7 @@ def default_env():
previous = {key: os.environ.get(key) for key in keys}
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = previous["VLLM_WORKER_MULTIPROC_METHOD"] or "spawn"
os.environ["VLLM_TARGET_DEVICE"] = previous["VLLM_TARGET_DEVICE"] or (
"cuda" if torch.cuda.is_available() and torch.cuda.device_count() > 0 else "cpu"
"cuda" if torch.cuda.is_available() and torch.accelerator.device_count() > 0 else "cpu"
)
yield
for key, value in previous.items():
@@ -51,7 +51,7 @@ def default_vllm_config():
from vllm.config import DeviceConfig, VllmConfig, set_current_vllm_config
# Use CPU device if no GPU is available (e.g., in CI environments)
has_gpu = torch.cuda.is_available() and torch.cuda.device_count() > 0
has_gpu = torch.cuda.is_available() and torch.accelerator.device_count() > 0
device = "cuda" if has_gpu else "cpu"
device_config = DeviceConfig(device=device)
@@ -46,7 +46,7 @@ def _warmup_pipeline(cfm: CFM, aggregator: Aggregator, stop_head: torch.nn.Linea
gen_lat = cfm.sample(llm_cond, lat_cond, y0, t, sde_args, sde_rnd)
aggregator(gen_lat)
stop_head(llm_cond[:, -1, :]).softmax(dim=-1)
torch.cuda.synchronize(device)
torch.accelerator.synchronize(device)
def _build_pipeline():
@@ -95,7 +95,7 @@ class TestCFMGraphExecutor:
his_lat = torch.randn(bsz, _HIS_PATCH_SIZE, _LATENT_DIM, device=device, dtype=_DTYPE)
gen_lat, inputs_embeds, stop_out = executor.execute(input_tensor, his_lat)
torch.cuda.synchronize()
torch.accelerator.synchronize()
assert gen_lat.shape == (bsz, _PATCH_SIZE, _LATENT_DIM)
assert inputs_embeds.shape == (bsz, 1, _LLM_HIDDEN)
@@ -109,7 +109,7 @@ class TestCFMGraphExecutor:
new_input = torch.randn_like(input_tensor)
new_his = torch.randn_like(his_lat)
gen_lat2, inputs_embeds2, stop_out2 = executor.execute(new_input, new_his)
torch.cuda.synchronize()
torch.accelerator.synchronize()
assert gen_lat2.shape == gen_lat.shape
assert inputs_embeds2.shape == inputs_embeds.shape
assert stop_out2.shape == stop_out.shape
@@ -125,7 +125,7 @@ class TestCFMGraphExecutor:
snapshot_his = his_lat.clone()
executor.execute(input_tensor, his_lat)
torch.cuda.synchronize()
torch.accelerator.synchronize()
assert torch.equal(input_tensor, snapshot_input)
assert torch.equal(his_lat, snapshot_his)
@@ -139,7 +139,7 @@ class TestCFMGraphExecutorPool:
his_lat = torch.randn(1, _HIS_PATCH_SIZE, _LATENT_DIM, device=device, dtype=_DTYPE)
gen_lat, inputs_embeds, stop_out = pool.execute(input_tensor, his_lat)
torch.cuda.synchronize()
torch.accelerator.synchronize()
assert gen_lat.shape == (1, _PATCH_SIZE, _LATENT_DIM)
assert inputs_embeds.shape == (1, 1, _LLM_HIDDEN)
assert stop_out.shape == (1, 2)
+1 -1
View File
@@ -68,7 +68,7 @@ class TestGetProcessGpuMemory:
assert memory >= 0
del tensor
torch.cuda.empty_cache()
torch.accelerator.empty_cache()
def test_raises_on_invalid_device(self, mocker: MockerFixture):
from vllm_omni.worker.gpu_memory_utils import get_process_gpu_memory