code-switch-mtp / tests /test_phase5_dependent.py
Anupam-Rawat-IITB's picture
Refresh to the current main: code, results, logs and the final deck (part 3)
3ef3d94 verified
Raw History Blame Contribute Delete
8.07 kB
"""Dependent draft heads: initial equivalence, shapes, information flow, loss weighting."""
import torch
import torch.nn as nn
from src.train.dependent import DependentStack, PrefixFeatureStack, acceptance_weights, mtp_step, teacher_forced_logits
from src.train.model import MTPStack
HIDDEN, VOCAB, HEADS = 16, 50, 4
def _stacks():
torch.manual_seed(0)
unembed = nn.Linear(HIDDEN, VOCAB, bias=False)
embed = nn.Embedding(VOCAB, HIDDEN)
for q in list(unembed.parameters()) + list(embed.parameters()):
q.requires_grad = False
return MTPStack(HIDDEN, unembed, HEADS, True), DependentStack(HIDDEN, unembed, HEADS, embed, 2.0), embed
def test_zero_init_matches_independent_stack():
ind, dep, _ = _stacks()
hidden = torch.randn(2, 12, HIDDEN)
block = torch.randint(0, VOCAB, (2, 12))
for k in range(HEADS):
a = teacher_forced_logits(ind, ind.trunk_states(hidden), block, k)
b = teacher_forced_logits(dep, dep.trunk_states(hidden), block, k)
assert a.shape == (2, 12 - k - 1, VOCAB)
assert torch.equal(a, b)
def test_head_reads_only_its_predecessor_tokens():
_, dep, _ = _stacks()
for group in dep.proj:
for lin in group:
nn.init.normal_(lin.weight, std=0.1)
hidden = torch.randn(1, 12, HIDDEN)
block = torch.randint(0, VOCAB, (1, 12))
trunk = dep.trunk_states(hidden)
k = 2 # predicts offset 3 from offsets 1 and 2
base = teacher_forced_logits(dep, trunk, block, k)
changed = block.clone()
changed[0, 5] = (changed[0, 5] + 1) % VOCAB
out = teacher_forced_logits(dep, trunk, changed, k)
differs = (out != base).any(-1)[0]
# token 5 is offset 1 for position 4 and offset 2 for position 3; no other position reads it
assert differs.nonzero().flatten().tolist() == [3, 4]
# the target itself (offset 3, i.e. position 2 for token 5) never leaks in
assert not differs[2]
def test_head_one_has_no_dependence():
_, dep, _ = _stacks()
hidden = torch.randn(1, 8, HIDDEN)
trunk = dep.trunk_states(hidden)
assert torch.equal(dep.dependent_logits(trunk, 0, []), dep.head_logits(trunk, 0))
def test_frozen_modules_are_not_trainable_or_saved():
_, dep, embed = _stacks()
ids = {id(q) for q in dep.trainable_parameters()}
assert id(embed.weight) not in ids
assert not any("_frozen" in k for k in dep.state_dict())
assert len(list(dep.proj.parameters())) == 1 + 2 + 3
def test_acceptance_weights_mean_one_and_monotone():
log_reach = torch.log(torch.tensor([[0.9, 0.5, 0.1, 0.5]]))
w = acceptance_weights(log_reach)
assert abs(float(w.mean()) - 1.0) < 1e-6
assert w[0, 0] > w[0, 1] > w[0, 2]
def test_step_updates_projections_and_reports_counts():
_, dep, _ = _stacks()
opt = torch.optim.AdamW(dep.trainable_parameters(), lr=1e-2)
hidden = torch.randn(2, 12, HIDDEN)
block = torch.randint(0, VOCAB, (2, 12))
for weighted in (False, True):
losses, correct, counts = mtp_step(dep, opt, hidden, block, 0.1, weighted)
assert len(losses) == HEADS and counts == [2 * (12 - k - 1) for k in range(HEADS)]
assert all(float(lin.weight.abs().sum()) > 0 for group in dep.proj for lin in group)
def test_backbone_choice_replaces_lookahead_targets_only():
_, dep, _ = _stacks()
opt = torch.optim.SGD(dep.trainable_parameters(), lr=0.0)
hidden = torch.randn(2, 12, HIDDEN)
block = torch.randint(0, VOCAB, (2, 12))
choice = torch.randint(0, VOCAB, (2, 12))
plain, _, _ = mtp_step(dep, opt, hidden, block, 0.1, False)
taught, _, counts = mtp_step(dep, opt, hidden, block, 0.1, False, choice)
assert taught[0] == plain[0] # head 1 keeps the text target
assert all(taught[k] != plain[k] for k in range(1, HEADS))
assert counts == [2 * (12 - k - 1) for k in range(HEADS)]
# choice[:, j] is the backbone's token for position j + 1, so shifting it by one reproduces the text targets
shifted = torch.cat([block[:, 1:], block[:, :1]], dim=1)
same, _, _ = mtp_step(dep, opt, hidden, block, 0.1, False, shifted)
assert same == plain
def _update(dep, hidden, block, weights):
"""Parameter change of the last head's block after one SGD step with the given target weights."""
before = [q.detach().clone() for q in dep.trainable_parameters()]
opt = torch.optim.SGD(dep.trainable_parameters(), lr=0.1)
mtp_step(dep, opt, hidden, block, 0.1, False, None, weights)
after = [q.detach().clone() for q in dep.trainable_parameters()]
for q, b in zip(dep.trainable_parameters(), before):
q.data.copy_(b)
return torch.cat([(a - b).flatten() for a, b in zip(after, before)])
def test_target_weights_reweight_lookahead_losses_only():
_, dep, _ = _stacks()
hidden = torch.randn(2, 12, HIDDEN)
block = torch.randint(0, VOCAB, (2, 12))
plain = _update(dep, hidden, block, None)
uniform = _update(dep, hidden, block, torch.full((2, 12), 3.0))
assert torch.allclose(plain, uniform, atol=1e-6) # weighted mean: a constant weight changes nothing
weights = torch.ones(2, 12)
weights[:, 6:] = 0.0
masked = _update(dep, hidden, block, weights)
assert not torch.allclose(plain, masked, atol=1e-6)
# head 1 is never weighted: zero weight everywhere on look-ahead targets still trains on the next-token loss
hidden2 = hidden.clone()
only_next = _update(dep, hidden2, block, torch.cat([torch.ones(2, 2), torch.zeros(2, 10)], 1))
assert only_next.abs().sum() > 0
def _prefix_stack():
torch.manual_seed(0)
unembed = nn.Linear(HIDDEN, VOCAB, bias=False)
embed = nn.Embedding(VOCAB, HIDDEN)
for q in list(unembed.parameters()) + list(embed.parameters()):
q.requires_grad = False
ids = torch.arange(VOCAB)
stack = PrefixFeatureStack(HIDDEN, unembed, HEADS, embed, 2.0, ids % 3 == 0, ids % 3, ids % 7 == 0)
return stack, DependentStack(HIDDEN, unembed, HEADS, embed, 2.0)
def test_prefix_features_start_as_plain_dependent_stack():
pf, dep = _prefix_stack()
dep.load_state_dict({k: v for k, v in pf.state_dict().items() if k in dep.state_dict()})
for stack in (pf, dep):
for group in stack.proj:
for lin in group:
nn.init.constant_(lin.weight, 0.01)
hidden = torch.randn(2, 12, HIDDEN)
block = torch.randint(0, VOCAB, (2, 12))
for k in range(HEADS):
assert torch.equal(teacher_forced_logits(pf, pf.trunk_states(hidden), block, k), teacher_forced_logits(dep, dep.trunk_states(hidden), block, k))
def test_prefix_features_same_in_training_and_drafting():
pf, _ = _prefix_stack()
block = torch.randint(0, VOCAB, (3, 20))
since = pf.tokens_since_word_start(block)
for row in range(3): # the vectorised count equals a plain loop
count = 0
for i, t in enumerate(block[row].tolist()):
count = 0 if t % 3 == 0 else count + 1
assert since[row, i] == (count if any(x % 3 == 0 for x in block[row, : i + 1].tolist()) else i + 1)
for k in range(1, HEADS):
n = block.shape[1] - (k + 1)
prev = [block[:, i + 1 : i + 1 + n] for i in range(k)]
feats = pf.prefix_features(since[:, :n], prev) # carried forward from the context, as when drafting
last = block[:, k : k + n] # the token the prefix ends at, read directly off the sequence
assert torch.equal(feats[..., :4].argmax(-1), since[:, k : k + n].clamp(max=3))
assert torch.equal(feats[..., 4:7].argmax(-1), last % 3)
assert torch.equal(feats[..., 7].bool(), last % 7 == 0)
def test_prefix_feature_weights_train_and_change_logits():
pf, _ = _prefix_stack()
opt = torch.optim.SGD(pf.trainable_parameters(), lr=0.5)
hidden = torch.randn(2, 12, HIDDEN)
block = torch.randint(0, VOCAB, (2, 12))
mtp_step(pf, opt, hidden, block, 0.1, False)
mtp_step(pf, opt, hidden, block, 0.1, False)
assert all(float(lin.weight.abs().sum()) > 0 for lin in pf.feat_proj)
assert "feat_proj.0.weight" in pf.state_dict() and "tok_script" in pf.state_dict()