[Feat][XPU] VLLM_BATCH_INVARIANT support for Dense/MoE models (#55881)

Signed-off-by: Tony Lin <tony.lin@intel.com>
Co-authored-by: Flora Feng <4florafeng@gmail.com>
This commit is contained in:
Tony Lin
2026-09-22 11:06:54 -04:00
committed by GitHub
co-authored by Flora Feng
parent 1ea7c63f4a
commit e4340e41c9
10 changed files with 619 additions and 8 deletions
@@ -6,6 +6,7 @@ import torch
import torch.distributed as dist
from torch.distributed import ProcessGroup
import vllm.envs as envs
from vllm.logger import init_logger
from .base_device_communicator import DeviceCommunicatorBase
@@ -45,7 +46,25 @@ class XpuCommunicator(DeviceCommunicatorBase):
self.all2all_manager = AgRsAll2AllManager(self.cpu_group)
logger.info("Using AgRs manager on XPU device.")
def _fixed_rank_sum(self, input_: torch.Tensor) -> torch.Tensor:
flat_input = input_.reshape(-1)
gathered = torch.empty(
(self.world_size, flat_input.numel()),
dtype=input_.dtype,
device=input_.device,
)
dist.all_gather_single(gathered.view(-1), flat_input, group=self.device_group)
output = gathered[0].clone()
for rank in range(1, self.world_size):
output.add_(gathered[rank])
return output.view(input_.shape)
def all_reduce(self, input_: torch.Tensor) -> torch.Tensor:
if envs.VLLM_BATCH_INVARIANT:
# XCCL changes its reduction order with message size. Gather first
# and accumulate in rank order, independent of the token batch.
return self._fixed_rank_sum(input_)
output = input_.clone()
dist.all_reduce(output, group=self.device_group)
return output
@@ -69,7 +88,12 @@ class XpuCommunicator(DeviceCommunicatorBase):
output_shape, dtype=input_tensor.dtype, device=input_tensor.device
)
dist.reduce_scatter_tensor(output, input_tensor, group=self.device_group)
if envs.VLLM_BATCH_INVARIANT:
reduced = self._fixed_rank_sum(input_tensor)
start = self.rank_in_group * chunk_size
output.copy_(reduced.narrow(0, start, chunk_size))
else:
dist.reduce_scatter_tensor(output, input_tensor, group=self.device_group)
# Reshape before returning
return output.movedim(0, dim).contiguous()
@@ -99,7 +123,15 @@ class XpuCommunicator(DeviceCommunicatorBase):
output = torch.empty(
output_shape, dtype=input_tensor.dtype, device=input_tensor.device
)
if sizes is None or sizes.count(sizes[0]) == len(sizes):
if envs.VLLM_BATCH_INVARIANT:
reduced = self._fixed_rank_sum(input_tensor)
start = (
self.rank_in_group * chunk_size
if sizes is None
else sum(sizes[: self.rank_in_group])
)
output.copy_(reduced.narrow(0, start, chunk_size))
elif sizes is None or sizes.count(sizes[0]) == len(sizes):
dist.reduce_scatter_tensor(output, input_tensor, group=self.device_group)
elif torch.xpu.device_count() < self.world_size:
# uneven reduce_scatter is not supported when the
@@ -191,7 +223,7 @@ class XpuCommunicator(DeviceCommunicatorBase):
(self.world_size,) + input_size, dtype=input_.dtype, device=input_.device
)
# All-gather.
dist.all_gather_into_tensor(output_tensor, input_, group=self.device_group)
dist.all_gather_single(output_tensor, input_, group=self.device_group)
if self.rank_in_group == dst:
# Reshape
output_tensor = output_tensor.movedim(0, dim)
@@ -1104,7 +1104,10 @@ def enable_batch_invariant_mode():
_fp16_block_size_n = 128
# Softmax, log_softmax, mean, and bmm are already batch-invariant on XPU
# Native mean can change reduction order with the row count on XPU too.
_batch_invariant_LIB.impl("aten::mean.dim", mean_batch_invariant, key)
# Softmax, log_softmax, and bmm are already batch-invariant on XPU
# (oneDNN backend produces bitwise-identical results regardless of batch
# context). Only register these overrides on CUDA where they are needed.
if not current_platform.is_xpu():
@@ -1113,7 +1116,6 @@ def enable_batch_invariant_mode():
)
_batch_invariant_LIB.impl("aten::softmax", softmax_batch_invariant, key)
_batch_invariant_LIB.impl("aten::_softmax", softmax_batch_invariant, key)
_batch_invariant_LIB.impl("aten::mean.dim", mean_batch_invariant, key)
# torch 2.12+ registers a built-in Triton bmm kernel for CUDA
# (torch._native.ops.bmm_outer_product), so we need allow_override
# to replace it at the dispatcher level.
@@ -94,7 +94,13 @@ def _get_priority_backends(moe_config: FusedMoEConfig) -> list[UnquantizedMoeBac
_move_to_back(_AVAILABLE_BACKENDS, UnquantizedMoeBackend.FLASHINFER_CUTLASS)
elif current_platform.is_xpu():
_AVAILABLE_BACKENDS = [UnquantizedMoeBackend.XPU]
# XPUExperts does not support batch invariance; TRITON is kept as a
# fallback so VLLM_BATCH_INVARIANT=1 still resolves to a valid
# (batch-invariant) backend on XPU.
_AVAILABLE_BACKENDS = [
UnquantizedMoeBackend.XPU,
UnquantizedMoeBackend.TRITON,
]
elif current_platform.is_cpu():
_AVAILABLE_BACKENDS = [UnquantizedMoeBackend.CPU]
return _AVAILABLE_BACKENDS
+17
View File
@@ -119,6 +119,14 @@ class RMSNorm(CustomOp):
x: torch.Tensor,
residual: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if envs.VLLM_BATCH_INVARIANT and residual is not None:
assert self.variance_size_override is None, (
"Batch invariance is not supported for variance_size_override"
)
weight = self.weight.data if self.pass_weight_add else None
return ir.ops.fused_add_rms_norm.impls["native"].impl_fn(
x, residual, weight, self.variance_epsilon
)
return self.forward_cuda(x, residual)
def extra_repr(self) -> str:
@@ -171,6 +179,15 @@ class GemmaRMSNorm(CustomOp):
x: torch.Tensor,
residual: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if envs.VLLM_BATCH_INVARIANT:
if residual is None:
return self.forward_cuda(x, residual)
return ir.ops.fused_add_rms_norm.impls["native"].impl_fn(
x,
residual,
self.weight.float() + 1.0,
self.variance_epsilon,
)
import vllm._xpu_ops # noqa: F401 registers torch.ops.vllm.xpu_gemma_rms_norm
# Fall back to the native path if the fused gemma kernels are not
+40
View File
@@ -162,6 +162,25 @@ class XPUPlatform(Platform):
if selected_backend == AttentionBackendEnum.TRITON_ATTN:
logger.info_once("Using Triton backend.")
return AttentionBackendEnum.TRITON_ATTN.get_path()
elif attn_selector_config.use_batch_invariant:
# Flash Attention on XPU has not been validated for batch
# invariance. Honor an explicit Flash Attention request;
# otherwise fall back to Triton Attention, which implements
# batch-invariant kernels.
if selected_backend == AttentionBackendEnum.FLASH_ATTN:
logger.warning_once(
"Using Flash Attention on XPU with batch invariance "
"enabled because it was explicitly requested. This "
"backend has not been validated for batch invariance "
"on XPU and may produce non-deterministic results "
"across batch sizes."
)
return AttentionBackendEnum.FLASH_ATTN.get_path()
logger.info_once(
"VLLM_BATCH_INVARIANT is enabled. Using Triton Attention "
"backend on XPU, which implements batch-invariant kernels."
)
return AttentionBackendEnum.TRITON_ATTN.get_path()
elif attn_selector_config.use_mm_prefix:
# Flash Attention on XPU has no FA4 kernel, so it cannot apply the
# multimodal prefix-LM bidirectional mask. Honor an explicit Flash
@@ -283,6 +302,27 @@ class XPUPlatform(Platform):
# lazy import to avoid circular import
from vllm.config import CUDAGraphMode
if envs.VLLM_BATCH_INVARIANT:
model_config = vllm_config.model_config
if model_config is not None and (
model_config.quantization is not None
or vllm_config.quant_config is not None
):
raise ValueError(
"XPU batch invariance currently supports only unquantized "
f"models; got quantization={model_config.quantization!r}. "
"Use an unquantized model or disable VLLM_BATCH_INVARIANT."
)
cache_dtype = vllm_config.cache_config.cache_dtype
if cache_dtype not in ("auto", "float16", "bfloat16"):
raise ValueError(
"XPU batch invariance currently does not support quantized "
f"KV caches; got kv_cache_dtype={cache_dtype!r}. "
"Use an unquantized KV cache dtype or disable "
"VLLM_BATCH_INVARIANT."
)
compilation_config = vllm_config.compilation_config
if compilation_config.compile_sizes is None:
compilation_config.compile_sizes = []
+10
View File
@@ -526,6 +526,16 @@ class SamplingParams(
self._verify_args()
if (
envs.VLLM_BATCH_INVARIANT
and self.temperature >= _SAMPLING_EPS
and self.seed is None
):
logger.warning_once(
"Random sampling without an explicit seed may not be batch "
"invariant. Set seed in SamplingParams or use temperature=0."
)
if self.temperature < _SAMPLING_EPS:
# Zero temperature means greedy sampling.
self.top_p = 1.0
+6 -1
View File
@@ -224,9 +224,14 @@ class TopKTopPSampler(nn.Module):
else:
self.forward = self.forward_cpu
elif current_platform.is_xpu():
if xpu_sampler_supported():
if xpu_sampler_supported() and not envs.VLLM_BATCH_INVARIANT:
self.forward = self.forward_xpu
else:
if envs.VLLM_BATCH_INVARIANT:
logger.info_once(
"VLLM_BATCH_INVARIANT is enabled. Using the "
"PyTorch-native sampler on XPU."
)
self.forward = self.forward_native
elif (
logprobs_mode not in PROCESSED_LOGPROBS_MODES