File size: 5,174 Bytes
af21d7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
# activation patching on frozen in-world eval steps: target = own previous action (frozen), source = the teacher's
# previous action (moves); copy one block's attention output (proj) or MLP output (down) at the current step only
import sys, os, numpy as np, torch
MC = os.path.expanduser("~/dev/mcsr-speedrun"); sys.path[:0] = [MC, MC + "/scripts"]
from mcsr.kvstep import load_policy, EDITS
from mcsr.interp.vp_hook import attach
O = MC + "/data/iron/rc"; dev = torch.device("cuda")
m = load_policy(MC + "/data/iron/sW/policy-unfused.pt", dev); attach(m, EDITS)
rec = torch.load(f"{O}/rec_eval.pt"); z = dict(np.load(f"{O}/steps_eval.npz"))
n, L = rec["VALID"].shape
fz = np.zeros((n, L), bool)
for e in range(n):
    i = np.where(z["env"] == e)[0]; i = i[np.argsort(z["t"][i])]
    st = np.stack([z["x"][i], z["y"][i], z["z"][i], z["yaw"][i], z["pitch"][i]], 1)
    ch = np.where(np.abs(np.diff(st, axis=0)).max(1) > 1e-3)[0]; f = ch[-1] + 1 if len(ch) else 0
    if f < L - 10: fz[e, f + 5:] = z["screen"][i][f + 5:] == 0
fz[:, :256] = False
es, ts = np.where(fz); pick = np.random.default_rng(1).choice(len(es), 400, replace=False)
E, CAM, KEY, TC, TK = rec["E"], rec["CAM"].long(), rec["KEY"].float(), rec["TCAM"].long(), (rec["TKEY"].float() > .5).float()
def batch(idx, src):
    e = torch.stack([E[es[i], ts[i] - 255:ts[i] + 1] for i in idx]).to(dev)
    c = torch.stack([CAM[es[i], ts[i] - 256:ts[i]] for i in idx]); k = torch.stack([KEY[es[i], ts[i] - 256:ts[i]] for i in idx])
    if src == "teacher":
        c[:, -1] = torch.stack([TC[es[i], ts[i] - 1] for i in idx]); k[:, -1] = torch.stack([TK[es[i], ts[i] - 1] for i in idx])
    return e, c.to(dev), k.to(dev)
mods = [(f"block {l:2d} attention", m.blocks[l].proj) for l in range(len(m.blocks))] + \
       [(f"block {l:2d} MLP", m.blocks[l].down) for l in range(len(m.blocks))]
def run(idx, src, record=None, patch=None):
    hs = []
    for nm, mod in mods:
        if record is not None:
            hs.append(mod.register_forward_hook(lambda md, a, y, nm=nm: record.__setitem__(nm, y[:, -1].detach().clone())))
        if patch is not None and nm == patch[0]:
            def h(md, a, y, v=patch[1]):
                y = y.clone(); y[:, -1] = v.to(y.dtype); return y
            hs.append(mod.register_forward_hook(h))
    e, c, k = batch(idx, src)
    with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
        o = m.temporal(e, {"camera": c, "act": k})
    for h in hs: h.remove()
    return torch.softmax(o["camera"][:, -1].float(), -1)[..., 20].min(-1).values.cpu()
res = {nm: [] for nm, _ in mods}; base_t, base_s = [], []
for b0 in range(0, 400, 50):
    idx = pick[b0:b0 + 50]
    srec = {}
    base_s.append(run(idx, "teacher", record=srec)); base_t.append(run(idx, "own"))
    for nm, _ in mods:
        res[nm].append(run(idx, "own", patch=(nm, srec[nm])))
bt, bs = torch.cat(base_t), torch.cat(base_s)
print(f"frozen in-world eval steps: {len(bt)}; own previous action p(no move) median {bt.median():.3f}, moves on {(bt<.5).float().mean():.1%}; "
      f"teacher's previous action median {bs.median():.3f}, moves on {(bs<.5).float().mean():.1%}")
print("copying ONE component's output at the current step from the teacher-previous run into the frozen run:")
for nm, _ in mods:
    p = torch.cat(res[nm])
    print(f"  {nm:20s}: p(no move) median {p.median():.3f}; moves on {(p<.5).float().mean():6.1%}")

# block 0's attention pattern from the current step, frozen (own previous action) vs teacher's previous action
from mcsr.model import rope
import torch.nn.functional as F
def attn0(idx, src):
    e, c, k = batch(idx, src)
    cap = {}
    h = m.blocks[0].register_forward_pre_hook(lambda md, a: cap.__setitem__("x", a[0].detach()))
    with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
        m.temporal(e, {"camera": c, "act": k})
    h.remove()
    b = m.blocks[0]; x = cap["x"].float(); B, T, Dm = x.shape; H = b.heads
    with torch.no_grad():
        q, kk, v = b.qkv(b.n1(x.to(b.qkv.weight.dtype)).float().to(b.qkv.weight.dtype)).float().view(B, T, 3, H, Dm // H).permute(2, 0, 3, 1, 4)
        cos, sin = m.cos[:, :, :T].float(), m.sin[:, :, :T].float()
        q, kk = rope(q, cos, sin), rope(kk, cos, sin)
        w = torch.softmax((q[:, :, -1:] @ kk.transpose(-1, -2)) / (Dm // H) ** .5, -1)[:, :, 0]   # [B, H, T]
    return w.cpu()
wo, wt = [], []
for b0 in range(0, 400, 50):
    idx = pick[b0:b0 + 50]; wo.append(attn0(idx, "own")); wt.append(attn0(idx, "teacher"))
wo, wt = torch.cat(wo), torch.cat(wt)
for nm, w in (("own previous action (frozen)", wo), ("teacher's previous action", wt)):
    self_ = w[..., -1]; last4 = w[..., -4:].sum(-1)
    ent = -(w.clamp_min(1e-12) * w.clamp_min(1e-12).log()).sum(-1)
    print(f"block 0 attention from the current step, {nm}: mass on itself mean {self_.mean():.3f} (per head max {self_.mean(0).max():.3f}), "
          f"on the last 4 steps {last4.mean():.3f}, entropy {ent.mean():.2f} nats of max {np.log(256):.2f}")
print("per head, mass on itself: own " + " ".join(f"{v:.2f}" for v in wo[..., -1].mean(0)) + "\n               teacher's " + " ".join(f"{v:.2f}" for v in wt[..., -1].mean(0)))