[Refactor] Normalize DeepSeek V4.1 model package naming (#56741)
Signed-off-by: Bugen Zhao <i@bugenzhao.com>
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,363 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Multimodal preprocessing for the DeepSeek-V4.1 vision variant.
|
||||
|
||||
The image transform and image-span construction are ported from the
|
||||
official repository's ``image_processor.py`` so that token counts bit-match
|
||||
the reference. Each ``<|deepseek_image|>`` placeholder in the prompt expands
|
||||
to ``[IMAGE_START] + ([IMAGE] * n_llm_w + [IMAGE_NEW_LINE]) * n_llm_h +
|
||||
[IMAGE_END]``; every span position carries ``image_token_id`` (129264) in
|
||||
``input_ids`` and the roles ride along in a per-image ``types`` tensor
|
||||
(the reference's out-of-band ``token_types``). IMAGE slots receive aligner
|
||||
rows in reading order; the delimiters take the learned ``image_start`` /
|
||||
``image_newline`` / ``image_end`` vectors.
|
||||
|
||||
The token stream matches the reference exactly: no compressor-alignment
|
||||
pad is inserted (the reference pools image tokens across compressor-group
|
||||
boundaries freely).
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image, ImageOps
|
||||
from transformers import BatchFeature
|
||||
|
||||
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
|
||||
from vllm.multimodal.parse import ImageSize, MultiModalDataItems
|
||||
from vllm.multimodal.processing import (
|
||||
BaseDummyInputsBuilder,
|
||||
BaseMultiModalProcessor,
|
||||
BaseProcessingInfo,
|
||||
PromptReplacement,
|
||||
PromptUpdate,
|
||||
PromptUpdateDetails,
|
||||
)
|
||||
from vllm.transformers_utils.configs.deepseek_v41 import DeepseekV41Config
|
||||
|
||||
IMAGE_START, IMAGE, IMAGE_NEW_LINE, IMAGE_END = range(4)
|
||||
|
||||
IMAGE_PLACEHOLDER = "<|deepseek_image|>"
|
||||
|
||||
# The checkpoint tokenizer's id for IMAGE_PLACEHOLDER (the config's
|
||||
# ``image_token_id``). Every image-span position carries this id, exactly
|
||||
# like the reference; the MoE router detects image tokens as the range
|
||||
# [IMAGE_SENTINEL_BASE_ID, IMAGE_SENTINEL_BASE_ID + 5).
|
||||
IMAGE_SENTINEL_BASE_ID = 129264
|
||||
|
||||
|
||||
def image_sentinel_mask(token_ids: torch.Tensor) -> torch.Tensor:
|
||||
"""Boolean mask for image-span positions."""
|
||||
return token_ids == IMAGE_SENTINEL_BASE_ID
|
||||
|
||||
|
||||
def validate_image_sentinel_ids(tokenizer) -> None:
|
||||
"""Check the image token id against the tokenizer."""
|
||||
image_id = tokenizer.convert_tokens_to_ids(IMAGE_PLACEHOLDER)
|
||||
if image_id != IMAGE_SENTINEL_BASE_ID:
|
||||
raise ValueError(
|
||||
f"Image placeholder {IMAGE_PLACEHOLDER!r} has id {image_id}, "
|
||||
f"expected {IMAGE_SENTINEL_BASE_ID} (the config's "
|
||||
"image_token_id); the DeepSeek-V4.1 vision path keys image "
|
||||
"routing and engram masking off this id."
|
||||
)
|
||||
|
||||
|
||||
def llm_grid(best_height, best_width, patch_size, downsample_ratio):
|
||||
"""Token grid the aligner produces from a patch grid of this pixel size."""
|
||||
return (
|
||||
math.ceil((best_height // patch_size) / downsample_ratio),
|
||||
math.ceil((best_width // patch_size) / downsample_ratio),
|
||||
)
|
||||
|
||||
|
||||
def num_image_tokens(n_llm_h: int, n_llm_w: int) -> int:
|
||||
return n_llm_h * (n_llm_w + 1) + 2
|
||||
|
||||
|
||||
def solve_resize_ratio(height, width, patch_size, downsample_ratio, max_n_token):
|
||||
"""Largest aspect-preserving pixel size whose token grid still fits in
|
||||
max_n_token. Returns (best_height, best_width)."""
|
||||
r = height / width
|
||||
max_w_float = math.sqrt((max_n_token - 2) / r + 0.25) - 0.5
|
||||
max_h_float = max_w_float * r
|
||||
cell = patch_size * downsample_ratio
|
||||
if max_w_float < 1.0: # very tall: collapse to a single column
|
||||
return (max_n_token - 2) // 2 * cell, cell
|
||||
if max_h_float < 1.0: # very wide: collapse to a single row
|
||||
return cell, (max_n_token - 3) * cell
|
||||
beta = min(
|
||||
math.floor(max_w_float) * cell / width,
|
||||
math.floor(max_h_float) * cell / height,
|
||||
)
|
||||
return (
|
||||
math.floor(height * beta / patch_size) * patch_size,
|
||||
math.floor(width * beta / patch_size) * patch_size,
|
||||
)
|
||||
|
||||
|
||||
def safe_resize(
|
||||
height, width, best_height, best_width, patch_size, downsample_ratio, max_n_token
|
||||
):
|
||||
"""Shrink the pixel size until the image costs at most max_n_token LLM
|
||||
tokens."""
|
||||
n_llm_h, n_llm_w = llm_grid(best_height, best_width, patch_size, downsample_ratio)
|
||||
if num_image_tokens(n_llm_h, n_llm_w) > max_n_token:
|
||||
best_height, best_width = solve_resize_ratio(
|
||||
height, width, patch_size, downsample_ratio, max_n_token
|
||||
)
|
||||
n_llm_h, n_llm_w = llm_grid(
|
||||
best_height, best_width, patch_size, downsample_ratio
|
||||
)
|
||||
assert num_image_tokens(n_llm_h, n_llm_w) <= max_n_token
|
||||
return n_llm_h, n_llm_w, best_height, best_width
|
||||
|
||||
|
||||
def load_image(
|
||||
image: Image.Image,
|
||||
*,
|
||||
patch_size: int,
|
||||
downsample_ratio: int,
|
||||
max_n_token: int,
|
||||
min_pixels: int,
|
||||
max_wh_ratio: float | None,
|
||||
):
|
||||
"""Transform one PIL image into ViT patches.
|
||||
|
||||
Same math as the reference ``load_image``, except the image is already
|
||||
decoded (vLLM supplies PIL images instead of a record dict).
|
||||
"""
|
||||
p = patch_size
|
||||
image = image.convert("RGB")
|
||||
width, height = image.size
|
||||
if max_wh_ratio is not None and width > height * max_wh_ratio:
|
||||
width = height * max_wh_ratio
|
||||
if 0 < width * height < min_pixels:
|
||||
ratio = (min_pixels / (width * height)) ** 0.5
|
||||
width = int(width * ratio)
|
||||
height = int(height * ratio)
|
||||
best_width = math.ceil(width / p) * p
|
||||
best_height = math.ceil(height / p) * p
|
||||
n_llm_h, n_llm_w, best_height, best_width = safe_resize(
|
||||
height, width, best_height, best_width, p, downsample_ratio, max_n_token
|
||||
)
|
||||
n_vit_h, n_vit_w = best_height // p, best_width // p
|
||||
if max_wh_ratio is not None and image.width >= max_wh_ratio * image.height:
|
||||
image = image.resize((best_width, best_height))
|
||||
else:
|
||||
image = ImageOps.pad(image, (best_width, best_height), color=(127, 127, 127))
|
||||
x = torch.from_numpy(np.asarray(image, dtype=np.float32)).permute(2, 0, 1) / 255
|
||||
x = ((x - 0.5) / 0.5).to(torch.bfloat16)
|
||||
patches = (
|
||||
x.reshape(3, n_vit_h, p, n_vit_w, p)
|
||||
.permute(1, 3, 0, 2, 4)
|
||||
.reshape(n_vit_h * n_vit_w, 3, p, p)
|
||||
)
|
||||
return patches, n_vit_h, n_vit_w, n_llm_h, n_llm_w
|
||||
|
||||
|
||||
def image_token_types(n_llm_h: int, n_llm_w: int) -> torch.Tensor:
|
||||
"""Reading-order span layout: one IMAGE_NEW_LINE per row."""
|
||||
types = [IMAGE_START]
|
||||
types += ([IMAGE] * n_llm_w + [IMAGE_NEW_LINE]) * n_llm_h
|
||||
types.append(IMAGE_END)
|
||||
return torch.tensor(types, dtype=torch.int64)
|
||||
|
||||
|
||||
class DeepseekV4VLImageProcessor:
|
||||
"""Per-image transform (the PIL-input equivalent of the reference
|
||||
``load_image``)."""
|
||||
|
||||
def __init__(self, config: DeepseekV41Config) -> None:
|
||||
super().__init__()
|
||||
self.patch_size = config.vision_patch_size
|
||||
self.downsample_ratio = config.vision_downsample_ratio
|
||||
self.max_n_token = config.vision_max_n_token
|
||||
self.min_pixels = config.vision_min_pixels
|
||||
self.max_wh_ratio = config.vision_max_wh_ratio
|
||||
|
||||
def __call__(self, image: Image.Image):
|
||||
return load_image(
|
||||
image,
|
||||
patch_size=self.patch_size,
|
||||
downsample_ratio=self.downsample_ratio,
|
||||
max_n_token=self.max_n_token,
|
||||
min_pixels=self.min_pixels,
|
||||
max_wh_ratio=self.max_wh_ratio,
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4VLProcessor:
|
||||
"""Minimal stand-in for the HF processor of DeepSeek-V4.1 vision models.
|
||||
|
||||
The official repository ships image preprocessing as plain functions in
|
||||
``image_processor.py`` (no ``auto_map`` processor), so this class wraps
|
||||
their ports directly and the model loads without ``--trust-remote-code``.
|
||||
|
||||
``__call__`` returns a ``BatchFeature`` with one entry per image
|
||||
(flattened across images):
|
||||
|
||||
- ``patches``: ``(sum(n_vit_h * n_vit_w), 3, p, p)`` bf16 ViT patches.
|
||||
- ``vit_grid``: ``(num_images, 2)`` int64 ``[n_vit_h, n_vit_w]``.
|
||||
- ``llm_grid``: ``(num_images, 2)`` int64 ``[n_llm_h, n_llm_w]``.
|
||||
- ``types``: concatenated per-image pad-free span roles
|
||||
(IMAGE_START/IMAGE/IMAGE_NEW_LINE/IMAGE_END); every span position
|
||||
carries ``image_token_id`` in the prompt's token ids.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV41Config) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.image_processor = DeepseekV4VLImageProcessor(config)
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
text: str | None = None,
|
||||
images: Sequence[Image.Image] | None = None,
|
||||
return_tensors: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> BatchFeature:
|
||||
patches_list = []
|
||||
vit_grid = []
|
||||
llm_grid_list = []
|
||||
types_list = []
|
||||
for image in images or []:
|
||||
patches, n_vit_h, n_vit_w, n_llm_h, n_llm_w = self.image_processor(image)
|
||||
patches_list.append(patches)
|
||||
vit_grid.append((n_vit_h, n_vit_w))
|
||||
llm_grid_list.append((n_llm_h, n_llm_w))
|
||||
types_list.append(image_token_types(n_llm_h, n_llm_w))
|
||||
|
||||
if not patches_list:
|
||||
return BatchFeature({})
|
||||
|
||||
return BatchFeature(
|
||||
{
|
||||
"patches": torch.cat(patches_list),
|
||||
"vit_grid": torch.tensor(vit_grid, dtype=torch.int64),
|
||||
"llm_grid": torch.tensor(llm_grid_list, dtype=torch.int64),
|
||||
"types": torch.cat(types_list),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4VLProcessingInfo(BaseProcessingInfo):
|
||||
def get_hf_config(self) -> DeepseekV41Config:
|
||||
return self.ctx.get_hf_config(DeepseekV41Config)
|
||||
|
||||
def get_hf_processor(self, **kwargs: object) -> DeepseekV4VLProcessor:
|
||||
if kwargs:
|
||||
raise ValueError(f"Unexpected processor kwargs: {sorted(kwargs)}")
|
||||
return DeepseekV4VLProcessor(self.get_hf_config())
|
||||
|
||||
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
|
||||
return {"image": None}
|
||||
|
||||
def get_mm_max_tokens_per_item(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
) -> Mapping[str, int]:
|
||||
return {"image": self.get_hf_config().vision_max_n_token}
|
||||
|
||||
def get_image_placeholder_token_id(self) -> int:
|
||||
token_id = self.get_tokenizer().convert_tokens_to_ids(IMAGE_PLACEHOLDER)
|
||||
if token_id is None:
|
||||
raise ValueError(f"Token not found in tokenizer: {IMAGE_PLACEHOLDER}")
|
||||
return token_id
|
||||
|
||||
def get_image_size_with_most_features(self) -> ImageSize:
|
||||
hf_config = self.get_hf_config()
|
||||
patch_size = hf_config.vision_patch_size
|
||||
downsample_ratio = hf_config.vision_downsample_ratio
|
||||
# A square maximizes the ViT patch count (area) within the token
|
||||
# budget; solve the budget-derived size directly to keep the dummy
|
||||
# image small.
|
||||
budget = hf_config.vision_max_n_token
|
||||
side = budget * patch_size * downsample_ratio
|
||||
best_h, best_w = solve_resize_ratio(
|
||||
side, side, patch_size, downsample_ratio, budget
|
||||
)
|
||||
return ImageSize(width=best_w, height=best_h)
|
||||
|
||||
|
||||
class DeepseekV4VLDummyInputsBuilder(
|
||||
BaseDummyInputsBuilder[DeepseekV4VLProcessingInfo]
|
||||
):
|
||||
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
return IMAGE_PLACEHOLDER * mm_counts.get("image", 0)
|
||||
|
||||
def get_dummy_mm_data(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions],
|
||||
) -> MultiModalDataDict:
|
||||
size = self.info.get_image_size_with_most_features()
|
||||
return {
|
||||
"image": self._get_dummy_images(
|
||||
width=size.width,
|
||||
height=size.height,
|
||||
num_images=mm_counts.get("image", 0),
|
||||
overrides=cast(ImageDummyOptions | None, mm_options.get("image")),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class DeepseekV4VLMultiModalProcessor(
|
||||
BaseMultiModalProcessor[DeepseekV4VLProcessingInfo]
|
||||
):
|
||||
def _get_mm_fields_config(
|
||||
self,
|
||||
hf_inputs: BatchFeature,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
) -> Mapping[str, MultiModalFieldConfig]:
|
||||
vit_grid = hf_inputs.get("vit_grid")
|
||||
llm_grid = hf_inputs.get("llm_grid")
|
||||
|
||||
if vit_grid is None or llm_grid is None:
|
||||
empty = torch.empty(0, dtype=torch.long)
|
||||
patch_sizes = types_sizes = empty
|
||||
else:
|
||||
patch_sizes = vit_grid.prod(-1)
|
||||
n_llm_h, n_llm_w = llm_grid[:, 0], llm_grid[:, 1]
|
||||
types_sizes = n_llm_h * (n_llm_w + 1) + 2
|
||||
|
||||
return {
|
||||
"patches": MultiModalFieldConfig.flat_from_sizes("image", patch_sizes),
|
||||
"vit_grid": MultiModalFieldConfig.batched("image", keep_on_cpu=True),
|
||||
"llm_grid": MultiModalFieldConfig.batched("image", keep_on_cpu=True),
|
||||
"types": MultiModalFieldConfig.flat_from_sizes(
|
||||
"image", types_sizes, keep_on_cpu=True
|
||||
),
|
||||
}
|
||||
|
||||
def _get_prompt_updates(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
out_mm_kwargs: MultiModalKwargsItems,
|
||||
) -> Sequence[PromptUpdate]:
|
||||
image_token_id = self.info.get_image_placeholder_token_id()
|
||||
validate_image_sentinel_ids(self.info.get_tokenizer())
|
||||
|
||||
def get_image_replacement(item_idx: int) -> PromptUpdateDetails:
|
||||
types: torch.Tensor = out_mm_kwargs["image"][item_idx]["types"].data
|
||||
# Every span position carries image_token_id; the roles live in
|
||||
# ``types``. All of them are embed positions (delimiters get the
|
||||
# learned vectors from embed_multimodal, not the embed table).
|
||||
full = [image_token_id] * types.numel()
|
||||
return PromptUpdateDetails.select_token_id(full, image_token_id)
|
||||
|
||||
return [
|
||||
PromptReplacement(
|
||||
modality="image",
|
||||
target=[image_token_id],
|
||||
replacement=get_image_replacement,
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,42 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepSeek V4.1 fused ops.
|
||||
|
||||
Single bridging point for the kernels V4.1 shares verbatim with V4: the
|
||||
re-exports below are the only place this package reaches into
|
||||
``vllm.models.deepseek_v4``, so submodules import them from ``.`` instead of
|
||||
naming the V4 path themselves. Keep these imports above the ``.``-relative
|
||||
ones — ``indexer_k_store`` reads them off this partially-initialized module.
|
||||
"""
|
||||
|
||||
from vllm.models.deepseek_v4.common.ops.fused_indexer_q import (
|
||||
MXFP4_BLOCK_SIZE,
|
||||
fused_indexer_q_rope_quant,
|
||||
)
|
||||
from vllm.models.deepseek_v4.common.ops.fused_indexer_q import (
|
||||
_fp32x2_to_fp4x2 as _fp32x2_to_fp4x2, # re-export for .indexer_k_store
|
||||
)
|
||||
from vllm.models.deepseek_v4.common.ops.fused_inv_rope_fp8_quant import (
|
||||
fused_inv_rope_fp8_quant,
|
||||
)
|
||||
|
||||
from .cache_utils import (
|
||||
build_flashinfer_mixed_sparse_indices,
|
||||
combine_topk_swa_indices,
|
||||
compute_global_topk_indices_and_lens,
|
||||
dequantize_and_gather_k_cache,
|
||||
quantize_and_insert_k_cache,
|
||||
)
|
||||
from .indexer_k_store import indexer_k_norm_rope_store
|
||||
|
||||
__all__ = [
|
||||
"MXFP4_BLOCK_SIZE",
|
||||
"build_flashinfer_mixed_sparse_indices",
|
||||
"combine_topk_swa_indices",
|
||||
"compute_global_topk_indices_and_lens",
|
||||
"dequantize_and_gather_k_cache",
|
||||
"fused_indexer_q_rope_quant",
|
||||
"fused_inv_rope_fp8_quant",
|
||||
"indexer_k_norm_rope_store",
|
||||
"quantize_and_insert_k_cache",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,383 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""V4.1 state saving/compression and independently schedulable cache insertion."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
if current_platform.is_rocm():
|
||||
from vllm.platforms.rocm import _ON_GFX950
|
||||
else:
|
||||
_ON_GFX950 = False
|
||||
|
||||
# The ring and raw rows a ratio-2 request program pools are not adjacent, so
|
||||
# reading them as one tile means joining two pointers. ROCm's Triton fails to
|
||||
# legalize `tt.join` on pointers, so there the two rows are loaded separately.
|
||||
_JOIN_ROW_PTRS = not current_platform.is_rocm()
|
||||
|
||||
|
||||
def fused_save_compress_norm(
|
||||
kv_score: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
state_cache: torch.Tensor | None,
|
||||
slot_mapping: torch.Tensor,
|
||||
query_start_loc: torch.Tensor | None,
|
||||
token_to_req_indices: torch.Tensor | None,
|
||||
rms_norm_weight: torch.Tensor,
|
||||
rms_norm_eps: float,
|
||||
compress_ratio: int,
|
||||
latent_out: torch.Tensor,
|
||||
) -> None:
|
||||
"""Pool each closed group into a normalized BF16 latent; save FP32 states.
|
||||
|
||||
The latent feeds the main-cache insert and the indexer K path, which the
|
||||
attention layer schedules on separate streams.
|
||||
|
||||
Ratio 2 keeps one ring block per request holding the open group's rows:
|
||||
position ``p`` lives in row ``p % capacity`` and ``slot_mapping`` encodes
|
||||
``block * capacity + p % capacity``. The grid has one program per request
|
||||
followed by one per pair of packed tokens. A request program handles the
|
||||
group that the chunk's first token closes with its predecessor's ring row,
|
||||
then stores the chunk's last ``capacity`` rows to the ring; because the
|
||||
same program does both, ring reads and writes never race. A pair program
|
||||
handles the group that ends inside its pair, reading both rows from the
|
||||
raw input. Ratio 1 has no ring and one program per token; ``slot_mapping``
|
||||
then only marks valid tokens.
|
||||
|
||||
Args:
|
||||
kv_score: FP32 [tokens, 512] for CR1, [tokens, 1024] for CR2.
|
||||
positions: Absolute positions of the packed request tokens.
|
||||
state_cache: Ring FP32 [blocks, capacity, 1024] KV/score states (CR2).
|
||||
slot_mapping: Ring slots (CR2) or main-cache slots (CR1).
|
||||
query_start_loc: [num_reqs + 1] token offsets of each request's chunk.
|
||||
token_to_req_indices: Request indices for the packed token rows.
|
||||
rms_norm_weight: BF16 [512] normalization weight.
|
||||
rms_norm_eps: RMSNorm epsilon.
|
||||
compress_ratio: Group size, either 1 or 2.
|
||||
latent_out: BF16 [tokens, 512], written only at valid group boundaries.
|
||||
"""
|
||||
assert compress_ratio in (1, 2)
|
||||
assert kv_score.dtype == torch.float32
|
||||
assert kv_score.shape[1] == 512 * compress_ratio and kv_score.stride(1) == 1
|
||||
assert latent_out.shape == (kv_score.shape[0], 512)
|
||||
assert latent_out.is_contiguous() and latent_out.dtype == torch.bfloat16
|
||||
assert positions.is_contiguous() and slot_mapping.is_contiguous()
|
||||
# Rows stay 64-byte aligned, as the kernel's tl.multiple_of hint promises.
|
||||
assert kv_score.stride(0) % 16 == 0
|
||||
if compress_ratio == 2:
|
||||
assert state_cache is not None and query_start_loc is not None
|
||||
assert token_to_req_indices is not None
|
||||
assert query_start_loc.is_contiguous()
|
||||
assert token_to_req_indices.is_contiguous()
|
||||
assert state_cache.dtype == torch.float32
|
||||
assert state_cache.shape[2] == 1024 and state_cache.stride(2) == 1
|
||||
assert state_cache.stride(1) % 16 == 0
|
||||
state_stride, state_row_stride, state_block = (
|
||||
state_cache.stride(0),
|
||||
state_cache.stride(1),
|
||||
state_cache.shape[1],
|
||||
)
|
||||
num_reqs = query_start_loc.numel() - 1
|
||||
else:
|
||||
state_cache = query_start_loc = token_to_req_indices = None
|
||||
state_stride = state_row_stride = state_block = 1
|
||||
num_reqs = 0
|
||||
num_tokens = slot_mapping.numel()
|
||||
assert num_tokens <= min(kv_score.shape[0], positions.numel())
|
||||
if num_tokens == 0:
|
||||
return
|
||||
grid = num_reqs + triton.cdiv(num_tokens, compress_ratio)
|
||||
_fused_save_compress_norm_kernel[(grid,)](
|
||||
kv_score,
|
||||
positions,
|
||||
state_cache,
|
||||
slot_mapping,
|
||||
query_start_loc,
|
||||
token_to_req_indices,
|
||||
rms_norm_weight,
|
||||
latent_out,
|
||||
num_tokens,
|
||||
num_reqs,
|
||||
RAW_STRIDE=kv_score.stride(0),
|
||||
STATE_STRIDE=state_stride,
|
||||
STATE_ROW_STRIDE=state_row_stride,
|
||||
STATE_BLOCK=state_block,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
EPS=rms_norm_eps,
|
||||
JOIN_ROW_PTRS=_JOIN_ROW_PTRS,
|
||||
num_warps=4,
|
||||
**({"launch_pdl": False} if current_platform.is_cuda() else {}),
|
||||
)
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_tokens", "num_reqs"])
|
||||
def _fused_save_compress_norm_kernel(
|
||||
raw,
|
||||
positions,
|
||||
state,
|
||||
state_slots,
|
||||
query_start_loc,
|
||||
req_ids,
|
||||
norm_weight,
|
||||
latent,
|
||||
num_tokens,
|
||||
num_reqs,
|
||||
RAW_STRIDE: tl.constexpr,
|
||||
STATE_STRIDE: tl.constexpr,
|
||||
STATE_ROW_STRIDE: tl.constexpr,
|
||||
STATE_BLOCK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
JOIN_ROW_PTRS: tl.constexpr,
|
||||
):
|
||||
pid = tl.program_id(0)
|
||||
d = tl.arange(0, 512)
|
||||
|
||||
if COMPRESS_RATIO == 2: # noqa: SIM102 (constexpr branch, then runtime)
|
||||
if pid < num_reqs:
|
||||
# Request program: the group closed by the chunk's first token,
|
||||
# then the ring tail store.
|
||||
start = tl.load(query_start_loc + pid)
|
||||
end = tl.load(query_start_loc + pid + 1)
|
||||
if start >= end:
|
||||
return
|
||||
state_slot = tl.load(state_slots + start)
|
||||
if state_slot < 0:
|
||||
return
|
||||
position = tl.load(positions + start)
|
||||
if (position + 1) % 2 == 0:
|
||||
ring = state + (state_slot // STATE_BLOCK).to(tl.int64) * STATE_STRIDE
|
||||
prev = ring + ((position - 1) % STATE_BLOCK) * STATE_ROW_STRIDE
|
||||
current = raw + start.to(tl.int64) * RAW_STRIDE
|
||||
if JOIN_ROW_PTRS:
|
||||
# Joining pointers hides row alignment from Triton; restate it.
|
||||
rows = tl.multiple_of(tl.join(prev, current)[:, None], (16, 16))
|
||||
kv = tl.load(rows + d[None, :])
|
||||
score = tl.load(rows + 512 + d[None, :])
|
||||
# Every lane has read the ring before the tail store below
|
||||
# writes it.
|
||||
tl.debug_barrier()
|
||||
pooled = tl.sum(kv * tl.softmax(score, 0), 0)
|
||||
else:
|
||||
kv_prev = tl.load(prev + d)
|
||||
score_prev = tl.load(prev + 512 + d)
|
||||
kv_current = tl.load(current + d)
|
||||
score_current = tl.load(current + 512 + d)
|
||||
# Every lane has read the ring before the tail store below
|
||||
# writes it.
|
||||
tl.debug_barrier()
|
||||
peak = tl.maximum(score_prev, score_current)
|
||||
weight_prev = tl.exp(score_prev - peak)
|
||||
weight_current = tl.exp(score_current - peak)
|
||||
pooled = (kv_prev * weight_prev + kv_current * weight_current) / (
|
||||
weight_prev + weight_current
|
||||
)
|
||||
_store_latent(pooled, start, norm_weight, latent, EPS)
|
||||
num_rows = tl.minimum(end - start, STATE_BLOCK)
|
||||
for k in tl.range(0, num_rows):
|
||||
token = end - num_rows + k
|
||||
slot = tl.load(state_slots + token)
|
||||
if slot >= 0:
|
||||
row = (
|
||||
state
|
||||
+ (slot // STATE_BLOCK).to(tl.int64) * STATE_STRIDE
|
||||
+ (slot % STATE_BLOCK) * STATE_ROW_STRIDE
|
||||
)
|
||||
src = raw + token.to(tl.int64) * RAW_STRIDE
|
||||
tl.store(row + d, tl.load(src + d))
|
||||
tl.store(row + 512 + d, tl.load(src + 512 + d))
|
||||
return
|
||||
|
||||
# Group program: one token (ratio 1) or the token of the pair that ends
|
||||
# a group (ratio 2). A chunk's first token belongs to its request program.
|
||||
t = (pid - num_reqs) * COMPRESS_RATIO
|
||||
if COMPRESS_RATIO == 2:
|
||||
t += (tl.load(positions + t) + 1) % 2
|
||||
state_slot = tl.load(state_slots + t, t < num_tokens, other=-1)
|
||||
if state_slot < 0:
|
||||
return
|
||||
if COMPRESS_RATIO == 1:
|
||||
pooled = tl.load(raw + t.to(tl.int64) * RAW_STRIDE + d)
|
||||
else:
|
||||
if t == tl.load(query_start_loc + tl.load(req_ids + t)):
|
||||
return
|
||||
rows = raw + (t.to(tl.int64) - 1 + tl.arange(0, 2)[:, None]) * RAW_STRIDE
|
||||
kv = tl.load(rows + d[None, :])
|
||||
score = tl.load(rows + 512 + d[None, :])
|
||||
pooled = tl.sum(kv * tl.softmax(score, 0), 0)
|
||||
_store_latent(pooled, t, norm_weight, latent, EPS)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _store_latent(pooled, t, norm_weight, latent, EPS: tl.constexpr):
|
||||
d = tl.arange(0, 512)
|
||||
weight = tl.load(norm_weight + d).to(tl.float32)
|
||||
variance = tl.sum(pooled * pooled, 0) / 512
|
||||
normed = pooled * tl.rsqrt(variance + EPS) * weight
|
||||
tl.store(latent + t.to(tl.int64) * 512 + d, normed.to(tl.bfloat16))
|
||||
|
||||
|
||||
def rope_quant_insert(
|
||||
latent: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
compress_ratio: int,
|
||||
fp8_scale: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
"""Apply GPT-J RoPE and publish a latent to the compressed KV cache.
|
||||
|
||||
The BF16 latent supplies both NoPE quantization and RoPE input. It is read
|
||||
only for valid slots at group boundaries. The cache dtype selects the
|
||||
layout: ``uint8`` is the fp8_ds_mla paged layout (576 value bytes and eight
|
||||
segregated UE8M0 scale bytes per token, including one zero padding scale);
|
||||
``bfloat16`` and ``float8_e4m3fn`` are the plain [448 NoPE | 64 RoPE] rows
|
||||
read by FlashInfer, the latter scaled by the per-tensor ``fp8_scale``.
|
||||
"""
|
||||
assert compress_ratio in (1, 2)
|
||||
assert latent.shape[1] == 512 and latent.dtype == torch.bfloat16
|
||||
assert latent.is_contiguous()
|
||||
num_tokens = slot_mapping.numel()
|
||||
assert num_tokens <= min(latent.shape[0], positions.numel())
|
||||
if num_tokens == 0:
|
||||
return
|
||||
launch_kwargs = {"launch_pdl": False} if current_platform.is_cuda() else {}
|
||||
if kv_cache.dtype == torch.uint8:
|
||||
assert kv_cache.shape[-1] == 584
|
||||
_rope_quant_insert_kernel[(num_tokens,)](
|
||||
latent,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
kv_cache,
|
||||
slot_mapping,
|
||||
COS_STRIDE=cos_sin_cache.stride(0),
|
||||
CACHE_STRIDE=kv_cache.stride(0),
|
||||
CACHE_BLOCK=kv_cache.shape[1],
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
SANITIZE_CACHE_NANS=_ON_GFX950,
|
||||
num_warps=4,
|
||||
**launch_kwargs,
|
||||
)
|
||||
return
|
||||
|
||||
assert kv_cache.dtype in (torch.bfloat16, torch.float8_e4m3fn)
|
||||
assert kv_cache.shape[-1] == 512 and kv_cache.stride(-1) == 1
|
||||
store_fp8 = kv_cache.dtype == torch.float8_e4m3fn
|
||||
if store_fp8:
|
||||
assert fp8_scale is not None and fp8_scale.numel() == 1
|
||||
assert fp8_scale.dtype == torch.float32
|
||||
_rope_plain_insert_kernel[(num_tokens,)](
|
||||
latent,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
kv_cache,
|
||||
slot_mapping,
|
||||
fp8_scale if store_fp8 else None,
|
||||
COS_STRIDE=cos_sin_cache.stride(0),
|
||||
CACHE_STRIDE=kv_cache.stride(0),
|
||||
ROW_STRIDE=kv_cache.stride(1),
|
||||
CACHE_BLOCK=kv_cache.shape[1],
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
STORE_FP8=store_fp8,
|
||||
num_warps=4,
|
||||
**launch_kwargs,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _rope_quant_insert_kernel(
|
||||
latent,
|
||||
positions,
|
||||
cos_sin,
|
||||
cache,
|
||||
cache_slots,
|
||||
COS_STRIDE: tl.constexpr,
|
||||
CACHE_STRIDE: tl.constexpr,
|
||||
CACHE_BLOCK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
SANITIZE_CACHE_NANS: tl.constexpr,
|
||||
):
|
||||
t = tl.program_id(0)
|
||||
slot = tl.load(cache_slots + t)
|
||||
if slot < 0:
|
||||
return
|
||||
position = tl.load(positions + t)
|
||||
if (position + 1) % COMPRESS_RATIO != 0:
|
||||
return
|
||||
d = tl.arange(0, 512)
|
||||
normed = tl.load(latent + t.to(tl.int64) * 512 + d).to(tl.float32)
|
||||
page = cache + (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE
|
||||
values = page + (slot % CACHE_BLOCK) * 576
|
||||
scales = page + CACHE_BLOCK * 576 + (slot % CACHE_BLOCK) * 8
|
||||
|
||||
quant = tl.reshape(normed, (8, 64))
|
||||
amax = tl.maximum(tl.max(tl.abs(quant), 1), 1e-4)
|
||||
exponent = tl.ceil(tl.log2(amax * (1.0 / 448.0)))
|
||||
scaled = quant * tl.reshape(tl.exp2(-exponent), (8, 1))
|
||||
fp8 = tl.clamp(scaled, -448.0, 448.0).to(tl.float8e4nv)
|
||||
packed = tl.reshape(fp8.to(tl.uint8, bitcast=True), (512,))
|
||||
tl.store(values + d, packed, d < 448)
|
||||
s = tl.arange(0, 8)
|
||||
max_encoded: tl.constexpr = 254.0 if SANITIZE_CACHE_NANS else 255.0
|
||||
encoded = tl.minimum(tl.maximum(exponent + 127.0, 0.0), max_encoded)
|
||||
tl.store(scales + s, encoded.to(tl.uint8), s < 7)
|
||||
tl.store(scales + 7, tl.full((), 0, tl.uint8))
|
||||
|
||||
even, odd = tl.split(tl.reshape(normed, (256, 2)))
|
||||
pair = tl.arange(0, 256) - 224
|
||||
cs = cos_sin + (position // COMPRESS_RATIO * COMPRESS_RATIO) * COS_STRIDE
|
||||
c = tl.load(cs + tl.maximum(pair, 0), pair >= 0, other=1.0).to(tl.float32)
|
||||
s = tl.load(cs + 32 + tl.maximum(pair, 0), pair >= 0, other=0.0).to(tl.float32)
|
||||
rotated = tl.interleave(even * c - odd * s, odd * c + even * s)
|
||||
if SANITIZE_CACHE_NANS:
|
||||
rotated = tl.where(rotated == rotated, rotated, 0.0)
|
||||
rope_dst = (values + 448).to(tl.pointer_type(tl.bfloat16))
|
||||
tl.store(rope_dst + d - 448, rotated.to(tl.bfloat16), d >= 448)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _rope_plain_insert_kernel(
|
||||
latent,
|
||||
positions,
|
||||
cos_sin,
|
||||
cache,
|
||||
cache_slots,
|
||||
fp8_scale,
|
||||
COS_STRIDE: tl.constexpr,
|
||||
CACHE_STRIDE: tl.constexpr,
|
||||
ROW_STRIDE: tl.constexpr,
|
||||
CACHE_BLOCK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
STORE_FP8: tl.constexpr,
|
||||
):
|
||||
t = tl.program_id(0)
|
||||
slot = tl.load(cache_slots + t)
|
||||
if slot < 0:
|
||||
return
|
||||
position = tl.load(positions + t)
|
||||
if (position + 1) % COMPRESS_RATIO != 0:
|
||||
return
|
||||
d = tl.arange(0, 512)
|
||||
normed = tl.load(latent + t.to(tl.int64) * 512 + d).to(tl.float32)
|
||||
|
||||
# NoPE pairs load (cos, sin) = (1, 0), so the rotation is the identity there.
|
||||
even, odd = tl.split(tl.reshape(normed, (256, 2)))
|
||||
pair = tl.arange(0, 256) - 224
|
||||
cs = cos_sin + (position // COMPRESS_RATIO * COMPRESS_RATIO) * COS_STRIDE
|
||||
c = tl.load(cs + tl.maximum(pair, 0), pair >= 0, other=1.0).to(tl.float32)
|
||||
s = tl.load(cs + 32 + tl.maximum(pair, 0), pair >= 0, other=0.0).to(tl.float32)
|
||||
row = tl.interleave(even * c - odd * s, odd * c + even * s).to(tl.bfloat16)
|
||||
|
||||
dst = (
|
||||
cache
|
||||
+ (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE
|
||||
+ (slot % CACHE_BLOCK) * ROW_STRIDE
|
||||
)
|
||||
if STORE_FP8:
|
||||
scaled = row.to(tl.float32) * (1.0 / tl.load(fp8_scale))
|
||||
tl.store(dst + d, tl.clamp(scaled, -448.0, 448.0).to(tl.float8e4nv))
|
||||
else:
|
||||
tl.store(dst + d, row)
|
||||
@@ -0,0 +1,253 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Indexer K production for DeepSeek V4.1 kv-source layers.
|
||||
|
||||
In v4.1 the index key is derived from the *main* compressor's latent:
|
||||
``k = k_norm(wk(latent))`` (reference model.py Indexer.forward), then RoPE'd
|
||||
at the group's first-token position and MXFP4/FP8-quantized into the paged
|
||||
indexer K cache. The ``wk(latent)`` GEMM runs in torch; this kernel fuses the
|
||||
remaining k_norm → RoPE → quant → paged store, one program per token.
|
||||
|
||||
Unlike the legacy (v4.0) indexer path there is no per-token pooling from a
|
||||
compressor state cache: the latent already stands for a whole group, so only
|
||||
group-boundary tokens ``(position + 1) % compress_ratio == 0`` produce a key.
|
||||
"""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from . import MXFP4_BLOCK_SIZE, _fp32x2_to_fp4x2
|
||||
|
||||
# ROCm tiled ("SHUFFLE") indexer K value layout, mirroring
|
||||
# indexer_k_quant_and_cache_triton's defaults: 16 positions x 16 bytes.
|
||||
_BLOCK_TILE_SIZE = 16
|
||||
_HEAD_TILE_SIZE = 16
|
||||
|
||||
|
||||
def indexer_k_norm_rope_store(
|
||||
k_pre: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
rms_norm_weight: torch.Tensor,
|
||||
rms_norm_eps: float,
|
||||
k_cache: torch.Tensor,
|
||||
kv_slot_mapping: torch.Tensor,
|
||||
compress_ratio: int,
|
||||
use_fp4_cache: bool,
|
||||
) -> None:
|
||||
"""k_norm → RoPE → quant → paged store for indexer keys.
|
||||
|
||||
Args:
|
||||
k_pre: [num_tokens, 128] bf16, the ``wk(latent)`` projection. Only
|
||||
group-boundary rows are read.
|
||||
positions: [num_tokens] int64 token positions.
|
||||
cos_sin_cache: [max_pos, rope_head_dim] GPT-J layout (cos half, then
|
||||
sin half), from the layer's compress-RoPE instance.
|
||||
rms_norm_weight: [128] k_norm weight.
|
||||
k_cache: uint8 paged indexer cache [num_blocks, block_size, row_bytes].
|
||||
kv_slot_mapping: [num_tokens] slots in the indexer cache (-1 = skip).
|
||||
compress_ratio: group size; keys are emitted at group boundaries.
|
||||
use_fp4_cache: MXFP4 (2 nibbles/byte + ue8m0 per 32) when True, else
|
||||
per-token FP8 with a single fp32 scale.
|
||||
"""
|
||||
num_tokens = kv_slot_mapping.numel()
|
||||
assert k_pre.ndim == 2 and k_pre.shape[1] == 128
|
||||
assert k_pre.dtype == torch.bfloat16 and k_pre.stride(1) == 1
|
||||
assert num_tokens <= k_pre.shape[0] and num_tokens <= positions.numel()
|
||||
assert compress_ratio in (1, 2)
|
||||
if num_tokens == 0:
|
||||
return
|
||||
|
||||
head_dim = k_pre.shape[1]
|
||||
if use_fp4_cache:
|
||||
token_stride = head_dim // 2
|
||||
scale_dim = head_dim // MXFP4_BLOCK_SIZE
|
||||
else:
|
||||
token_stride = head_dim
|
||||
scale_dim = 4 # single float32 scale
|
||||
|
||||
# ROCm reads this cache back with the 16x16-tiled ("SHUFFLE") value
|
||||
# layout: cp_gather_indexer_k_quant_cache_triton on prefill and aiter's
|
||||
# deepgemm_fp8_paged_mqa_logits(Preshuffle=True) on decode both select it
|
||||
# from ``block_size > 1``, matching the v4.0 writer
|
||||
# (indexer_k_quant_and_cache_triton). Writing row-major here would hand
|
||||
# both readers permuted key bytes.
|
||||
block_size = k_cache.shape[1]
|
||||
shuffle = current_platform.is_rocm() and block_size > 1
|
||||
if shuffle:
|
||||
if use_fp4_cache:
|
||||
raise NotImplementedError(
|
||||
"MXFP4 indexer K cache has no tiled ROCm layout; "
|
||||
"the ROCm readers only implement the FP8 one."
|
||||
)
|
||||
if block_size % _BLOCK_TILE_SIZE != 0 or head_dim % _HEAD_TILE_SIZE != 0:
|
||||
raise ValueError(
|
||||
f"ROCm tiled indexer K cache needs block_size "
|
||||
f"({block_size}) % {_BLOCK_TILE_SIZE} == 0 and head_dim "
|
||||
f"({head_dim}) % {_HEAD_TILE_SIZE} == 0."
|
||||
)
|
||||
|
||||
launch_kwargs = {"launch_pdl": False} if current_platform.is_cuda() else {}
|
||||
_indexer_k_norm_rope_quant_store_kernel[(num_tokens,)](
|
||||
k_pre,
|
||||
k_pre.stride(0),
|
||||
positions,
|
||||
rms_norm_weight,
|
||||
rms_norm_eps,
|
||||
cos_sin_cache,
|
||||
cos_sin_cache.stride(0),
|
||||
k_cache,
|
||||
kv_slot_mapping,
|
||||
k_cache.shape[1],
|
||||
HEAD_SIZE=head_dim,
|
||||
ROPE_HEAD_DIM=64,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
TOKEN_STRIDE=token_stride,
|
||||
SCALE_DIM=scale_dim,
|
||||
KV_BLOCK_STRIDE=k_cache.stride(0),
|
||||
FP8_MAX=448.0,
|
||||
USE_FP4=use_fp4_cache,
|
||||
SHUFFLE=shuffle,
|
||||
BLOCK_TILE_SIZE=_BLOCK_TILE_SIZE,
|
||||
HEAD_TILE_SIZE=_HEAD_TILE_SIZE,
|
||||
num_warps=1,
|
||||
**launch_kwargs,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _indexer_k_norm_rope_quant_store_kernel(
|
||||
k_pre_ptr,
|
||||
k_pre_stride,
|
||||
positions_ptr,
|
||||
rms_norm_weight_ptr,
|
||||
rms_norm_eps,
|
||||
cos_sin_cache_ptr,
|
||||
cos_sin_stride,
|
||||
k_cache_ptr,
|
||||
kv_slot_mapping_ptr,
|
||||
kv_cache_block_size,
|
||||
HEAD_SIZE: tl.constexpr,
|
||||
ROPE_HEAD_DIM: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
TOKEN_STRIDE: tl.constexpr,
|
||||
SCALE_DIM: tl.constexpr,
|
||||
KV_BLOCK_STRIDE: tl.constexpr,
|
||||
FP8_MAX: tl.constexpr,
|
||||
USE_FP4: tl.constexpr,
|
||||
SHUFFLE: tl.constexpr,
|
||||
BLOCK_TILE_SIZE: tl.constexpr,
|
||||
HEAD_TILE_SIZE: tl.constexpr,
|
||||
):
|
||||
token_idx = tl.program_id(0)
|
||||
|
||||
kv_slot_idx = tl.load(kv_slot_mapping_ptr + token_idx)
|
||||
if kv_slot_idx < 0:
|
||||
return
|
||||
position = tl.load(positions_ptr + token_idx)
|
||||
# Only the last token of a group publishes that group's index key.
|
||||
if (position + 1) % COMPRESS_RATIO != 0:
|
||||
return
|
||||
|
||||
block = tl.arange(0, HEAD_SIZE)
|
||||
|
||||
# ── k_norm (fp32 throughout, bf16 roundtrip like the reference) ────
|
||||
k = tl.load(k_pre_ptr + token_idx * k_pre_stride + block).to(tl.float32)
|
||||
rms_w = tl.load(rms_norm_weight_ptr + block).to(tl.float32)
|
||||
variance = tl.sum(k * k, axis=0) / HEAD_SIZE
|
||||
k = (k * tl.rsqrt(variance + rms_norm_eps) * rms_w).to(tl.bfloat16)
|
||||
k = k.to(tl.float32)
|
||||
|
||||
# ── Register-based GPT-J forward RoPE in fp32 ─────────────────────
|
||||
# A latent stands for the first token of its group, so group j takes
|
||||
# position j * compress_ratio.
|
||||
NUM_PAIRS: tl.constexpr = HEAD_SIZE // 2
|
||||
NOPE_HEAD_DIM: tl.constexpr = HEAD_SIZE - ROPE_HEAD_DIM
|
||||
NOPE_PAIRS: tl.constexpr = NOPE_HEAD_DIM // 2
|
||||
HALF_ROPE: tl.constexpr = ROPE_HEAD_DIM // 2
|
||||
|
||||
even, odd = tl.split(tl.reshape(k, (NUM_PAIRS, 2))) # each [NUM_PAIRS]
|
||||
pair_idx = tl.arange(0, NUM_PAIRS)
|
||||
rope_pair_local = pair_idx - NOPE_PAIRS
|
||||
is_rope_pair = rope_pair_local >= 0
|
||||
cs_idx = tl.maximum(rope_pair_local, 0)
|
||||
|
||||
compressed_pos = (position // COMPRESS_RATIO) * COMPRESS_RATIO
|
||||
cache_base = cos_sin_cache_ptr + compressed_pos * cos_sin_stride
|
||||
cos_v = tl.load(cache_base + cs_idx, mask=is_rope_pair, other=1.0)
|
||||
sin_v = tl.load(cache_base + HALF_ROPE + cs_idx, mask=is_rope_pair, other=0.0)
|
||||
|
||||
new_even = even * cos_v - odd * sin_v
|
||||
new_odd = odd * cos_v + even * sin_v
|
||||
|
||||
# bf16 roundtrip for parity with the reference / Q-side kernel numerics.
|
||||
new_even = new_even.to(tl.bfloat16).to(tl.float32)
|
||||
new_odd = new_odd.to(tl.bfloat16).to(tl.float32)
|
||||
|
||||
# ── Paged cache pointers (segregated: values first, then scales) ──
|
||||
kv_block_idx = kv_slot_idx // kv_cache_block_size
|
||||
kv_pos_in_block = kv_slot_idx % kv_cache_block_size
|
||||
cache_block_ptr = k_cache_ptr + kv_block_idx.to(tl.int64) * KV_BLOCK_STRIDE
|
||||
if SHUFFLE:
|
||||
# [block_size // BT, HEAD_SIZE // HT, BT, HT] value tiles.
|
||||
val_ptr = (
|
||||
cache_block_ptr
|
||||
+ (kv_pos_in_block // BLOCK_TILE_SIZE) * BLOCK_TILE_SIZE * TOKEN_STRIDE
|
||||
+ (kv_pos_in_block % BLOCK_TILE_SIZE) * HEAD_TILE_SIZE
|
||||
)
|
||||
else:
|
||||
val_ptr = cache_block_ptr + kv_pos_in_block * TOKEN_STRIDE
|
||||
scale_ptr = (
|
||||
cache_block_ptr
|
||||
+ kv_cache_block_size * TOKEN_STRIDE
|
||||
+ kv_pos_in_block * SCALE_DIM
|
||||
)
|
||||
|
||||
if USE_FP4:
|
||||
# MXFP4: each 32-element block = 16 consecutive even/odd pairs, so
|
||||
# tiling the halves into (N_BLOCKS, 16) lands one block per row.
|
||||
N_QUANT_BLOCKS: tl.constexpr = HEAD_SIZE // 32
|
||||
HALF_BLOCK: tl.constexpr = 16
|
||||
even_2d = tl.reshape(new_even, (N_QUANT_BLOCKS, HALF_BLOCK))
|
||||
odd_2d = tl.reshape(new_odd, (N_QUANT_BLOCKS, HALF_BLOCK))
|
||||
|
||||
amax = tl.maximum(
|
||||
tl.max(tl.abs(even_2d), axis=1),
|
||||
tl.max(tl.abs(odd_2d), axis=1),
|
||||
)
|
||||
amax = tl.maximum(amax, 6.0 * (2**-126))
|
||||
# ue8m0 block scale: 2^ceil(log2(amax / 6.0)), stored (exp + 127).
|
||||
log2_ratio = tl.ceil(tl.log2(amax * (1.0 / 6.0)))
|
||||
log2_ratio = tl.minimum(tl.maximum(log2_ratio, -127.0), 127.0)
|
||||
inv_scale = tl.exp2(-log2_ratio)
|
||||
ue8m0 = (log2_ratio + 127.0).to(tl.uint8) # [N_QUANT_BLOCKS]
|
||||
|
||||
inv_scale_col = tl.reshape(inv_scale, (N_QUANT_BLOCKS, 1))
|
||||
packed = _fp32x2_to_fp4x2(
|
||||
even_2d * inv_scale_col, odd_2d * inv_scale_col
|
||||
) # (N_BLOCKS, HALF_BLOCK) uint8
|
||||
packed_flat = tl.reshape(packed, (TOKEN_STRIDE,))
|
||||
|
||||
tl.store(val_ptr + tl.arange(0, TOKEN_STRIDE), packed_flat)
|
||||
tl.store(scale_ptr + tl.arange(0, SCALE_DIM), ue8m0)
|
||||
else:
|
||||
# Per-token FP8 (single 128-wide block) with one float32 scale.
|
||||
result = tl.interleave(new_even, new_odd) # [HEAD_SIZE] fp32
|
||||
result_bf16 = result.to(tl.bfloat16).to(tl.float32)
|
||||
INV_FP8_MAX: tl.constexpr = 1.0 / FP8_MAX
|
||||
absmax = tl.maximum(tl.max(tl.abs(result_bf16), axis=0), 1e-4)
|
||||
exponent = tl.ceil(tl.log2(absmax * INV_FP8_MAX))
|
||||
inv_scale = tl.exp2(-exponent)
|
||||
x_clamped = tl.clamp(result_bf16 * inv_scale, -FP8_MAX, FP8_MAX)
|
||||
x_uint8 = x_clamped.to(tl.float8e4nv).to(tl.uint8, bitcast=True)
|
||||
if SHUFFLE:
|
||||
tiled = (
|
||||
block // HEAD_TILE_SIZE * BLOCK_TILE_SIZE * HEAD_TILE_SIZE
|
||||
+ block % HEAD_TILE_SIZE
|
||||
)
|
||||
tl.store(val_ptr + tiled, x_uint8)
|
||||
else:
|
||||
tl.store(val_ptr + block, x_uint8)
|
||||
tl.store(scale_ptr.to(tl.pointer_type(tl.float32)), tl.exp2(exponent))
|
||||
@@ -0,0 +1,142 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _norm_row(x, weight, row, stride, eps, SIZE: tl.constexpr, BLOCK: tl.constexpr):
|
||||
cols = tl.arange(0, BLOCK)
|
||||
w = tl.load(weight + cols, cols < SIZE, 0).to(tl.float32)
|
||||
values = tl.load(x + row * stride + cols, cols < SIZE, 0).to(tl.float32)
|
||||
rrms = tl.rsqrt(tl.sum(values * values, 0) / SIZE + eps)
|
||||
return values * rrms * w
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_tokens"])
|
||||
def _q_kv_norm_quant_kernel(
|
||||
q,
|
||||
kv,
|
||||
qw,
|
||||
kvw,
|
||||
qo,
|
||||
kvo,
|
||||
scales,
|
||||
num_tokens,
|
||||
q_stride,
|
||||
kv_stride,
|
||||
eps,
|
||||
Q_SIZE: tl.constexpr,
|
||||
KV_SIZE: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
LAUNCH_PDL: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0).to(tl.int64)
|
||||
cols = tl.arange(0, BLOCK)
|
||||
if LAUNCH_PDL:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
if tl.program_id(1) == 0:
|
||||
groups = tl.arange(0, BLOCK // 32)
|
||||
if row < num_tokens:
|
||||
y = _norm_row(q, qw, row, q_stride, eps, Q_SIZE, BLOCK)
|
||||
# Preserve the materialized normalization output's rounding boundary.
|
||||
y = y.to(q.dtype.element_ty).to(tl.float32)
|
||||
grouped = tl.reshape(y, (BLOCK // 32, 32))
|
||||
amax = tl.max(tl.abs(grouped), 1)
|
||||
normalized = amax * (1.0 / 448.0)
|
||||
bits = normalized.to(tl.uint32, bitcast=True)
|
||||
exponent = (bits >> 23) & 255
|
||||
mantissa = bits & 0x7FFFFF
|
||||
bump = (mantissa != 0) & ~((exponent == 0) & (mantissa <= 0x400000))
|
||||
sf = tl.minimum(exponent + bump, 254)
|
||||
sf = tl.where(normalized <= 0, 0, sf)
|
||||
# Match FlashInfer's UE8M0 conversion, including zero/subnormal scales.
|
||||
inv_bits = tl.where(sf == 0, 0, (254 - sf) << 23)
|
||||
inv_scale = inv_bits.to(tl.float32, bitcast=True)
|
||||
quantized = tl.reshape(grouped * inv_scale[:, None], (BLOCK,))
|
||||
tl.store(qo + row * Q_SIZE + cols, quantized, cols < Q_SIZE)
|
||||
else:
|
||||
sf = tl.full((BLOCK // 32,), 0, tl.uint32)
|
||||
padded_groups: tl.constexpr = triton.cdiv(Q_SIZE // 32, 4) * 4
|
||||
sf = tl.where(groups < Q_SIZE // 32, sf, 0)
|
||||
# F8_128x4: [row/128, group/4, row%32, row%128/32, group%4].
|
||||
offsets = (
|
||||
row // 128 * (128 * padded_groups)
|
||||
+ groups // 4 * 512
|
||||
+ row % 32 * 16
|
||||
+ row % 128 // 32 * 4
|
||||
+ groups % 4
|
||||
)
|
||||
tl.store(scales + offsets, sf, groups < padded_groups)
|
||||
elif row < num_tokens:
|
||||
y = _norm_row(kv, kvw, row, kv_stride, eps, KV_SIZE, BLOCK)
|
||||
tl.store(kvo + row * KV_SIZE + cols, y, cols < KV_SIZE)
|
||||
|
||||
|
||||
def fused_q_kv_rmsnorm_quant(
|
||||
qr: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
kv_weight: torch.Tensor,
|
||||
eps: float,
|
||||
) -> tuple[QuantizedActivation, torch.Tensor]:
|
||||
"""Normalize Q/KV and quantize Q with FlashInfer's swizzled MXFP8 scales."""
|
||||
assert qr.ndim == kv.ndim == 2 and qr.shape[0] == kv.shape[0]
|
||||
assert qr.stride(-1) == kv.stride(-1) == 1
|
||||
assert q_weight.is_contiguous() and kv_weight.is_contiguous()
|
||||
assert qr.shape[1] % 32 == 0
|
||||
tokens, q_size = qr.shape
|
||||
kv_size = kv.shape[1]
|
||||
qo = torch.empty(qr.shape, dtype=torch.float8_e4m3fn, device=qr.device)
|
||||
kvo = torch.empty(kv.shape, dtype=kv.dtype, device=kv.device)
|
||||
padded_tokens = triton.cdiv(tokens, 128) * 128
|
||||
padded_groups = triton.cdiv(q_size // 32, 4) * 4
|
||||
scales = torch.empty(
|
||||
padded_tokens * padded_groups, dtype=torch.uint8, device=qr.device
|
||||
)
|
||||
if tokens:
|
||||
block = triton.next_power_of_2(max(q_size, kv_size))
|
||||
_q_kv_norm_quant_kernel[(padded_tokens, 2)](
|
||||
qr,
|
||||
kv,
|
||||
q_weight,
|
||||
kv_weight,
|
||||
qo,
|
||||
kvo,
|
||||
scales,
|
||||
tokens,
|
||||
qr.stride(0),
|
||||
kv.stride(0),
|
||||
eps,
|
||||
q_size,
|
||||
kv_size,
|
||||
block,
|
||||
current_platform.is_arch_support_pdl(),
|
||||
num_warps=8 if block >= 2048 else 4,
|
||||
)
|
||||
return QuantizedActivation(qo, scales, qr.dtype, qr.shape, kMxfp8Dynamic), kvo
|
||||
|
||||
|
||||
def can_fuse_query_quant(linears: list[torch.nn.Module]) -> bool:
|
||||
"""Require both local projections to use the same MXFP8 activation ABI."""
|
||||
if not current_platform.is_cuda():
|
||||
return False
|
||||
from vllm.model_executor.kernels.linear.mxfp8.flashinfer import (
|
||||
FlashInferCutedslMxfp8LinearKernel,
|
||||
FlashInferCutlassMxfp8LinearKernel,
|
||||
)
|
||||
|
||||
# QuantKey does not encode scale layout; restrict this producer to the
|
||||
# consumers that accept F8_128x4 swizzled scales.
|
||||
return all(
|
||||
getattr(linear, "input_quant_key", None) == kMxfp8Dynamic
|
||||
and type(getattr(getattr(linear, "quant_method", None), "kernel", None))
|
||||
in (FlashInferCutedslMxfp8LinearKernel, FlashInferCutlassMxfp8LinearKernel)
|
||||
for linear in linears
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepseekV4 rotary embedding initialization."""
|
||||
|
||||
from vllm.model_executor.layers.rotary_embedding import get_rope
|
||||
from vllm.model_executor.layers.rotary_embedding.base import RotaryEmbedding
|
||||
|
||||
|
||||
def build_deepseek_v4_rope(
|
||||
config,
|
||||
*,
|
||||
head_dim: int,
|
||||
rope_head_dim: int,
|
||||
max_position_embeddings: int,
|
||||
compress_ratio: int,
|
||||
) -> RotaryEmbedding:
|
||||
rope_parameters = config.rope_parameters
|
||||
# Newer checkpoints nest per-layer-type rope dicts ({"main", "compress"});
|
||||
# older ones ship a single flat dict shared by all layer types.
|
||||
if isinstance(rope_parameters.get("main"), dict) and isinstance(
|
||||
rope_parameters.get("compress"), dict
|
||||
):
|
||||
key = "compress" if compress_ratio > 0 else "main"
|
||||
rope_parameters = dict(rope_parameters[key])
|
||||
else:
|
||||
rope_parameters = dict(rope_parameters)
|
||||
|
||||
rope_parameters["rope_theta"] = (
|
||||
config.compress_rope_theta if compress_ratio > 0 else config.rope_theta
|
||||
)
|
||||
if compress_ratio > 0 and rope_parameters["rope_type"] != "default":
|
||||
# YaRN applies to all compressed-KV layers (compress_ratio > 0); only
|
||||
# pure sliding-window layers (compress_ratio == 0) use plain RoPE.
|
||||
rope_parameters["rope_type"] = (
|
||||
"deepseek_yarn"
|
||||
if rope_parameters.get("apply_yarn_scaling", True)
|
||||
else "deepseek_llama_scaling"
|
||||
)
|
||||
else:
|
||||
# Sliding-window layers use plain RoPE (theta=rope_theta, no YaRN).
|
||||
rope_parameters["rope_type"] = "deepseek_yarn"
|
||||
rope_parameters["factor"] = 1.0
|
||||
rope_parameters["original_max_position_embeddings"] = max_position_embeddings
|
||||
rope_parameters["mscale"] = 0 # Disable mscale
|
||||
rope_parameters["mscale_all_dim"] = 0 # Disable mscale
|
||||
rope_parameters["is_deepseek_v4"] = True
|
||||
rope_parameters["rope_dim"] = rope_head_dim
|
||||
return get_rope(
|
||||
head_dim,
|
||||
max_position=max_position_embeddings,
|
||||
rope_parameters=rope_parameters,
|
||||
is_neox_style=False,
|
||||
)
|
||||
Reference in New Issue
Block a user