[Feat] Add native Mooncake KV transfer from AR to DiT (#7166)
Signed-off-by: asukaqaq-s <1311722138@qq.com> Signed-off-by: Acerak01-fy <wfy2003324@163.com> Co-authored-by: Acerak01-fy <wfy2003324@163.com> Co-authored-by: amy-why-3459 <wuhaiyan17@huawei.com>
This commit is contained in:
53 files changed
+2564
-204
No files matched your search
@@ -75,7 +75,11 @@ from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
SequenceParallelOutput,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.forward_context import (
|
||||
get_paged_kv_computed_tokens,
|
||||
paged_kv_prefill,
|
||||
set_forward_context_denoise_step_idx,
|
||||
)
|
||||
from vllm_omni.diffusion.layers.fused_moe import FusedMoE
|
||||
from vllm_omni.diffusion.layers.norm import RMSNorm
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
|
||||
@@ -1097,8 +1101,6 @@ class ImageKVCacheManager(nn.Module):
|
||||
layer resolves the actual CUDA or Ascend paged kernel.
|
||||
"""
|
||||
|
||||
if uncond_cfg_prefill:
|
||||
raise RuntimeError("Hunyuan negative-CFG prefill must run before paged row activation")
|
||||
if self._injected_ar_kv is not None:
|
||||
raise NotImplementedError("Hunyuan Scheduler-paged KV does not support imported AR KV")
|
||||
if not query_lens or len(seq_lens) != len(query_lens):
|
||||
@@ -1109,7 +1111,6 @@ class ImageKVCacheManager(nn.Module):
|
||||
self.clear_legacy_prompt_kv_cache()
|
||||
bs = len(query_lens)
|
||||
q_len = query_lens[0]
|
||||
seq_len = seq_lens[0]
|
||||
assert query.shape[0] == bs * q_len, f"{query.shape[0]} != {bs * q_len}"
|
||||
|
||||
head_num_per_rank = query.shape[1]
|
||||
@@ -1121,22 +1122,19 @@ class ImageKVCacheManager(nn.Module):
|
||||
value = value.reshape(bs, q_len, kv_head_num_per_rank, head_dim)
|
||||
|
||||
joint_text_query = joint_text_key = joint_text_value = None
|
||||
if self.sp_size > 1 and first_step:
|
||||
if self.sp_size > 1 and uncond_cfg_prefill:
|
||||
joint_text_query, joint_text_key, joint_text_value = query, key, value
|
||||
query, key, value = query[:, :0], key[:, :0], value[:, :0]
|
||||
elif self.sp_size > 1 and first_step:
|
||||
if shard_image_size is None or shard_image_size <= 0:
|
||||
raise ValueError("Hunyuan paged Ulysses requires a positive local image shard size")
|
||||
local_prompt_len = seq_len - shard_image_size
|
||||
joint_query_len = query.shape[1] - shard_image_size
|
||||
if local_prompt_len != joint_query_len:
|
||||
raise ValueError(
|
||||
"Hunyuan paged Ulysses prompt layout mismatch: "
|
||||
f"key_prompt={local_prompt_len}, query_prompt={joint_query_len}"
|
||||
)
|
||||
joint_text_query = query[:, :joint_query_len]
|
||||
joint_text_key = key[:, :local_prompt_len]
|
||||
joint_text_value = value[:, :local_prompt_len]
|
||||
joint_text_key = key[:, :joint_query_len]
|
||||
joint_text_value = value[:, :joint_query_len]
|
||||
query = query[:, joint_query_len:]
|
||||
key = key[:, local_prompt_len:]
|
||||
value = value[:, local_prompt_len:]
|
||||
key = key[:, joint_query_len:]
|
||||
value = value[:, joint_query_len:]
|
||||
|
||||
if joint_text_query is None:
|
||||
attn_metadata = AttentionMetadata(full_attn_spans=full_attn_spans)
|
||||
@@ -1254,6 +1252,8 @@ class ImageKVCacheManager(nn.Module):
|
||||
) -> torch.Tensor:
|
||||
self.image_token_len = kwargs.get("num_image_tokens")
|
||||
if self.attn.is_paged_kv_active():
|
||||
# A native connector fills the same Scheduler-owned pages as
|
||||
# local prefill. Imported prefixes need no dense reconstruction.
|
||||
full_attn_spans = kwargs.get("full_attn_spans")
|
||||
if full_attn_spans is None:
|
||||
raise ValueError("Hunyuan Scheduler-paged KV requires full_attn_spans metadata")
|
||||
@@ -1837,7 +1837,9 @@ class HunYuanAttention(nn.Module):
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
scaling=self.scaling,
|
||||
image_token_len=4097,
|
||||
prefix=f"{prefix}.image_attn",
|
||||
# Native Mooncake pairs this canonical KV layer name with the AR
|
||||
# HunYuanAttention: model.layers.N.self_attn.attn. Keep both in sync.
|
||||
prefix=f"model.{prefix}",
|
||||
)
|
||||
self.image_rope2d_emb = HunYuanRotary2DEmbedder(
|
||||
num_heads=self.num_heads,
|
||||
@@ -2964,7 +2966,10 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
seq_lens=[prefill_seq_len],
|
||||
num_image_tokens=0,
|
||||
ar_kv_reuse_len=negative_reuse_len,
|
||||
full_attn_spans=model_kwargs["full_attn_spans"][batch_slice]
|
||||
full_attn_spans=[
|
||||
[(start, min(end, prefill_seq_len)) for start, end in spans if start < prefill_seq_len]
|
||||
for spans in model_kwargs["full_attn_spans"][batch_slice]
|
||||
]
|
||||
if model_kwargs.get("full_attn_spans")
|
||||
else None,
|
||||
)
|
||||
@@ -3019,6 +3024,28 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
device,
|
||||
):
|
||||
ar_kv_data = model_kwargs.pop("ar_kv_data", None)
|
||||
computed_tokens = get_paged_kv_computed_tokens()
|
||||
if computed_tokens and computed_tokens[0] > 0:
|
||||
positive_reuse_len = computed_tokens[0]
|
||||
if (
|
||||
len(computed_tokens) > 1
|
||||
and computed_tokens[1] < positive_reuse_len
|
||||
and (not cfg_parallel_ready or cfg_rank == 1)
|
||||
):
|
||||
prefill_inputs = self._build_negative_cfg_prefill_inputs(
|
||||
input_ids,
|
||||
model_kwargs,
|
||||
batch_size,
|
||||
computed_tokens[1],
|
||||
positive_reuse_len,
|
||||
cfg_parallel_ready,
|
||||
)
|
||||
with (
|
||||
paged_kv_prefill(1, positive_reuse_len),
|
||||
torch.autocast(device_type=device.type, dtype=torch.bfloat16),
|
||||
):
|
||||
self.model.forward_call(**prefill_inputs)
|
||||
return self._truncate_reused_prefix(input_ids, model_kwargs, positive_reuse_len), positive_reuse_len
|
||||
if ar_kv_data is None:
|
||||
logger.debug(
|
||||
"[AR KV Reuse] cfg_rank=%s: no AR KV received, fallback to full recompute (reuse_len=0)",
|
||||
|
||||
@@ -367,6 +367,8 @@ class HunyuanImage3Pipeline(
|
||||
|
||||
def __init__(self, od_config: OmniDiffusionConfig) -> None:
|
||||
self.hf_config = get_config(od_config.model, trust_remote_code=True)
|
||||
self.hf_config.cfg_distilled = _config_flag(self.hf_config, "cfg_distilled")
|
||||
self.hf_config.use_meanflow = _config_flag(self.hf_config, "use_meanflow")
|
||||
super().__init__(self.hf_config)
|
||||
# update diffusion config
|
||||
self.generation_config = GenerationConfig.from_pretrained(od_config.model)
|
||||
@@ -1282,7 +1284,9 @@ class HunyuanImage3Pipeline(
|
||||
|
||||
# 4. Encode conditional images
|
||||
# Skip encoding if AR KV reuse is enabled
|
||||
has_ar_kv = kwargs.get("ar_kv_data")
|
||||
has_ar_kv = kwargs.get("ar_kv_data") or request_layout_utils.native_kv_covers_cond_images(
|
||||
output, kwargs.get("kv_computed_tokens", ())
|
||||
)
|
||||
if batch_cond_image_info is not None and len(batch_cond_image_info[0]) > 0 and not has_ar_kv:
|
||||
cond_vae_images, cond_timestep, cond_vit_images = self._encode_cond_image(
|
||||
batch_cond_image_info, cfg_factor[mode], generator=generator
|
||||
@@ -1894,6 +1898,7 @@ class HunyuanImage3Pipeline(
|
||||
pipe._guidance_scale = guidance_scale
|
||||
pipe._guidance_rescale = getattr(sampling, "guidance_rescale", 0.0)
|
||||
|
||||
ar_kv_kwargs = self._extract_ar_kv_from_sampling(sampling)
|
||||
model_kwargs = self.prepare_model_inputs(
|
||||
prompt=prompt,
|
||||
cot_text=cot_text,
|
||||
@@ -1906,8 +1911,10 @@ class HunyuanImage3Pipeline(
|
||||
batch_cond_image_info=batch_cond_image_info,
|
||||
bot_task=tokenizer_bot_task,
|
||||
prepared_layout=request_layout_utils.get_hunyuan_prepared_layout(state),
|
||||
kv_computed_tokens=state.extra.get("kv_computed_tokens", ()),
|
||||
**ar_kv_kwargs,
|
||||
)
|
||||
model_kwargs.update(self._extract_ar_kv_from_sampling(sampling))
|
||||
model_kwargs.update(ar_kv_kwargs)
|
||||
model_kwargs["use_cache"] = False
|
||||
|
||||
input_ids = model_kwargs.pop("input_ids")
|
||||
@@ -2337,6 +2344,7 @@ class HunyuanImage3Pipeline(
|
||||
batch_cond_image_info=batch_cond_image_info,
|
||||
bot_task=tokenizer_bot_task,
|
||||
prepared_layout=request_layout_utils.get_hunyuan_prepared_layout(req.requests[0]),
|
||||
kv_computed_tokens=getattr(req.requests[0], "kv_computed_tokens", ()),
|
||||
**ar_kv_kwargs,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -373,7 +373,32 @@ def build_hunyuan_diffusion_kv_requests(
|
||||
real_pos = tokenizer_output.real_pos
|
||||
assert prefix_positions is not None and real_pos is not None
|
||||
|
||||
def boundary_rows(field_name: str) -> list[int | None]:
|
||||
positions = getattr(tokenizer_output, field_name)
|
||||
if positions is None:
|
||||
return [None] * cfg_factor
|
||||
if not isinstance(positions, list) or not positions:
|
||||
raise ValueError(f"Hunyuan {field_name} must be a non-empty boundary list")
|
||||
# Batched tokenizer output contains a separate boundary for each CFG
|
||||
# row. Never broadcast a conditional boundary into a negative row.
|
||||
if cfg_factor == 1 and len(positions) == 1 and (positions[0] is None or type(positions[0]) is int):
|
||||
return positions
|
||||
if len(positions) == cfg_factor and all(
|
||||
isinstance(row, list) and len(row) == 1 and (row[0] is None or type(row[0]) is int) for row in positions
|
||||
):
|
||||
return [row[0] for row in positions]
|
||||
raise ValueError(f"Hunyuan {field_name} must contain one boundary per CFG row")
|
||||
|
||||
think_boundaries = boundary_rows("think_recaption_end_pos")
|
||||
uncond_boundaries = boundary_rows("uncond_cfg_start_pos")
|
||||
|
||||
target_len = hunyuan_num_image_tokens(prepared_layout.generated_image_info)
|
||||
reusable_lens = [0] * cfg_factor
|
||||
if think_boundaries[0] is not None:
|
||||
reusable_lens[0] = think_boundaries[0] or 0
|
||||
if any(boundary is not None for boundary in uncond_boundaries):
|
||||
for sequence_id in range(1, cfg_factor):
|
||||
reusable_lens[sequence_id] = min(reusable_lens[0], uncond_boundaries[sequence_id] or 0)
|
||||
return tuple(
|
||||
DiffusionKVRequest(
|
||||
f"{request.request_id}/diffusion-kv/{sequence_id}",
|
||||
@@ -383,6 +408,7 @@ def build_hunyuan_diffusion_kv_requests(
|
||||
prefix_len=int(prefix_row[-1].item()),
|
||||
target_len=target_len,
|
||||
seq_len=int(valid_row[-1].item()),
|
||||
prompt_token_ids=tokenizer_output.tokens[sequence_id, : reusable_lens[sequence_id]].tolist(),
|
||||
# Prompt and reference-image tokens are already embedded in this
|
||||
# row's primary self-attention sequence. Hunyuan therefore has no
|
||||
# independently projected cross/joint-attention KV context.
|
||||
@@ -401,3 +427,14 @@ def get_hunyuan_prepared_layout(source: Any) -> HunyuanPreparedLayout | None:
|
||||
f"HunyuanImage3 expected prepared_layout to be HunyuanPreparedLayout, got {type(prepared_layout).__name__}"
|
||||
)
|
||||
return prepared_layout
|
||||
|
||||
|
||||
def native_kv_covers_cond_images(output: TokenizerEncodeOutput, computed_tokens: tuple[int, ...]) -> bool:
|
||||
"""Skip image encoding only when every CFG row already contains its image KV."""
|
||||
image_slices = output.joint_image_slices
|
||||
if not image_slices or len(image_slices) != len(computed_tokens):
|
||||
return False
|
||||
return all(
|
||||
slices and all(image_slice.stop <= computed for image_slice in slices)
|
||||
for slices, computed in zip(image_slices, computed_tokens, strict=True)
|
||||
)
|
||||
Reference in new issue
Block a user