Skip to content

Commit d1d0a34

Browse files
justinchubyCopilot
andcommitted
fix: harden projector spatial and QKV contracts
Match Step3VL antialiased position downsampling at image edges, validate every source Q/K/V tensor before fusion, and require Nemotron's exact 2x projector scale. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 59053cd commit d1d0a34

4 files changed

Lines changed: 117 additions & 18 deletions

File tree

‎src/mobius/components/_hunyuan_step_vision.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,7 @@ def _resize_positions(
466466
mode="linear",
467467
coordinate_transformation_mode="half_pixel",
468468
antialias=1,
469+
exclude_outside=1,
469470
)
470471
positions = op.Transpose(positions, perm=[0, 2, 3, 1])
471472
return op.Reshape(

‎src/mobius/components/_hunyuan_step_vision_test.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,3 +397,52 @@ def test_step3vl_runtime_grid_controls_position_resize_and_downsampling():
397397
},
398398
)[0]
399399
assert actual.shape == (1, math.ceil(h / 4) * math.ceil(w / 4), 3)
400+
401+
402+
def test_step3vl_position_resize_matches_torch_antialias_up_and_down():
403+
class _PositionResizeProbe(Step3VLClipSidecar):
404+
def forward(self, op, pixel_values, pos_h, pos_w):
405+
del pixel_values, pos_h, pos_w
406+
return self._resize_positions(
407+
op,
408+
op.Constant(value_int=target_size),
409+
op.Constant(value_int=target_size),
410+
)
411+
412+
for source_size, target_size in ((2, 4), (4, 2)):
413+
component = _PositionResizeProbe(
414+
vision_hidden_size=4,
415+
intermediate_size=4,
416+
num_heads=1,
417+
num_layers=0,
418+
patch_size=1,
419+
grid_height=4,
420+
grid_width=4,
421+
position_grid_size=source_size,
422+
downsample_hidden_size=4,
423+
output_size=3,
424+
)
425+
_, op, graph = create_test_builder()
426+
unused = op.Constant(value_float=0.0)
427+
output = component(op, unused, unused, unused)
428+
output.name = "positions"
429+
graph.outputs.append(output)
430+
state, session = _state_and_session(component, graph, 47 + source_size)
431+
432+
source = torch.from_numpy(state["position_embedding"]).reshape(
433+
1, source_size, source_size, 4
434+
)
435+
expected = functional.interpolate(
436+
source.permute(0, 3, 1, 2),
437+
size=(target_size, target_size),
438+
mode="bilinear",
439+
align_corners=False,
440+
antialias=True,
441+
).permute(0, 2, 3, 1)
442+
actual = session.run(None, {})[0]
443+
np.testing.assert_allclose(
444+
actual,
445+
expected.reshape(1, target_size * target_size, 4).numpy(),
446+
rtol=1e-6,
447+
atol=1e-6,
448+
)

‎src/mobius/integrations/gguf/_remaining_projectors.py‎

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,11 @@ def _create_cog(metadata: Mapping[str, object], shapes: TensorShapes) -> nn.Modu
393393
def _create_nemotron(metadata: Mapping[str, object], shapes: TensorShapes) -> nn.Module:
394394
image = _metadata_int(metadata, "clip.vision.image_size")
395395
patch = _metadata_int(metadata, "clip.vision.patch_size")
396+
scale = _metadata_int(metadata, "clip.vision.projector.scale_factor")
397+
if scale != 2:
398+
raise ValueError(
399+
f"nemotron_v2_vl clip.vision.projector.scale_factor must be 2, got {scale}."
400+
)
396401
registers = _shape(shapes, "v.class_embd", 2)[0]
397402
first = _shape(shapes, "mm.model.mlp.1.weight", 2)
398403
output = _shape(shapes, "mm.model.mlp.3.weight", 2)[0]
@@ -986,37 +991,39 @@ def map_remaining_projector_weight(name: str, projector_type: str) -> str | None
986991
return None if local is None else f"vision_encoder.{local}"
987992

988993

989-
def _fused_hunyuan_state(mmproj_gguf: Any) -> tuple[dict[str, torch.Tensor], set[str]]:
994+
def _fused_qkv_state(
995+
mmproj_gguf: Any,
996+
target_stem: str,
997+
) -> tuple[dict[str, torch.Tensor], set[str]]:
990998
state: dict[str, torch.Tensor] = {}
991999
consumed: set[str] = set()
9921000
layers = _metadata_int(mmproj_gguf.metadata, "clip.vision.block_count")
1001+
hidden_size = _metadata_int(mmproj_gguf.metadata, "clip.vision.embedding_length")
9931002
for layer in range(layers):
9941003
for kind in ("weight", "bias"):
9951004
names = [f"v.blk.{layer}.attn_{part}.{kind}" for part in ("q", "k", "v")]
9961005
values = [
9971006
np.asarray(mmproj_gguf.get_tensor(name), dtype=np.float32) for name in names
9981007
]
999-
state[f"vision_encoder.layers.{layer}.attn.in_proj.{kind}"] = torch.from_numpy(
1000-
np.concatenate(values, axis=0).copy()
1001-
)
1008+
expected_shape = (hidden_size, hidden_size) if kind == "weight" else (hidden_size,)
1009+
for name, value in zip(names, values):
1010+
if value.shape != expected_shape:
1011+
raise ValueError(
1012+
f"{name} has shape {value.shape}, expected {expected_shape} "
1013+
"before QKV fusion."
1014+
)
1015+
target = f"vision_encoder.{target_stem.format(layer=layer)}.{kind}"
1016+
state[target] = torch.from_numpy(np.concatenate(values, axis=0).copy())
10021017
consumed.update(names)
10031018
return state, consumed
10041019

