lorapop / code /tests /test_bank.py
bryan7264's picture
Add files using upload-large-folder tool
a4054b7 verified
Raw History Blame Contribute Delete
2.13 kB
# MIT License, Bryan Cheng, 2026.
"""Bank mode (one update per batch row) must equal single-update mode. Tiny random Qwen2 model, CPU, float32."""
import os
import sys
import torch
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from src.lorapop.deltas import clear, patch_model, set_bank, set_rows, set_updates # noqa: E402
def test_bank_equals_single():
from transformers import Qwen2Config, Qwen2ForCausalLM
torch.manual_seed(0)
cfg = Qwen2Config(vocab_size=300, hidden_size=64, intermediate_size=128, num_hidden_layers=2,
num_attention_heads=4, num_key_value_heads=2, max_position_embeddings=128)
model = Qwen2ForCausalLM(cfg).eval()
table = patch_model(model)
ups = []
for b in range(3):
u = {}
for k, w in table.items():
if (b == 1 and "down" in k) or b == 2:
continue # background 2 = base (no update); background 1 lacks down_proj
p, q = w.lin.weight.shape
r = 2 + b
u[k] = [(torch.randn(r, q) * 0.1, torch.randn(p, r) * 0.1, 1.0)]
ups.append(u)
x = torch.randint(0, 300, (6, 9))
owners = [0, 1, 2, 1, 0, 2]
with torch.no_grad():
set_bank(table, ups, dtype=torch.float32, device="cpu")
set_rows(owners, "cpu")
yb = model(input_ids=x).logits
clear(table)
for i, b in enumerate(owners):
set_updates(table, ups[b], dtype=torch.float32, device="cpu")
ys = model(input_ids=x[i:i + 1]).logits
assert torch.allclose(yb[i:i + 1], ys, atol=1e-4), (i, b)
clear(table)
def test_single_background_still_sets_row_owners():
"""Regression: with nb == 1 the battery must still route rows to bank entry 0 (else the update is skipped)."""
import types
from src.lorapop.battery import Battery
lst, owners = Battery._rep(types.SimpleNamespace(nb=1), ["a", "b", "c"])
assert lst == ["a", "b", "c"] and owners == [0, 0, 0]
lst2, owners2 = Battery._rep(types.SimpleNamespace(nb=2), ["a", "b"])
assert lst2 == ["a", "b", "a", "b"] and owners2 == [0, 0, 1, 1]