code-switch-mtp / tests /test_phase4_boundaries.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
8.63 kB
"""Tests for the Phase 4 boundary analyses: target alignment and the offline draft/verify replay.
Off-by-one errors are the main risk in both scripts: predictor k at
position p targets token p + k, and a draft read at round offset j
predicts continuation[j + 1 + i]. Each test pins one alignment on a
hand-checked example.
"""
import sys
from pathlib import Path
import torch
import torch.nn as nn
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from scripts.phase4_boundary_decoding import accepted_count, policy_length, simulate_doc
from scripts.phase4_gradient_conflict import pair_masks, per_position_grads
from src.train.model import MTPStack
HIDDEN, VOCAB = 8, 16
def _stack(n_heads: int = 4) -> MTPStack:
torch.manual_seed(0)
unemb = nn.Linear(HIDDEN, VOCAB, bias=False)
for p in unemb.parameters():
p.requires_grad = False
stack = MTPStack(HIDDEN, unemb, n_heads, use_shared_trunk=True)
for head in stack.heads: # non-zero heads so every gradient row is informative
nn.init.normal_(head.resblock.linear.weight, std=0.5)
return stack
def test_pair_masks_on_hand_checked_example():
# tokens: 0 1 2 3 4 5 6 ; words start at tokens 0 and 4
starts = [True, False, False, False, True, False, False]
next_starts, crosses = pair_masks(starts, 3)
# positions p = 0..3; next token is p+1, predictor 3 targets p+3
assert next_starts == [False, False, False, True]
# a word starts within tokens p+2..p+3: p=1 (token 4) and p=2 (token 4), not p=0 or p=3
assert crosses == [False, True, True, False]
def test_pair_masks_k2_only_checks_the_token_after_next():
starts = [True, False, True, False, True]
next_starts, crosses = pair_masks(starts, 2)
assert next_starts == [False, True, False]
assert crosses == [True, False, True]
def test_predictor_k_gradient_rows_stop_k_before_the_end():
"""Row p of predictor k's gradient is non-zero exactly when token p+k exists."""
stack = _stack()
seq = 9
block = torch.randint(0, VOCAB, (1, seq))
leaf = torch.randn(1, seq, HIDDEN, requires_grad=True)
grads = per_position_grads(stack, leaf, block)
for k in range(1, 5):
row_norms = grads[k].norm(dim=-1)
assert torch.all(row_norms[: seq - k] > 0), f"predictor {k} lost a valid position"
assert torch.all(row_norms[seq - k :] == 0), f"predictor {k} has a gradient without a target"
def test_predictor_k_gradient_targets_token_p_plus_k():
"""Changing token p+k changes predictor k's gradient at p and nowhere else."""
stack = _stack()
seq, k, p = 10, 3, 4
block = torch.randint(0, VOCAB, (1, seq))
leaf = torch.randn(1, seq, HIDDEN, requires_grad=True)
before = per_position_grads(stack, leaf, block)[k]
altered = block.clone()
altered[0, p + k] = (altered[0, p + k] + 1) % VOCAB
after = per_position_grads(stack, leaf, altered)[k]
changed = (before - after).norm(dim=-1) > 0
assert changed.tolist() == [i == p for i in range(seq)]
def test_policy_lengths():
flags = [True, False, True, False] # first predicted word start after draft 0 is draft 2
assert policy_length("fixed4", flags) == 4
assert policy_length("fixed2", flags) == 2
assert policy_length("gate_before", flags) == 2 # drafts 0, 1
assert policy_length("gate_after", flags) == 3 # drafts 0, 1, 2
assert policy_length("gate_before", [True, False, False, False]) == 4 # no later word start
assert policy_length("random_matched", flags, sampled_length=1) == 1
def test_accepted_count_reads_the_token_after_the_round_start():
continuation = [100, 1, 2, 3, 4, 5, 6] # continuation[0] is the last committed token
assert accepted_count([1, 2, 3, 9], continuation, 0, 4) == 3
assert accepted_count([1, 2, 3, 9], continuation, 0, 2) == 2 # cannot exceed the submitted length
assert accepted_count([3, 4, 9, 9], continuation, 2, 4) == 2
assert accepted_count([9, 2, 3, 4], continuation, 0, 4) == 0
def test_simulate_doc_commits_accepted_plus_one_and_scores_the_next_round():
# continuation: offset 0 is the last prompt token, then tokens 1..9
continuation = [100, 1, 2, 3, 4, 5, 6, 7, 8, 9]
token_starts = [False, True, False, False, True, False, True, False, False, True]
perfect = [[j + 1 + i for i in range(4)] for j in range(len(continuation))]
starts = [[token_starts[j + 1 + i] if j + 1 + i < len(token_starts) else False for i in range(4)] for j in range(len(continuation))]
rounds = simulate_doc(perfect, starts, continuation, token_starts, horizon=4, policy="fixed4")
# perfect drafts: one round commits 4 drafts + the backbone's own token
assert len(rounds) == 1
assert rounds[0]["n_acc"] == 4 and rounds[0]["committed"] == 5
assert rounds[0]["next_round_starts_word"] is None # no successor inside the horizon
gated = simulate_doc(perfect, starts, continuation, token_starts, horizon=4, policy="gate_before")
# round 0 drafts tokens 1..4 with flags T,F,F,T: stop before token 4 -> 3 drafts, commit 4 tokens
assert gated[0]["n_draft"] == 3 and gated[0]["committed"] == 4
assert len(gated) == 1
def test_simulate_doc_failure_position_and_successor():
continuation = [100, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
token_starts = [False, True, False, True, False, False, True, False, False, True, False, False]
drafts = [[j + 1, 99, 99, 99] for j in range(len(continuation))] # only the first draft is ever right
starts = [[False] * 4 for _ in continuation]
rounds = simulate_doc(drafts, starts, continuation, token_starts, horizon=4, policy="fixed4")
# every round accepts 1 draft and commits 2 tokens: offsets 0 and 2
assert [r["j"] for r in rounds] == [0, 2]
# round at 0 fails on token 2 (continues a word); round at 2 fails on token 4 (continues)
assert [r["failed_at_word_start"] for r in rounds] == [False, False]
# round at 0 is followed by a round whose first token is token 3, a word start
assert rounds[0]["next_round_starts_word"] is True
assert rounds[1]["next_round_starts_word"] is None
def test_all_accepted_round_commits_the_backbones_fifth_token_not_a_repeat():
"""With all four drafts accepted, the fifth committed token is the backbone's
prediction after draft 4 (continuation[5]), never draft 4 again -- the
Phase 3 loop verified only three drafts and repeated the fourth here."""
continuation = [100, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
token_starts = [False] * len(continuation)
drafts = [[continuation[j + 1 + i] if j + 1 + i < len(continuation) else -1 for i in range(4)] for j in range(len(continuation))]
starts = [[False] * 4 for _ in continuation]
rounds = simulate_doc(drafts, starts, continuation, token_starts, horizon=6, policy="fixed4")
first = rounds[0]
assert first["n_acc"] == 4
assert first["committed_tokens"] == [11, 12, 13, 14, 15]
assert first["committed_tokens"][-1] != drafts[0][3]
# the next round starts after all five, i.e. drafts from offset 5
assert rounds[1]["j"] == 5 and rounds[1]["committed_tokens"][0] == 16
def test_word_core_strips_punctuation_but_keeps_itrans_internal_dots():
from scripts.phase4_morpheme_boundaries import word_core
assert word_core("(अमेरिकी", "devanagari") == (1, 8)
assert word_core("देंगी।", "devanagari") == (0, 5)
assert word_core("Election)", "devanagari") is None # Latin word in Devanagari text
assert word_core("esTrA.cnA.cTa", "itrans") == (0, 13) # '.c' is a vowel sign, not punctuation
assert word_core("deMgI.", "itrans") == (0, 5) # sentence-final '.' is stripped
assert word_core("1997", "itrans") is None
def test_token_flags_marks_morpheme_starts_inside_words_only():
from scripts.phase4_morpheme_boundaries import token_flags
table = [b"ab", b"cd", b" ef", b"gh"] # text "abcd efgh": words at bytes 0-4 and 5-9
morphs = {"abcd": ["ab", "cd"], "efgh": ["efg", "h"]}
fl = token_flags([0, 1, 2, 3], table, lambda w: morphs[w], "itrans")
# token starts at bytes 0, 2, 4, 7; boundaries at byte 2 (ab|cd) and byte 8 (efg|h)
assert fl["within"] == [False, True, False, True]
assert fl["morph_start"] == [False, True, False, False]
assert fl["n_morph_boundaries"] == 2 and fl["n_morph_boundaries_at_token_start"] == 1
def test_bytes_to_unicode_is_a_bijection_over_all_bytes():
from scripts.phase4_morpheme_boundaries import bytes_to_unicode
table = bytes_to_unicode()
assert sorted(table) == list(range(256))
assert len(set(table.values())) == 256