10051020

1021+
def _fused_hunyuan_state(mmproj_gguf: Any) -> tuple[dict[str, torch.Tensor], set[str]]:
1022+
return _fused_qkv_state(mmproj_gguf, "layers.{layer}.attn.in_proj")
1023+
1024+
10061025
def _fused_cog_state(mmproj_gguf: Any) -> tuple[dict[str, torch.Tensor], set[str]]:
1007-
state: dict[str, torch.Tensor] = {}
1008-
consumed: set[str] = set()
1009-
layers = _metadata_int(mmproj_gguf.metadata, "clip.vision.block_count")
1010-
for layer in range(layers):
1011-
for kind in ("weight", "bias"):
1012-
names = [f"v.blk.{layer}.attn_{part}.{kind}" for part in ("q", "k", "v")]
1013-
values = [
1014-
np.asarray(mmproj_gguf.get_tensor(name), dtype=np.float32) for name in names
1015-
]
1016-
target = f"vision_encoder.blocks.{layer}.attention.qkv.{kind}"
1017-
state[target] = torch.from_numpy(np.concatenate(values, axis=0).copy())
1018-
consumed.update(names)
1019-
return state, consumed
1026+
return _fused_qkv_state(mmproj_gguf, "blocks.{layer}.attention.qkv")
10201027

10211028

10221029
def remaining_projector_state_dict(mmproj_gguf: Any, projector_type: str) -> dict:

‎src/mobius/integrations/gguf/_remaining_projectors_test.py‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,10 @@ def test_production_patch_weight_mapping_preserves_values(
282282
class _Reader:
283283
def __init__(self) -> None:
284284
self.tensor_names = (source_name,)
285-
self.metadata = {"clip.vision.block_count": 1}
285+
self.metadata = {
286+
"clip.vision.block_count": 1,
287+
"clip.vision.embedding_length": 2,
288+
}
286289

287290
def get_tensor(self, name: str) -> np.ndarray:
288291
if name == source_name:
@@ -312,6 +315,45 @@ def test_minicpm_rejects_unknown_projector_scale() -> None:
312315
)
313316

314317

318+
@pytest.mark.parametrize("projector_type", ["hunyuanvl", "cogvlm"])
319+
def test_fused_qkv_rejects_compensating_source_row_shapes(projector_type: str) -> None:
320+
names = tuple(
321+
f"v.blk.0.attn_{part}.{kind}"
322+
for kind in ("weight", "bias")
323+
for part in ("q", "k", "v")
324+
)
325+
326+
class _Reader:
327+
def __init__(self) -> None:
328+
self.tensor_names = names
329+
self.metadata = {
330+
"clip.vision.block_count": 1,
331+
"clip.vision.embedding_length": 2,
332+
}
333+
334+
@staticmethod
335+
def get_tensor(name: str) -> np.ndarray:
336+
if name.endswith(".bias"):
337+
return np.zeros((2,), dtype=np.float32)
338+
rows = {"attn_q": 3, "attn_k": 1, "attn_v": 2}
339+
stem = next(key for key in rows if key in name)
340+
return np.zeros((rows[stem], 2), dtype=np.float32)
341+
342+
with pytest.raises(ValueError, match=r"attn_q\.weight.*expected"):
343+
remaining_projector_state_dict(_Reader(), projector_type)
344+
345+
346+
@pytest.mark.parametrize("scale", [4, 2.0, True])
347+
def test_nemotron_rejects_non_exact_merge_scale(scale: object) -> None:
348+
metadata = {
349+
"clip.vision.image_size": 4,
350+
"clip.vision.patch_size": 2,
351+
"clip.vision.projector.scale_factor": scale,
352+
}
353+
with pytest.raises(ValueError, match=r"clip\.vision\.projector\.scale_factor"):
354+
create_remaining_vision_projector("nemotron_v2_vl", metadata, {})
355+
356+
315357
def test_meralion_factory_and_mapping_preserve_stack_before_norm_contract() -> None:
316358
metadata = {
317359
"clip.audio.embedding_length": 4,

0 commit comments

Comments
 (0)