File size: 2,977 Bytes
74b7543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""Can each config memorize the atomic facts? Atoms are pure memorization, so a
healthy config must fit them. Trains atoms-only for a few thousand steps."""
import json
import types

import torch
from pathlib import Path
from torch.utils.data import DataLoader, Subset
from transformers import default_data_collator

import train_twin_hyper as m

DATA = Path("data/twin_234hop_truood_diff.500.50.10")
STEPS = 1500
BS = 512
DEV = "cuda"

args = types.SimpleNamespace(
    model_name="gpt2-big", from_scratch=True, trust_remote_code=False,
    use_small_tokenizer=True, create_special_token=True, tokenizer_name=None,
    data_dir=DATA, init_one_hot=0, freeze_embeddings=0,
)
tok = m.build_tokenizer(args)
train = json.loads((DATA / "train.json").read_text())
hops = [m.record_hops(r) for r in train]
ds = m.JsonTextDataset(train, tok, 6, "answer")
atom_idx = [i for i, h in enumerate(hops) if h == 1]
loader = DataLoader(Subset(ds, atom_idx), batch_size=BS, shuffle=True,
                    collate_fn=default_data_collator, drop_last=True)
probe = default_data_collator([ds[i] for i in atom_idx[:2048]])
probe = {k: v.to(DEV) for k, v in probe.items()}

CONFIGS = [
    ("discoloop m4 a=1   b=0   (current)", 4, "discoloop", 1.0, 0.0),
    ("discoloop m4 a=0.5 b=0.5", 4, "discoloop", 0.5, 0.5),
    ("discoloop m2 a=1   b=0", 2, "discoloop", 1.0, 0.0),
    ("vanillaloop m4", 4, "vanillaloop", 0.5, 0.5),
]

print(f"atoms-only memorization test: {STEPS} steps, batch {BS}, lr 1e-3, {len(atom_idx)} atoms")
for name, ns, scheme, a, b in CONFIGS:
    torch.manual_seed(14)
    base = m.build_base_model(args, tok)
    model = m.HyperConnectionGPT2LM(
        base_model=base, num_stages=ns, architecture="looping", gate_mode="fixed",
        fixed_alpha=a, fixed_beta=b, norm_type="rms", zero_final_gate=True, sg_phi=False,
        use_position_embeddings=True, loop_scheme=scheme,
    ).to(DEV)
    opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
    it = iter(loader)
    marks = {}
    model.train()
    for step in range(1, STEPS + 1):
        try:
            batch = next(it)
        except StopIteration:
            it = iter(loader); batch = next(it)
        batch = {k: v.to(DEV) for k, v in batch.items()}
        loss = model(**batch).loss
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step(); opt.zero_grad()
        if step % 500 == 0:
            model.eval()
            with torch.no_grad():
                out = model(**probe)
                il = probe["input_len"]; ar = torch.arange(len(il), device=DEV)
                acc = (out.logits[ar, il - 1].argmax(-1) == probe["input_ids"][ar, il]).float().mean().item()
            marks[step] = (out.loss.item(), acc)
            model.train()
    print(f"\n  [{name}]")
    for s, (l, acc) in marks.items():
        print(f"     step {s:5d}: eval_loss={l:6.3f}  atom_acc={acc:.4f}")
    del model, opt
    torch.cuda.empty_cache()