Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 117 additions & 1 deletion components/src/dynamo/vllm/multimodal_utils/request_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,8 @@ def __init__(
self._mm_kwargs_receiver: Optional[MmKwargsNixlReceiver] = None
self._model_family = resolve_model_family(model)
self._qwen_grid_params: Optional[QwenGridParams] = None
self._k3_expansion: Optional[tuple[int, list[int]]] = None
self._k3_expansion_cached = False

if use_unified_vision_chunk is None:
model_config = getattr(
Expand All @@ -306,6 +308,117 @@ def __init__(
)
self.use_unified_vision_chunk = use_unified_vision_chunk

def _kimi_k3_pad_expansion(self) -> Optional[tuple[int, list[int]]]:
"""Return the structural-pad mapping for Kimi K3.

The native frontend emits one ``<|media_pad|>`` token per image.
vLLM's K3 processor instead matches the checkpoint's
``<|kimi_image_placeholder|>`` sequence, so the adapter converts the
stable vocabulary token into that checkpoint-native sequence.

Successful K3 mappings and definite non-K3 model types are cached.
Incomplete engine metadata is not cached because it may become
available later during startup. Once a model identifies itself as K3,
malformed metadata is an error rather than a silent no-op.
"""
if self._k3_expansion_cached:
return self._k3_expansion

model_config = getattr(
getattr(self.engine_client, "vllm_config", None), "model_config", None
)
hf_config = getattr(model_config, "hf_config", None)
if hf_config is None:
return None

model_type = getattr(hf_config, "model_type", None)
if model_type is None:
return None
if model_type != "kimi_k3":
self._k3_expansion_cached = True
return None

pad_id = getattr(hf_config, "media_placeholder_token_id", None)
if type(pad_id) is not int:
raise ValueError(
"Kimi-K3 requires an integer media_placeholder_token_id in "
"the model config"
)

image_placeholder = getattr(hf_config, "image_placeholder", None)
if not isinstance(image_placeholder, str) or not image_placeholder:
raise ValueError(
"Kimi-K3 requires a non-empty image_placeholder in the model config"
)

tokenizer = self.engine_client.get_tokenizer()
if tokenizer is None:
raise RuntimeError("Kimi-K3 tokenizer is unavailable")
native_ids = list(tokenizer.encode(image_placeholder, add_special_tokens=False))
Comment thread
furionw marked this conversation as resolved.
Resolved
Comment thread
furionw marked this conversation as resolved.
Resolved
if not native_ids or any(type(token_id) is not int for token_id in native_ids):
raise ValueError(
"Kimi-K3 image_placeholder must encode to a non-empty integer "
"token sequence"
)

self._k3_expansion = (pad_id, native_ids)
self._k3_expansion_cached = True
return self._k3_expansion

def _expand_kimi_k3_pads(
self, token_ids: list[int], multi_modal_data: Optional[dict[str, Any]]
) -> list[int]:
"""Replace each K3 structural image pad with its native token sequence."""
if not multi_modal_data:
return token_ids

image_modality = _normalize_forwarded_mm_modality(
"image",
self.use_unified_vision_chunk,
)
images = multi_modal_data.get(image_modality)
if images is None:
return token_ids
expected = len(images) if isinstance(images, (list, tuple)) else 1
if expected == 0:
return token_ids

expansion = self._kimi_k3_pad_expansion()
if expansion is None:
return token_ids
pad_id, native_ids = expansion

# Prompts here can exceed 100k tokens while pads number in the single
# digits. Locate the rare token in C and splice around it instead of
# walking every id in Python.
try:
first = token_ids.index(pad_id)
except ValueError:
return token_ids

pad_positions = [first]
while True:
try:
pad_positions.append(token_ids.index(pad_id, pad_positions[-1] + 1))
except ValueError:
break

if len(pad_positions) != expected:
raise ValueError(
f"Kimi-K3 prompt carries {len(pad_positions)} <|media_pad|> "
f"token(s) but {expected} image(s) were supplied; refusing to "
"expand."
)
Comment thread
furionw marked this conversation as resolved.
Resolved

expanded: list[int] = []
previous = 0
for position in pad_positions:
expanded.extend(token_ids[previous:position])
expanded.extend(native_ids)
previous = position + 1
expanded.extend(token_ids[previous:])
return expanded

@staticmethod
def _multimodal_disabled_error() -> ValueError:
return ValueError(
Expand Down Expand Up @@ -636,7 +749,10 @@ def build_tokens_prompt(
)

prompt_kwargs: dict[str, Any] = {
"prompt_token_ids": request["token_ids"],
"prompt_token_ids": self._expand_kimi_k3_pads(
request["token_ids"],
multi_modal_data,
),
"multi_modal_data": multi_modal_data,
}
if mm_uuids is not None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1067,3 +1067,202 @@ def test_qwen_handoff_accepts_encoder_embeddings():
"image_grid_thw": [[1, 16, 16]],
"embeddings_shape": [1, 256, 1024],
}


# --- Kimi-K3 structural-pad -> checkpoint-native expansion -------------------

_K3_PAD_ID = 163605
_K3_NATIVE_IDS = [27, 91, 74, 30223, 11947, 114136, 91, 29]


def _k3_processor(
*,
model_type: str = "kimi_k3",
unified_vision_chunk: bool = False,
pad_id: object = _K3_PAD_ID,
image_placeholder: object = "<|kimi_image_placeholder|>",
native_ids: object = _K3_NATIVE_IDS,
) -> tuple[mod.VllmMultimodalRequestProcessor, MagicMock]:
tokenizer = SimpleNamespace(
encode=MagicMock(return_value=native_ids),
)
engine_client = SimpleNamespace(
vllm_config=SimpleNamespace(
model_config=SimpleNamespace(
hf_config=SimpleNamespace(
model_type=model_type,
media_placeholder_token_id=pad_id,
image_placeholder=image_placeholder,
use_unified_vision_chunk=unified_vision_chunk,
)
)
),
get_tokenizer=MagicMock(return_value=tokenizer),
)
processor = mod.VllmMultimodalRequestProcessor(
model="moonshotai/Kimi-K3",
engine_client=engine_client,
enable_multimodal=True,
use_unified_vision_chunk=unified_vision_chunk,
)
return processor, engine_client


def test_k3_pad_expands_once_for_scalar_image():
processor, _ = _k3_processor()

result = processor._expand_kimi_k3_pads(
[1, _K3_PAD_ID, 2],
{"image": object()},
)

assert result == [1, *_K3_NATIVE_IDS, 2]


def test_k3_pad_expands_once_per_image():
processor, _ = _k3_processor()

result = processor._expand_kimi_k3_pads(
[_K3_PAD_ID, 7, _K3_PAD_ID],
{"image": [object(), object()]},
)

assert result == [*_K3_NATIVE_IDS, 7, *_K3_NATIVE_IDS]


def test_k3_pad_expands_for_unified_vision_chunk():
processor, _ = _k3_processor(unified_vision_chunk=True)

result = processor._expand_kimi_k3_pads(
[1, _K3_PAD_ID, 2],
{"vision_chunk": object()},
)

assert result == [1, *_K3_NATIVE_IDS, 2]


def test_k3_mismatched_pad_count_is_rejected():
processor, _ = _k3_processor()

with pytest.raises(ValueError, match="refusing to expand"):
processor._expand_kimi_k3_pads(
[_K3_PAD_ID],
{"image": [object(), object()]},
)


def test_k3_already_native_prompt_is_untouched():
processor, _ = _k3_processor()
native_prompt = [1, *_K3_NATIVE_IDS, 2]

result = processor._expand_kimi_k3_pads(
native_prompt,
{"image": object()},
)

assert result is native_prompt


def test_non_k3_model_is_never_rewritten_and_resolution_is_cached():
processor, engine_client = _k3_processor(model_type="qwen3_vl")
tokens = [1, _K3_PAD_ID, 2]

assert processor._expand_kimi_k3_pads(tokens, {"image": object()}) is tokens
assert processor._expand_kimi_k3_pads(tokens, {"image": object()}) is tokens
engine_client.get_tokenizer.assert_not_called()


def test_incomplete_engine_metadata_is_not_cached():
processor, engine_client = _k3_processor()
engine_client.vllm_config.model_config.hf_config = None

assert processor._kimi_k3_pad_expansion() is None

_, ready_engine_client = _k3_processor()
engine_client.vllm_config.model_config.hf_config = (
ready_engine_client.vllm_config.model_config.hf_config
)
assert processor._kimi_k3_pad_expansion() == (_K3_PAD_ID, _K3_NATIVE_IDS)


def test_k3_without_raw_image_media_is_untouched():
processor, engine_client = _k3_processor(pad_id=None)
tokens = [1, _K3_PAD_ID, 2]

assert processor._expand_kimi_k3_pads(tokens, None) is tokens
assert processor._expand_kimi_k3_pads(tokens, {}) is tokens
assert processor._expand_kimi_k3_pads(tokens, {"video": object()}) is tokens
assert processor._expand_kimi_k3_pads(tokens, {"image": []}) is tokens
engine_client.get_tokenizer.assert_not_called()


@pytest.mark.parametrize(
("pad_id", "image_placeholder", "native_ids", "message"),
[
(None, "<|kimi_image_placeholder|>", _K3_NATIVE_IDS, "integer"),
(_K3_PAD_ID, "", _K3_NATIVE_IDS, "non-empty image_placeholder"),
(_K3_PAD_ID, "<|kimi_image_placeholder|>", [], "non-empty integer"),
(_K3_PAD_ID, "<|kimi_image_placeholder|>", ["bad"], "non-empty integer"),
],
)
def test_invalid_k3_metadata_fails_fast(
pad_id: object,
image_placeholder: object,
native_ids: object,
message: str,
):
processor, _ = _k3_processor(
pad_id=pad_id,
image_placeholder=image_placeholder,
native_ids=native_ids,
)

with pytest.raises(ValueError, match=message):
processor._expand_kimi_k3_pads(
[_K3_PAD_ID],
{"image": object()},
)


def test_k3_tokenizer_failure_is_not_cached_or_suppressed():
processor, engine_client = _k3_processor()
engine_client.get_tokenizer.side_effect = RuntimeError("tokenizer failed")

for _ in range(2):
with pytest.raises(RuntimeError, match="tokenizer failed"):
processor._expand_kimi_k3_pads(
[_K3_PAD_ID],
{"image": object()},
)
assert engine_client.get_tokenizer.call_count == 2


def test_k3_successful_mapping_is_cached():
processor, engine_client = _k3_processor()

for _ in range(2):
assert (
processor._expand_kimi_k3_pads(
[_K3_PAD_ID],
{"image": object()},
)
== _K3_NATIVE_IDS
)
engine_client.get_tokenizer.assert_called_once_with()


def test_k3_long_prompt_splices_only_rare_pads():
processor, _ = _k3_processor()
tokens = list(range(100_000))
tokens[10] = _K3_PAD_ID
tokens[-10] = _K3_PAD_ID

result = processor._expand_kimi_k3_pads(
tokens,
{"image": [object(), object()]},
)

assert result[:10] == tokens[:10]
assert result[10 : 10 + len(_K3_NATIVE_IDS)] == _K3_NATIVE_IDS
assert result[-(len(_K3_NATIVE_IDS) + 9) : -9] == _K3_NATIVE_IDS
assert len(result) == len(tokens) + 2 * (len(_K3_NATIVE_IDS) - 1)
Loading