Files
OBLITERATUS/tests/test_tiny_kimi_linear_fixture.py

169 lines
7.7 KiB
Python

"""Independent CPU oracles for the synthetic Kimi Linear fixture."""
import hashlib
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
import torch
import torch.nn.functional as F
from obliteratus.analysis.numerical_contracts import project_weight_against_direction
from obliteratus.phase_admission import _attention_compute_dtypes
from obliteratus.recipes.placement import _resolve_writers
from obliteratus.recipes.validation import RecipeError
from obliteratus.strategies.utils import get_ffn_module, get_layer_modules
from tests.fixtures.tiny_arch_models import kimi_linear_layer_types, tiny_kimi_linear
def digest(model):
h = hashlib.sha256()
for name, value in model.state_dict().items():
h.update(name.encode())
h.update(value.detach().contiguous().numpy().tobytes())
return h.hexdigest()
def route_reference(gate, x):
ids, weights = [], []
for row in x.reshape(-1, x.shape[-1]):
scores = torch.sigmoid(gate.weight @ row)
choice = (scores + gate.e_score_correction_bias).tolist()
width = len(choice) // gate.n_group
groups = [sum(sorted(choice[g * width:(g + 1) * width], reverse=True)[:2])
for g in range(gate.n_group)]
picked = sorted(range(gate.n_group), key=lambda g: groups[g], reverse=True)[:gate.topk_group]
candidates = [i for i in range(len(choice)) if i // width in picked]
selected = sorted(candidates, key=lambda i: choice[i], reverse=True)[:gate.top_k]
w = scores[selected]
ids.append(selected)
weights.append(w / w.sum())
return torch.tensor(ids), torch.stack(weights)
def check_routing(gate, x):
ids, weights = gate(x)
expected_ids, expected_weights = route_reference(gate, x)
assert ids.shape == weights.shape == (x.shape[0] * x.shape[1], gate.top_k)
order, expected_order = ids.argsort(-1), expected_ids.argsort(-1)
torch.testing.assert_close(ids.gather(1, order), expected_ids.gather(1, expected_order))
torch.testing.assert_close(weights.gather(1, order), expected_weights.gather(1, expected_order))
def dense_mlp(m, x, expert=False):
a, b, c = (m.w1, m.w3, m.w2) if expert else (m.gate_proj, m.up_proj, m.down_proj)
return (F.silu(x @ a.weight.T) * (x @ b.weight.T)) @ c.weight.T
def dense_reference(model, x):
for layer in model.model.layers:
a = layer.self_attn
if layer.is_linear_attn:
q, k, v = (x @ p.weight.T for p in (a.q_proj, a.k_proj, a.v_proj))
decay = torch.sigmoid(x @ a.f_a_proj.weight.T @ a.f_b_proj.weight.T
+ a.dt_bias - a.A_log.exp().reshape(()))
beta = torch.sigmoid(x @ a.b_proj.weight.T)
gate = torch.sigmoid(x @ a.g_a_proj.weight.T @ a.g_b_proj.weight.T)
state = torch.zeros_like(x[:, 0])
out = []
for t in range(x.shape[1]):
state = decay[:, t] * state + beta[:, t] * k[:, t] * v[:, t]
out.append(q[:, t] * state * gate[:, t])
attention = torch.stack(out, 1) @ a.o_proj.weight.T
else:
q = x @ a.q_proj.weight.T
kv = (x @ a.kv_a_proj_with_mqa.weight.T)[..., :2] @ a.kv_b_proj.weight.T
attention = (q + kv) @ a.o_proj.weight.T
x = x + attention
if hasattr(layer, 'block_sparse_moe'):
m = layer.block_sparse_moe
ids, weights = route_reference(m.gate, x)
rows = []
for n, row in enumerate(x.reshape(-1, x.shape[-1])):
rows.append(sum(weights[n, j] * dense_mlp(m.experts[i], row, True)
for j, i in enumerate(ids[n].tolist())))
y = torch.stack(rows).reshape_as(x) + dense_mlp(m.shared_experts, x)
else:
y = dense_mlp(layer.mlp, x)
x = x + y
return x
X = torch.tensor([[[0.2, -0.3, 0.5, 0.7], [-0.4, 0.8, 0.1, -0.2]]])
def test_traversal_routing_and_forward(monkeypatch):
model = tiny_kimi_linear()
handle = SimpleNamespace(model=model, architecture='kimi_linear', num_layers=4)
layers = get_layer_modules(handle)
assert layers is model.model.layers
assert [layer.is_linear_attn for layer in layers] == [True, True, True, False]
assert [hasattr(layer, 'block_sparse_moe') for layer in layers] == [False, True, True, True]
weight = layers[0].self_attn.o_proj.weight
monkeypatch.setattr(model, "get_input_embeddings", lambda: SimpleNamespace(weight=weight), raising=False)
config = SimpleNamespace(model_type="kimi_linear", layer_types=["linear_attention"] * 3 + ["full_attention"])
assert _attention_compute_dtypes(handle, config) == [None, None, None, torch.float32]
profile = SimpleNamespace(model_type="kimi_linear", num_layers=4, hidden_size=4)
assert _resolve_writers(model, profile, [3], ["attn_out"], {}) == {
"attn_out": ["model.layers.3.self_attn.o_proj"],
}
assert get_ffn_module(layers[0], "kimi_linear") is layers[0].mlp
with pytest.raises(RecipeError, match="no matching modules"):
_resolve_writers(model, profile, [3], ["experts"], {})
for layer in layers[1:]:
check_routing(layer.block_sparse_moe.gate, X)
torch.testing.assert_close(model(X), dense_reference(model, X), atol=1e-6, rtol=1e-5)
def test_nonzero_router_bias_selects_experts_with_unbiased_fixture_weights():
gate = tiny_kimi_linear().model.layers[1].block_sparse_moe.gate
with torch.no_grad():
gate.weight.zero_()
gate.e_score_correction_bias.copy_(torch.tensor([-0.2, -0.1, 0.1, 0.4]))
ids, weights = gate(X)
torch.testing.assert_close(ids.sort(dim=-1).values, torch.tensor([[2, 3], [2, 3]]))
torch.testing.assert_close(weights, torch.full((2, 2), 0.5))
check_routing(gate, X)
def test_mapping_and_off_by_one():
assert kimi_linear_layer_types(4, [1, 2, 3], [4]) == ('kda', 'kda', 'kda', 'mla')
for kda, mla in [([0, 1, 2], [3]), ([1, 2, 3], [3]), ([1, 2], [4]), ([1, 2, 3], [5])]:
with pytest.raises(ValueError):
kimi_linear_layer_types(4, kda, mla)
with pytest.raises(AssertionError):
assert kimi_linear_layer_types(4, [2, 3, 4], [1]) == ('kda', 'kda', 'kda', 'mla')
def test_writer_projection_wrong_axis():
w = tiny_kimi_linear().model.layers[1].block_sparse_moe.experts[0].w2.weight.detach()
direction = torch.tensor([1., 0., 0., 0.])
expected = w.clone()
expected[0] = 0
torch.testing.assert_close(project_weight_against_direction(w, direction, direction_axis=0).weight, expected)
with pytest.raises((AssertionError, ValueError, RuntimeError)):
wrong = project_weight_against_direction(w, direction, direction_axis=1).weight
torch.testing.assert_close(wrong, expected)
def test_oracle_rejects_malformed_and_missing_shared(monkeypatch):
model = tiny_kimi_linear()
moe = model.model.layers[1].block_sparse_moe
with monkeypatch.context() as patch:
patch.setattr(moe.gate, 'forward', lambda _: (torch.zeros(2, 1, dtype=torch.long), torch.ones(2, 1)))
with pytest.raises(AssertionError):
check_routing(moe.gate, X)
expected = dense_reference(model, X)
with monkeypatch.context() as patch:
patch.setattr(moe.shared_experts, 'forward', lambda x: torch.zeros_like(x))
with pytest.raises(AssertionError):
torch.testing.assert_close(model(X), expected, atol=1e-6, rtol=1e-5)
def test_determinism_and_manifest():
manifest = json.loads((Path(__file__).parent / 'fixtures/kimi_contract_manifest.json').read_text())
assert digest(tiny_kimi_linear()) == manifest['tiny_kimi_linear']['state_dict_sha256']['value']
assert digest(tiny_kimi_linear()) == digest(tiny_kimi_linear())
assert digest(tiny_kimi_linear(128)) != digest(tiny_kimi_linear())