Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-16 20:33:18 +09:00
117 changed files with 6209 additions and 995 deletions
@@ -190,9 +190,11 @@ def candidate_blocks_to_sparse_indices(
candidate_blocks: [rows, K] int32 request-local candidate block ids
(-1 padded), in units of ``candidate_block_size`` positions. K
must be a power of two (the in-kernel sort); rows may be strided.
row_ks/row_ke: [rows] int32 per-row K range; bounds are in the same
row_ks: [rows] int32 per-row K range start; bounds are in the same
(packed-workspace) coordinates the sparse kernel iterates over.
Pass zeros for the paged path, whose blocks are context-relative.
row_ke: [rows] int32 per-row K range end, in the same coordinates as
``row_ks``.
candidate_block_size: Positions per candidate block.
sparse_block_kv: Positions per sparse block (8 or 16).
out: Optional ``(sparse_indices, end)`` buffers to write into,
@@ -322,12 +324,16 @@ def sparse_mqa_logits_prefill_chunk(
k_scale: [total_kv] int32 packed UE8M0 K scales.
weights: [rows, H] bf16 per-head weights; the sparse kernels take
bf16 and do not fold the Q scale in.
cu_seqlen_ks/cu_seqlen_ke: [rows] int32 per-token K bounds in the
packed workspace.
cu_seqlen_ks: [rows] int32 per-token K start bounds in the packed
workspace.
cu_seqlen_ke: [rows] int32 per-token K end bounds in the packed
workspace.
candidate_blocks: [rows, K] int32 request-local candidate block ids.
topk_indices: [rows, topk_tokens] output buffer.
sparse_indices/end/col_indices: Caller-owned scratch, see
`candidate_blocks_to_sparse_indices` and `sparse_topk_remap`.
sparse_indices: Caller-owned scratch, see
`candidate_blocks_to_sparse_indices`.
end: Caller-owned scratch, see `candidate_blocks_to_sparse_indices`.
col_indices: Caller-owned scratch, see `sparse_topk_remap`.
kernel_metadata: DeepGEMM schedule from a previous call with the same
candidates and bounds (i.e. another indexer layer in the same
step). When given, the candidate expansion is skipped and
@@ -413,7 +419,9 @@ def sparse_mqa_logits_paged_decode(
candidate_blocks: [rows, K] int32 candidate block ids.
topk_indices: [rows, topk_tokens] output buffer.
row_ks: [rows] int32 zeros (paged blocks are context-relative).
sparse_indices/end/col_indices: Caller-owned scratch.
sparse_indices: Caller-owned scratch.
end: Caller-owned scratch.
col_indices: Caller-owned scratch.
kernel_metadata: See `sparse_mqa_logits_prefill_chunk`.
Returns:
@@ -187,6 +187,7 @@ from vllm.model_executor.kernels.linear.scaled_mm.b12x import (
)
from vllm.model_executor.kernels.linear.scaled_mm.cpu import (
CPUFp8BlockScaledMMKernel,
CPUFp8PerTensorScaledMMLinearKernel,
CPUInt8ScaledMMLinearKernel,
)
from vllm.model_executor.kernels.linear.scaled_mm.cutlass import (
@@ -438,6 +439,7 @@ _POSSIBLE_FP8_KERNELS: dict[PlatformEnum, list[type[FP8ScaledMMLinearKernel]]] =
ChannelWiseTorchFP8ScaledMMLinearKernel,
],
PlatformEnum.CPU: [
CPUFp8PerTensorScaledMMLinearKernel,
PerTensorTorchFP8ScaledMMLinearKernel,
ChannelWiseTorchFP8ScaledMMLinearKernel,
],
@@ -9,6 +9,7 @@ from vllm.model_executor.kernels.linear.scaled_mm.BlockScaledMMLinearKernel impo
)
from vllm.model_executor.kernels.linear.scaled_mm.cpu import (
CPUFp8BlockScaledMMKernel,
CPUFp8PerTensorScaledMMLinearKernel,
CPUInt8ScaledMMLinearKernel,
)
from vllm.model_executor.kernels.linear.scaled_mm.cutlass import (
@@ -67,5 +68,6 @@ __all__ = [
"ZentorchInt8ScaledMMLinearKernel",
"Fp8BlockScaledMMLinearKernel",
"CPUFp8BlockScaledMMKernel",
"CPUFp8PerTensorScaledMMLinearKernel",
"XPUFp8BlockScaledMMKernel",
]
@@ -21,10 +21,14 @@ from .BlockScaledMMLinearKernel import (
FP8ScaledMMLinearLayerConfig,
)
from .ScaledMMLinearKernel import (
FP8ScaledMMLinearKernel,
Int8ScaledMMLinearKernel,
Int8ScaledMMLinearLayerConfig,
)
# BLOCK_K in csrc/cpu/sgl-kernels/gemm.h — the AMX kernel's fixed K-block size.
_BLOCK_SIZE_K = 128
class CPUInt8ScaledMMLinearKernel(Int8ScaledMMLinearKernel):
@classmethod
@@ -330,3 +334,99 @@ class CPUFp8BlockScaledMMKernel(Fp8BlockScaledMMLinearKernel):
raise NotImplementedError(
"CPUFp8BlockScaledMMKernel overrides apply_weights directly."
)
class CPUFp8PerTensorScaledMMLinearKernel(FP8ScaledMMLinearKernel):
"""FP8 W8A16 per-tensor-scaled GEMM via AMX BRGEMM on CPU.
Reuses the block-scaled AMX kernel (fp8_scaled_mm_cpu) with a single
synthetic block spanning the whole weight, so activations stay BF16/FP32
— no FP8 activation quantization, unlike PerTensorTorchFP8ScaledMMLinearKernel.
"""
@classmethod
def is_supported(
cls, compute_capability: int | None = None
) -> tuple[bool, str | None]:
if not current_platform.is_cpu():
return False, "requires CPU platform."
if not torch.cpu._is_amx_tile_supported():
return False, "requires AMX tile support (Sapphire Rapids or newer)."
if not ops._supports_cpu_fp8_w8a16:
return False, "fp8_scaled_mm_cpu op not available."
return True, None
@classmethod
def can_implement(cls, c: FP8ScaledMMLinearLayerConfig) -> tuple[bool, str | None]:
if not c.weight_quant_key.scale.group_shape.is_per_tensor():
return False, "requires a per-tensor weight scale."
if not c.activation_quant_key.scale.group_shape.is_per_tensor():
return False, "requires a per-tensor activation scale."
if c.out_dtype not in (torch.bfloat16, torch.float32):
return False, "Only bfloat16/float32 output dtype supported."
n = c.weight_shape[0]
if n % 32 != 0:
# The AMX tinygemm kernel tiles N in chunks of 32 and cannot
# handle a remainder tile smaller than that.
return False, f"requires weight output dim (N={n}) to be a multiple of 32."
return True, None
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
w_name, w_s_name, _, _ = self.layer_param_names
# Fp8LinearMethod transposes weight to (K, N) for torch._scaled_mm-style
# kernels; convert_weight_packed/fp8_scaled_mm_cpu expect (N, K), as
# produced by CUDA nn.Linear-style checkpoints.
weight = getattr(layer, w_name).t().contiguous()
n, k = weight.shape
packed_weight = torch.ops._C.convert_weight_packed(weight)
replace_parameter(
layer, w_name, torch.nn.Parameter(packed_weight, requires_grad=False)
)
# Synthesize a single-block "block scale" tensor from the scalar
# per-tensor weight scale so fp8_scaled_mm_cpu can be reused as-is.
weight_scale = getattr(layer, w_s_name)
self._block_size_n = -(-n // 32) * 32 # round up to a multiple of 32
num_k_blocks = -(-k // _BLOCK_SIZE_K)
block_scale = weight_scale.reshape(()).expand(1, num_k_blocks).contiguous()
replace_parameter(
layer, w_s_name, torch.nn.Parameter(block_scale, requires_grad=False)
)
def apply_weights(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
w_name, w_s_name, _, _ = self.layer_param_names
weight = getattr(layer, w_name)
weight_scale = getattr(layer, w_s_name)
x_2d = x.reshape(-1, x.shape[-1]) if x.dim() > 2 else x
out = torch.ops._C.fp8_scaled_mm_cpu(
x_2d,
weight,
weight_scale,
[self._block_size_n, _BLOCK_SIZE_K],
bias,
x.dtype,
True, # is_vnni (weight already prepacked)
)
return out.reshape(x.shape[:-1] + (out.size(-1),)) if x.dim() > 2 else out
def apply_scaled_mm(
self,
*,
A: torch.Tensor,
B: torch.Tensor,
out_dtype: torch.dtype,
As: torch.Tensor,
Bs: torch.Tensor,
bias: torch.Tensor | None,
output_shape: list,
) -> torch.Tensor:
raise NotImplementedError(
"CPUFp8PerTensorScaledMMLinearKernel overrides apply_weights directly."
)
@@ -615,14 +615,15 @@ class RoutedExperts(PluggableLayer):
# compressed-tensors checkpoints with packed weights are stored flipped
# TODO (mgoin): check self.quant_method.quant_config.quant_format
# against known CompressionFormat enum values that have this quality
if quant_method_name in (
"CompressedTensorsWNA16MoEMethod",
"CompressedTensorsW4A16FlydslMoEMethod",
if (
quant_method_name
in (
"CompressedTensorsWNA16MoEMethod",
"CompressedTensorsW4A16FlydslMoEMethod",
)
and is_transposed
):
if is_transposed:
loaded_weight = loaded_weight.t().contiguous()
else:
loaded_weight = loaded_weight
loaded_weight = loaded_weight.t().contiguous()
if shard_id not in ("w1", "w2", "w3"):
raise ValueError(f"shard_id must be ['w1','w2','w3'] but got {shard_id}.")
File diff suppressed because it is too large Load Diff
@@ -727,11 +727,15 @@ def _get_available_ram_bytes() -> int:
host_available = psutil.virtual_memory().available
from vllm.utils.cpu_resource_utils import get_cgroup_memory_limit
from vllm.utils.cpu_resource_utils import (
get_cgroup_memory_limit,
get_cgroup_memory_usage,
)
cgroup_limit, cgroup_usage = get_cgroup_memory_limit()
cgroup_limit = get_cgroup_memory_limit()
if cgroup_limit is None:
return host_available
cgroup_usage = get_cgroup_memory_usage()
cgroup_available = (
cgroup_limit if cgroup_usage is None else max(0, cgroup_limit - cgroup_usage)
)
+1 -3
View File
@@ -780,9 +780,7 @@ class DeepCLIPVisionEmbeddings(CLIPVisionEmbeddings):
self, pixel_values: torch.Tensor, patch_embeds: torch.Tensor | None = None
) -> torch.Tensor:
batch_size = pixel_values.shape[0]
if patch_embeds is not None:
patch_embeds = patch_embeds
else:
if patch_embeds is None:
patch_embeds = self.patch_embedding(pixel_values)
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
@@ -964,7 +964,6 @@ class MiMoV2OmniMultiModalProcessor(BaseMultiModalProcessor[MiMoV2OmniProcessing
assert isinstance(va_item, (list, tuple)) and len(va_item) == 2
vid, audio_src = va_item
va_item = VideoAudioInput(video=vid, audio=audio_src)
vid = vid
# Convert video frames to (TCHW, timestamps) if needed
if (
isinstance(vid, tuple)
@@ -253,6 +253,7 @@ class Qwen2AudioMultiModalProcessor(BaseMultiModalProcessor[Qwen2AudioProcessing
hf_processor_mm_kwargs = dict(
**hf_processor_mm_kwargs,
sampling_rate=feature_extractor.sampling_rate,
truncation=True,
)
return mm_data, hf_processor_mm_kwargs
-1
View File
@@ -173,7 +173,6 @@ class Step3p5Attention(nn.Module):
rope_scaling = None
if sliding_window is not None and enable_sliding_window:
sliding_window = sliding_window
if swa_num_attention_heads is not None:
num_heads = swa_num_attention_heads
self.total_num_heads = swa_num_attention_heads