From 71964b3cc3e7c450971fa1c5142958bd3247dde0 Mon Sep 17 00:00:00 2001 From: Martin Vit Date: Fri, 21 Aug 2026 00:09:55 +0000 Subject: [PATCH 1/3] Bound Kimi vision RoPE allocation to input grids Compute MoonViT rotary frequencies only for the image grid sizes present in each request instead of materializing the configured 512x512 ceiling. This reduces the measured first-image CUDA allocation peak from 340,018,176 bytes to 1,990,656 bytes for a 36x36 grid while preserving bit-identical CPU and CUDA output. Co-authored-by: OpenAI Codex Signed-off-by: Martin Vit --- tests/models/kimi_k3/test_vision_warmup.py | 37 +++++++++++++ vllm/model_executor/models/kimi_k25_vit.py | 63 +++++++++++----------- 2 files changed, 67 insertions(+), 33 deletions(-) diff --git a/tests/models/kimi_k3/test_vision_warmup.py b/tests/models/kimi_k3/test_vision_warmup.py index f7e4af39839e..bdd5b88a8f91 100644 --- a/tests/models/kimi_k3/test_vision_warmup.py +++ b/tests/models/kimi_k3/test_vision_warmup.py @@ -13,6 +13,43 @@ ) +def _full_grid_rope_reference( + rope: kimi_k25_vit.Rope2DPosEmbRepeated, + shapes: list[list[int]], +) -> torch.Tensor: + flat_pos = torch.arange(rope.max_height * rope.max_width).float() + x_pos = flat_pos % rope.max_width + y_pos = flat_pos // rope.max_width + dim_range = torch.arange(0, rope.dim, 4).float() + freqs = 1.0 / (rope.theta_base ** (dim_range / rope.dim)) + x_freqs = torch.outer(x_pos, freqs).float() + y_freqs = torch.outer(y_pos, freqs).float() + x_cis = torch.polar(torch.ones_like(x_freqs), x_freqs) + y_cis = torch.polar(torch.ones_like(y_freqs), y_freqs) + table = torch.cat( + [x_cis.unsqueeze(dim=-1), y_cis.unsqueeze(dim=-1)], dim=-1 + ).reshape(rope.max_height, rope.max_width, -1) + return torch.cat( + [table[:h, :w].reshape(-1, rope.dim // 2).repeat(t, 1) for t, h, w in shapes] + ) + + +def test_vision_rope_materializes_only_requested_grids() -> None: + rope = kimi_k25_vit.Rope2DPosEmbRepeated( + dim=32, + max_height=11, + max_width=13, + ) + shapes = [[1, 3, 5], [2, 4, 2], [1, 3, 5]] + + actual = rope.get_freqs_cis(shapes, device=torch.device("cpu")) + expected = _full_grid_rope_reference(rope, shapes) + + assert torch.equal(actual, expected) + assert actual.shape == (46, 16) + assert not hasattr(rope, "freqs_cis") + + def test_warm_vision_position_interpolation(monkeypatch) -> None: model = torch.nn.Sequential( kimi_k25_vit.Learnable2DInterpPosEmbDivided_fixed( diff --git a/vllm/model_executor/models/kimi_k25_vit.py b/vllm/model_executor/models/kimi_k25_vit.py index a3da0fe82a79..f63df30d8772 100644 --- a/vllm/model_executor/models/kimi_k25_vit.py +++ b/vllm/model_executor/models/kimi_k25_vit.py @@ -282,27 +282,28 @@ def extra_repr(self): f"max_width={self.max_width}, theta_base={self.theta_base}" ) - def _precompute_freqs_cis(self, device: torch.device) -> torch.Tensor: - """Calculate the cis(freqs) for each position in the 2D grid.""" - N = self.max_height * self.max_width - flat_pos = torch.arange(0, N).float().to(device) - x_pos = flat_pos % self.max_width - y_pos = flat_pos // self.max_width - dim_range = ( - torch.arange(0, self.dim, 4)[: (self.dim // 4)].float().to(device) - ) # C/4 + def _compute_grid_freqs_cis( + self, height: int, width: int, device: torch.device + ) -> torch.Tensor: + """Calculate rotary frequencies for one requested image grid.""" + x_pos = torch.arange(width, dtype=torch.float32, device=device) + y_pos = torch.arange(height, dtype=torch.float32, device=device) + dim_range = torch.arange(0, self.dim, 4, dtype=torch.float32, device=device)[ + : (self.dim // 4) + ] freqs = 1.0 / (self.theta_base ** (dim_range / self.dim)) - x_freqs = torch.outer(x_pos, freqs).float() # N, C/4 - y_freqs = torch.outer(y_pos, freqs).float() # N, C/4 - x_cis = torch.polar(torch.ones_like(x_freqs), x_freqs) # N, C/4 - y_cis = torch.polar(torch.ones_like(y_freqs), y_freqs) # N, C/4 - # N, C/4, 2 - freqs_cis = torch.cat( - [x_cis.unsqueeze(dim=-1), y_cis.unsqueeze(dim=-1)], dim=-1 - ) - # max_height, max_width, C/2 - freqs_cis = freqs_cis.reshape(self.max_height, self.max_width, -1) - return freqs_cis + x_freqs = torch.outer(x_pos, freqs).float() + y_freqs = torch.outer(y_pos, freqs).float() + x_cis = torch.polar(torch.ones_like(x_freqs), x_freqs) + y_cis = torch.polar(torch.ones_like(y_freqs), y_freqs) + freqs_cis = torch.stack( + ( + x_cis.unsqueeze(0).expand(height, -1, -1), + y_cis.unsqueeze(1).expand(-1, width, -1), + ), + dim=-1, + ) + return freqs_cis.reshape(height * width, self.dim // 2) def get_freqs_cis( self, grid_thws: torch.Tensor | list[list[int]], device: torch.device @@ -314,11 +315,6 @@ def get_freqs_cis( Returns: freqs_cis: tensor of shape (sum(t * height * width), dim//2) """ - if not hasattr(self, "freqs_cis"): - self.register_buffer( - "freqs_cis", self._precompute_freqs_cis(device), persistent=False - ) - shapes = grid_thws if isinstance(grid_thws, list) else grid_thws.tolist() assert all( 1 <= h <= self.max_height and 1 <= w <= self.max_width for t, h, w in shapes @@ -327,14 +323,15 @@ def get_freqs_cis( self.max_height, self.max_width, ) - freqs_cis = torch.cat( - [ - self.freqs_cis[:h, :w].reshape(-1, self.dim // 2).repeat(t, 1) - for t, h, w in shapes - ], - dim=0, - ) - return freqs_cis + grids: dict[tuple[int, int], torch.Tensor] = {} + result = [] + for t, h, w in shapes: + grid = grids.get((h, w)) + if grid is None: + grid = self._compute_grid_freqs_cis(h, w, device) + grids[(h, w)] = grid + result.append(grid.repeat(t, 1)) + return torch.cat(result, dim=0) class MLP2(nn.Module): From 18d9e2789b1939fd4158b2e35ce4340437995a08 Mon Sep 17 00:00:00 2001 From: Martin Vit Date: Fri, 21 Aug 2026 02:05:13 +0000 Subject: [PATCH 2/3] Bound Kimi projector transients per image Project independent Kimi vision features separately so MXFP8/Marlin workspace scales with the largest image instead of the sum of all scheduled images. Preserve output order, shape, activation dtype, and numerical results while reducing the measured TP16 three-image transient peak by 32.52 MiB. Co-authored-by: OpenAI Codex Signed-off-by: Martin Vit --- tests/models/kimi_k3/test_vision_projector.py | 42 +++++++++++++++++-- vllm/model_executor/models/kimi_k25_vit.py | 23 +++++----- 2 files changed, 51 insertions(+), 14 deletions(-) diff --git a/tests/models/kimi_k3/test_vision_projector.py b/tests/models/kimi_k3/test_vision_projector.py index 9f2750809a40..c89c79a3b4ce 100644 --- a/tests/models/kimi_k3/test_vision_projector.py +++ b/tests/models/kimi_k3/test_vision_projector.py @@ -80,11 +80,11 @@ def __init__(self): requires_grad=False, ) self.pre_norm = nn.LayerNorm(4, dtype=torch.bfloat16) - self.input_dtype: torch.dtype | None = None + self.inputs: list[torch.Tensor] = [] def forward(self, inputs: torch.Tensor) -> torch.Tensor: - self.input_dtype = inputs.dtype - return inputs + self.inputs.append(inputs) + return inputs + len(self.inputs) def test_kimi_projector_uses_norm_activation_dtype_for_fp8_weights(): @@ -95,9 +95,43 @@ def test_kimi_projector_uses_norm_activation_dtype_for_fp8_weights(): [torch.randn(2, 4), torch.randn(1, 4)], ) - assert projector.input_dtype == torch.bfloat16 + assert len(projector.inputs) == 2 + assert [inputs.shape for inputs in projector.inputs] == [(2, 4), (1, 4)] + assert all(inputs.dtype == torch.bfloat16 for inputs in projector.inputs) assert [output.shape for output in outputs] == [(2, 4), (1, 4)] assert all(output.dtype == torch.bfloat16 for output in outputs) + assert torch.equal(outputs[0], projector.inputs[0] + 1) + assert torch.equal(outputs[1], projector.inputs[1] + 2) + + +def test_kimi_projector_rejects_empty_vision_output(): + with pytest.raises( + ValueError, match="Kimi vision projection requires at least one image feature" + ): + mm_projector_forward(_SerializedFp8Projector(), []) + + +class _DeterministicProjector(nn.Module): + def __init__(self): + super().__init__() + self.pre_norm = nn.LayerNorm(4) + self.linear = nn.Linear(4, 3, bias=False) + + def forward(self, inputs: torch.Tensor) -> torch.Tensor: + return self.linear(self.pre_norm(inputs)) + + +def test_kimi_projector_preserves_batched_projection_results(): + torch.manual_seed(1) + projector = _DeterministicProjector() + inputs = [torch.randn(2, 4), torch.randn(3, 4)] + expected = torch.split(projector(torch.cat(inputs)), [2, 3]) + + outputs = mm_projector_forward(projector, inputs) + + assert len(outputs) == len(expected) + for output, reference in zip(outputs, expected): + torch.testing.assert_close(output, reference) def test_kimi_vision_rope_reuses_packed_qk_buffers(): diff --git a/vllm/model_executor/models/kimi_k25_vit.py b/vllm/model_executor/models/kimi_k25_vit.py index f63df30d8772..6c0bbd1deb33 100644 --- a/vllm/model_executor/models/kimi_k25_vit.py +++ b/vllm/model_executor/models/kimi_k25_vit.py @@ -840,21 +840,24 @@ def prepare_encoder_cudagraph_metadata( @torch.inference_mode() def mm_projector_forward(mm_projector: torch.nn.Module, vt_output: list[torch.Tensor]): - """Apply MM projector to vision tower outputs.""" - num_embedding_list = [x.shape[0] for x in vt_output] - batched = torch.cat(vt_output, dim=0) + """Apply the projector without concatenating independent image features.""" + if not vt_output: + raise ValueError("Kimi vision projection requires at least one image feature") + projector_norm = getattr(mm_projector, "pre_norm", None) if projector_norm is None: projector_norm = getattr(mm_projector, "post_norm", None) projector_dtype = ( - projector_norm.weight.dtype if projector_norm is not None else batched.dtype + projector_norm.weight.dtype if projector_norm is not None else None ) - if batched.dtype != projector_dtype: - batched = batched.to(projector_dtype) - proj_out = mm_projector(batched) - proj_out = proj_out.reshape(-1, proj_out.shape[-1]) - proj_out = torch.split(proj_out, num_embedding_list) - return proj_out + + projected = [] + for image_features in vt_output: + if projector_dtype is not None and image_features.dtype != projector_dtype: + image_features = image_features.to(projector_dtype) + output = mm_projector(image_features) + projected.append(output.reshape(-1, output.shape[-1])) + return tuple(projected) @torch.inference_mode() From 78f81231ae4085e31cffbc4c89021131f4c3629b Mon Sep 17 00:00:00 2001 From: Martin Vit Date: Fri, 18 Sep 2026 13:32:11 +0000 Subject: [PATCH 3/3] Bound Kimi vision RoPE product memory Rotate the disposable FP32 query and key conversion buffers in place before copying the result back into packed BF16 QKV storage. This removes the second full-size FP32 product tensor while preserving bit-identical BF16 output and storage identity. Co-authored-by: OpenAI Codex Signed-off-by: Martin Vit --- vllm/model_executor/models/kimi_k25_vit.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/vllm/model_executor/models/kimi_k25_vit.py b/vllm/model_executor/models/kimi_k25_vit.py index 6c0bbd1deb33..bd881aaa5b52 100644 --- a/vllm/model_executor/models/kimi_k25_vit.py +++ b/vllm/model_executor/models/kimi_k25_vit.py @@ -93,14 +93,17 @@ def apply_rope( # Q and K are non-overlapping views of the packed QKV projection. Their # unrotated values are dead after this call, so reuse those BF16 buffers - # instead of retaining two additional full-size outputs. Processing Q and - # K sequentially also permits the allocator to reuse the FP32 temporary. + # instead of retaining two additional full-size outputs. Rotate each + # FP32/complex conversion buffer in place so the multiplication does not + # materialize a second full-size FP32 tensor. xq_complex = torch.view_as_complex(xq.float().view(*xq.shape[:-1], -1, 2)) - xq.copy_(torch.view_as_real(xq_complex * freqs_cis).flatten(-2)) + xq_complex.mul_(freqs_cis) + xq.copy_(torch.view_as_real(xq_complex).flatten(-2)) del xq_complex xk_complex = torch.view_as_complex(xk.float().view(*xk.shape[:-1], -1, 2)) - xk.copy_(torch.view_as_real(xk_complex * freqs_cis).flatten(-2)) + xk_complex.mul_(freqs_cis) + xk.copy_(torch.view_as_real(xk_complex).flatten(-2)) return xq, xk