[Hardware] Replace torch.cuda.device_count/current_device/set_device API (#36145)

Signed-off-by: Kunshang Ji <jikunshang95@gmail.com>
Signed-off-by: Kunshang Ji <kunshang.ji@intel.com>
This commit is contained in:
Kunshang Ji
2026-03-12 07:57:47 -07:00
committed by GitHub
parent 2e693f48e7
commit 53ec16a705
89 changed files with 254 additions and 219 deletions
@@ -491,7 +491,7 @@ class FlashInferAllToAllManager(All2AllManagerBase):
self.initialize(
world_size=self.world_size,
rank=self.rank,
gpus_per_node=torch.cuda.device_count,
gpus_per_node=torch.accelerator.device_count,
)
return self.initialized
@@ -151,7 +151,7 @@ class nccl_symm_mem_context:
self.pynccl_comm = pynccl_comm
self._mem_pool_ctx = torch.cuda.use_mem_pool(get_nccl_mem_pool())
self.is_graph_capture = torch.cuda.is_current_stream_capturing()
self.device = torch.cuda.current_device()
self.device = torch.accelerator.current_device_index()
def __enter__(self):
if self.disabled:
@@ -50,7 +50,7 @@ class SymmMemCommunicator:
device = torch.device(f"cuda:{device}")
elif isinstance(device, str):
device = torch.device(device)
torch.cuda.set_device(device)
torch.accelerator.set_device_index(device)
self.dtype = torch.bfloat16
self.device = device
self.group = group
+1 -1
View File
@@ -33,7 +33,7 @@ def start_async_worker(
def thread_target() -> None:
assert device_index is not None
torch.cuda.set_device(device_index)
torch.accelerator.set_device_index(device_index)
cuda_stream = torch.cuda.Stream(device=device_index)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
+1 -1
View File
@@ -314,7 +314,7 @@ class EplbState:
if self.device.type == "cuda":
self.cuda_device_index = self.device.index
if self.cuda_device_index is None and torch.cuda.is_available():
self.cuda_device_index = torch.cuda.current_device()
self.cuda_device_index = torch.accelerator.current_device_index()
@staticmethod
def build_initial_global_physical_to_logical_map(
@@ -483,9 +483,9 @@ def _init_lmcache_engine(
)
# Change current device.
num_gpus = torch.cuda.device_count()
num_gpus = torch.accelerator.device_count()
local_rank = parallel_config.rank % num_gpus
torch.cuda.set_device(local_rank)
torch.accelerator.set_device_index(local_rank)
device = torch.device(f"cuda:{local_rank}")
metadata = LMCacheEngineMetadata(
model_config.model,
@@ -169,7 +169,7 @@ class IPCWeightTransferEngine(
update_info.shapes,
update_info.ipc_handles,
):
device_index = torch.cuda.current_device()
device_index = torch.accelerator.current_device_index()
props = torch.cuda.get_device_properties(device_index)
physical_gpu_id = str(props.uuid)
@@ -242,7 +242,7 @@ class IPCWeightTransferEngine(
args = trainer_args
# Get physical GPU UUID
device_index = torch.cuda.current_device()
device_index = torch.accelerator.current_device_index()
props = torch.cuda.get_device_properties(device_index)
gpu_uuid = str(props.uuid)
@@ -140,13 +140,14 @@ class NCCLWeightTransferEngine(
worker_rank = dp_rank * world_size_per_dp + rank_within_dp
rank = worker_rank + init_info.rank_offset
# Create stateless process group
device = torch.accelerator.current_device_index()
self.model_update_group = (
NCCLWeightTransferEngine._stateless_init_process_group(
init_info.master_address,
init_info.master_port,
rank,
init_info.world_size,
torch.cuda.current_device(),
device=device,
)
)
@@ -275,7 +276,7 @@ class NCCLWeightTransferEngine(
Initialize NCCL process group for trainer-side weight transfer.
The trainer is always rank 0 in the process group. Uses the current
CUDA device (torch.cuda.current_device()).
CUDA device (torch.accelerator.current_device_index()).
Args:
init_info: Either an NCCLWeightTransferInitInfo object or a dict with keys:
@@ -309,8 +310,13 @@ class NCCLWeightTransferEngine(
world_size = init_info.world_size
# Trainer is always rank 0
device = torch.accelerator.current_device_index()
return NCCLWeightTransferEngine._stateless_init_process_group(
master_address, master_port, 0, world_size, torch.cuda.current_device()
master_address,
master_port,
0,
world_size,
device,
)
@staticmethod
@@ -190,7 +190,7 @@ class StaticSinkAttention(Attention, CustomOp):
sink_kv_slot_mapping = torch.arange(
self.block_size,
self.sink_len + self.block_size,
device=torch.cuda.current_device(),
device=torch.accelerator.current_device_index(),
dtype=torch.long,
)
triton_reshape_and_cache_flash_diffkv(
@@ -295,14 +295,17 @@ class DefaultMoERunner(MoERunner):
states_shape = (moe.max_num_tokens, self.moe_config.hidden_dim)
logits_shape = (moe.max_num_tokens, self.moe_config.num_logical_experts)
device = torch.accelerator.current_device_index()
self.batched_hidden_states = torch.zeros(
states_shape, dtype=moe.in_dtype, device=torch.cuda.current_device()
states_shape,
dtype=moe.in_dtype,
device=device,
)
self.batched_router_logits = torch.zeros(
logits_shape,
dtype=moe.router_logits_dtype,
device=torch.cuda.current_device(),
device=device,
)
def must_reduce_shared_expert_outputs(self) -> bool:
@@ -28,7 +28,7 @@ class TrtLlmGenExperts(mk.FusedMoEExpertsModular):
max_capture_size,
):
super().__init__(moe_config, quant_config)
self.device = torch.cuda.current_device()
self.device = torch.accelerator.current_device_index()
self.num_experts = moe_config.num_local_experts
self.gemm1_alpha = torch.tensor(
[1.702] * self.num_experts, dtype=torch.float32, device=self.device
+1 -1
View File
@@ -202,7 +202,7 @@ class RMSNorm(CustomOp):
# external Oink initialization work in this case.
else:
try:
device_index = torch.cuda.current_device()
device_index = torch.accelerator.current_device_index()
if _oink_ops.is_oink_available_for_device(device_index):
self._use_oink_rmsnorm = True
self._use_oink_fused_add_rmsnorm = (
@@ -36,7 +36,8 @@ class DualChunkRotaryEmbedding(CustomOp):
self.chunk_size = chunk_size
self.local_size = local_size
self.dtype = dtype
self.device = torch.device(f"cuda:{torch.cuda.current_device()}")
device_idx = torch.accelerator.current_device_index()
self.device = torch.device(f"cuda:{device_idx}")
(q_cache, qc_cache, k_cache, qc_no_clamp_cache, q_inter_cache) = (
self._compute_cos_sin_cache()
)
@@ -539,6 +539,8 @@ def deserialize_tensorizer_model(
)
before_mem = get_mem_usage()
start = time.perf_counter()
device_index = torch.accelerator.current_device_index()
device_type = current_platform.device_type
with (
open_stream(
tensorizer_config.tensorizer_uri, mode="rb", **tensorizer_args.stream_kwargs
@@ -546,9 +548,7 @@ def deserialize_tensorizer_model(
TensorDeserializer(
stream,
dtype=tensorizer_config.dtype,
device=f"xpu:{torch.xpu.current_device()}"
if current_platform.is_xpu()
else f"cuda:{torch.cuda.current_device()}",
device=f"{device_type}:{device_index}",
**tensorizer_args.deserialization_kwargs,
) as deserializer,
):
+1 -1
View File
@@ -624,7 +624,7 @@ def cuda_device_count_stateless() -> int:
"""Get number of CUDA devices, caching based on the value of
CUDA_VISIBLE_DEVICES at the time of call.
This should be used instead of torch.cuda.device_count()
This should be used instead of torch.accelerator.device_count()
unless CUDA_VISIBLE_DEVICES has already been set to the desired
value."""
+1 -1
View File
@@ -134,7 +134,7 @@ class CoreEngineProcManager:
for proc, local_dp_rank in zip(self.processes, local_dp_ranks):
# Adjust device control in DP for non-CUDA platforms
# as well as external and ray launchers
# For CUDA platforms, we use torch.cuda.set_device()
# For CUDA platforms, we use torch.accelerator.set_device_index()()
if is_dp and (
not current_platform.is_cuda_alike()
or vllm_config.parallel_config.use_ray
+3 -3
View File
@@ -73,8 +73,8 @@ class SMControlContextManager:
assert current_platform.is_cuda(), (
"SM control is currently only supported on CUDA"
)
total_sms = num_compute_units(torch.cuda.current_device())
device = torch.accelerator.current_device_index()
total_sms = num_compute_units(device)
assert comm_sms < total_sms
self.total_sms = total_sms
@@ -204,7 +204,7 @@ class UBatchWrapper:
@torch.inference_mode()
def _capture_ubatch_thread(results, ubatch_metadata):
torch.cuda.set_device(self.device)
torch.accelerator.set_device_index(self.device)
ubatch_context = ubatch_metadata.context
with torch.cuda.stream(ubatch_context.compute_stream):
_ = torch.cuda.current_blas_handle()
+3 -3
View File
@@ -239,11 +239,11 @@ class Worker(WorkerBase):
# DP_LOCAL_RANK * TP_PP_WORLD_SIZE + TP_LOCAL_RANK
self.local_rank += dp_local_rank * tp_pp_world_size
assert self.local_rank < torch.cuda.device_count(), (
assert self.local_rank < torch.accelerator.device_count(), (
f"DP adjusted local rank {self.local_rank} is out of bounds. "
)
visible_device_count = (
torch.cuda.device_count() if torch.cuda.is_available() else 0
torch.accelerator.device_count() if torch.cuda.is_available() else 0
)
assert self.parallel_config.local_world_size <= visible_device_count, (
f"local_world_size ({self.parallel_config.local_world_size}) must "
@@ -252,7 +252,7 @@ class Worker(WorkerBase):
)
self.device = torch.device(f"cuda:{self.local_rank}")
current_platform.set_device(self.device)
torch.accelerator.set_device_index(self.device)
current_platform.check_if_supports_dtype(self.model_config.dtype)
+1 -1
View File
@@ -60,7 +60,7 @@ class XPUWorker(Worker):
and current_platform.is_xpu()
):
self.device = torch.device(f"xpu:{self.local_rank}")
current_platform.set_device(self.device)
torch.accelerator.set_device_index(self.device)
current_platform.check_if_supports_dtype(self.model_config.dtype)
torch.accelerator.empty_cache()
self.init_gpu_memory = torch.xpu.get_device_properties(