|
| 1 | +"""Vision sink semantics and BF16 compatibility, independent of model weights.""" |
| 2 | +import math |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import pytest |
| 6 | + |
| 7 | +mx = pytest.importorskip("mlx.core") |
| 8 | + |
| 9 | +from jang_tools.mimo_v2.v26_omni import MiMoV26Omni |
| 10 | +from jang_tools.mimo_v2.v26_vision import MiMoV26VisionAttention, MiMoV26VisionConfig |
| 11 | + |
| 12 | + |
| 13 | +@pytest.mark.parametrize("dtype", [mx.float32, mx.bfloat16]) |
| 14 | +@pytest.mark.parametrize("length,window", [(3, 64), (7, 1)]) |
| 15 | +def test_virtual_sink_is_extra_denominator_logit(dtype, length, window): |
| 16 | + cfg = MiMoV26VisionConfig(hidden_size=64, num_heads=1, |
| 17 | + num_key_value_heads=1, visual_token_window_size=window) |
| 18 | + attn = MiMoV26VisionAttention(cfg, use_sink=True) |
| 19 | + attn.sink_mode = "virtual" |
| 20 | + attn.sinks = mx.array([math.log(2)], dtype=dtype) |
| 21 | + q = mx.zeros((1, 1, length, 64), dtype=dtype) |
| 22 | + v = mx.ones_like(q) |
| 23 | + result = np.array(attn._attend(q, q, v, full_attn=False).astype(mx.float32)) |
| 24 | + # Zero q/k gives unit mass to each visible key; the sink contributes |
| 25 | + # exp(log(2)) = 2 to the denominator and zero to the numerator. |
| 26 | + count = np.array([sum(abs(i-j) <= window for j in range(length)) |
| 27 | + for i in range(length)], dtype=np.float32) |
| 28 | + expected = count / (count + 2) |
| 29 | + np.testing.assert_allclose(result[0, 0, :, 0], expected, atol=0.004, rtol=0) |
| 30 | + # A key-0 bias with all-one values would incorrectly return all ones. |
| 31 | + assert float(result.max()) < 0.9 |
| 32 | + |
| 33 | + |
| 34 | +def test_serving_wrapper_selects_virtual_sink_before_loading(monkeypatch, tmp_path): |
| 35 | + from jang_tools.mimo_v2 import v26_omni as omni |
| 36 | + |
| 37 | + calls = [] |
| 38 | + |
| 39 | + class Tower: |
| 40 | + def __init__(self, cfg, merger_norm): |
| 41 | + pass |
| 42 | + |
| 43 | + def set_sink_mode(self, mode): |
| 44 | + calls.append(("sink", mode)) |
| 45 | + |
| 46 | + def load_source_weights(self, weights, dtype): |
| 47 | + calls.append(("load", weights)) |
| 48 | + |
| 49 | + monkeypatch.setattr(omni.V.MiMoV26VisionConfig, "from_model_dir", lambda _: None) |
| 50 | + monkeypatch.setattr(omni.V.MiMoV26VisionProcessor, "from_model_dir", lambda _: None) |
| 51 | + monkeypatch.setattr(omni.V, "MiMoVisionTower", Tower) |
| 52 | + monkeypatch.setattr(omni.V, "load_visual_weights_from_source", lambda _: "weights") |
| 53 | + wrapper = MiMoV26Omni(tmp_path, None, None) |
| 54 | + wrapper.vision() |
| 55 | + assert calls == [("sink", "virtual"), ("load", "weights")] |
| 56 | + wrapper.vision() |
| 57 | + assert len(calls) == 2 |
0 commit comments