Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
42 changes: 38 additions & 4 deletions tests/models/kimi_k3/test_vision_projector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand All @@ -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():
Expand Down
37 changes: 37 additions & 0 deletions tests/models/kimi_k3/test_vision_warmup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
86 changes: 43 additions & 43 deletions vllm/model_executor/models/kimi_k25_vit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -843,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()
Expand Down
Loading