Prahaladha commited on
Commit
a27a87c
·
verified ·
1 Parent(s): ba6881d

sync learned_computer: 3 files from /dev/shm/neurv

Browse files
Files changed (3) hide show
  1. neurv/rv1.sh +2 -2
  2. neurv/rv_rollout.py +154 -0
  3. neurv/swap_data.sh +7 -0
neurv/rv1.sh CHANGED
@@ -2,10 +2,10 @@
2
  # learned RISC-V computer: 256M, all 8 GPUs. usage: rv1.sh <name> <steps> [extra args]
3
  cd /dev/shm/neurv
4
  NAME=$1; STEPS=$2; shift 2
5
- D=$HOME/neurv_data/split1
6
  export PYTHONPATH=/dev/shm/neurv/pkgs OMP_NUM_THREADS=2 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
7
  echo "$(date -u +%T) RV start name=$NAME steps=$STEPS args=$*"
8
  CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 /dev/shm/prh/venv/bin/python -u -m torch.distributed.run --nproc_per_node 8 --master_port 29820 train_rv.py --name $NAME \
9
- --programs $D/train.jsonl --heldout $D/heldout.jsonl --steps $STEPS --batch 24 --d 1024 --layers 20 --lr 3e-4 --hard 0.5 --prog_share 0.6 \
10
  --eval_every 2000 --workers 14 "$@"
11
  echo "$(date -u +%T) TRAIN_EXIT rc=$?"
 
2
  # learned RISC-V computer: 256M, all 8 GPUs. usage: rv1.sh <name> <steps> [extra args]
3
  cd /dev/shm/neurv
4
  NAME=$1; STEPS=$2; shift 2
5
+ D=$HOME/neurv_data
6
  export PYTHONPATH=/dev/shm/neurv/pkgs OMP_NUM_THREADS=2 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
7
  echo "$(date -u +%T) RV start name=$NAME steps=$STEPS args=$*"
8
  CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 /dev/shm/prh/venv/bin/python -u -m torch.distributed.run --nproc_per_node 8 --master_port 29820 train_rv.py --name $NAME \
9
+ --programs ${PROGS:-$D/split2/train.jsonl} --heldout $D/split1/heldout.jsonl --steps $STEPS --batch 24 --d 1024 --layers 20 --lr 3e-4 --hard 0.5 --prog_share 0.6 \
10
  --eval_every 2000 --workers 14 "$@"
11
  echo "$(date -u +%T) TRAIN_EXIT rc=$?"
neurv/rv_rollout.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run whole programs INSIDE the learned RISC-V computer, with no correction: from boot, every tick the network reads only
2
+ its own previous output. Compared against the real chip tick by tick.
3
+
4
+ The real traces are computed on CPU first (one process per program), stored only as a 64-bit fingerprint per tick, so a
5
+ 100k-tick program costs 800 KB instead of 800 MB. The network loop runs K ticks per CUDA-graph replay, never syncing with
6
+ the CPU; it fingerprints its own state each tick the same way, so the first wrong tick is found exactly.
7
+
8
+ Usage: python rv_rollout.py <ckpt.pt> <programs.jsonl> <outdir> [--n N] [--max_ticks T] [--names a,b]
9
+ Writes outdir/summary.json: per program real_steps, end, first_wrong_tick, output (real and network), output_correct.
10
+ """
11
+ import argparse
12
+ import json
13
+ import multiprocessing as mp
14
+ import os
15
+ import sys
16
+ import time
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn # noqa: F401
21
+ import torch.nn.functional as F # noqa: F401
22
+
23
+ HERE = os.path.dirname(os.path.abspath(__file__))
24
+ sys.path.insert(0, HERE)
25
+ import rv # noqa: E402
26
+
27
+ N_REG, MEM = rv.N_REG, rv.MEM
28
+ N_TOK = N_REG + MEM // 4
29
+ K = 16
30
+ _W = np.random.default_rng(12345).integers(1, 2 ** 30, size=(2, 2 * N_TOK), dtype=np.int64)
31
+
32
+
33
+ def fingerprint_np(s):
34
+ """two 64-bit sums over the 16-bit halves of every word (exact in int64)."""
35
+ h = np.concatenate([(s & 0xFFFF).astype(np.int64), (s >> 16).astype(np.int64)])
36
+ return (_W * h[None]).sum(1)
37
+
38
+
39
+ def real_trace(job):
40
+ img, inp, max_ticks = job
41
+ uc = rv.new_uc()
42
+ rv.boot(uc, img, inp)
43
+ s = rv.read_state(uc)
44
+ fps = [fingerprint_np(s)]
45
+ end = "cap"
46
+ for t in range(max_ticks):
47
+ n = rv.step_state(uc, s)
48
+ fps.append(fingerprint_np(n))
49
+ if int(n[32]) == rv.TRAP_PC:
50
+ end = "trap"; s = n; break
51
+ if int(n[32]) == int(s[32]) and (n == s).all():
52
+ end = "halt"; s = n; break
53
+ s = n
54
+ out_n = min(int(s[N_REG + rv.OUT_PTR // 4]), rv.OUT_LEN)
55
+ out = s[N_REG + rv.OUT_BASE // 4: N_REG + (rv.OUT_BASE + rv.OUT_LEN) // 4].astype("<u4").tobytes()[:out_n]
56
+ return np.stack(fps), end, out, len(fps) - 1
57
+
58
+
59
+ def main():
60
+ ap = argparse.ArgumentParser()
61
+ ap.add_argument("ckpt"); ap.add_argument("programs"); ap.add_argument("outdir")
62
+ ap.add_argument("--n", type=int, default=0); ap.add_argument("--max_ticks", type=int, default=200000)
63
+ ap.add_argument("--names", default="")
64
+ a = ap.parse_args()
65
+ os.makedirs(a.outdir, exist_ok=True)
66
+ recs = [json.loads(l) for l in open(a.programs)]
67
+ if a.names:
68
+ want = set(a.names.split(","))
69
+ recs = [r for r in recs if r["id"] in want or r["id"].replace("demo_", "") in want]
70
+ if a.n:
71
+ recs = recs[:a.n]
72
+ jobs = [(bytes.fromhex(r["img"]), bytes.fromhex(r["inp"]), min(a.max_ticks, int(r["steps"]) + 64)) for r in recs]
73
+ t0 = time.time()
74
+ with mp.get_context("spawn").Pool(min(len(jobs), 32)) as pool:
75
+ traces = pool.map(real_trace, jobs)
76
+ t_real = time.time() - t0
77
+ B = len(jobs)
78
+ T = max(tr[3] for tr in traces)
79
+ T = (T // K + 1) * K
80
+ fp_real = np.zeros((B, T + 1, 2), np.int64)
81
+ for b, (fps, _, _, n) in enumerate(traces):
82
+ fp_real[b, :len(fps)] = fps
83
+ fp_real[b, len(fps):] = fps[-1]
84
+ print(f"real: {B} programs, longest {max(tr[3] for tr in traces)} ticks, {t_real:.1f}s", flush=True)
85
+
86
+ src = open(os.path.join(HERE, "train_rv.py")).read()
87
+ ns = {"np": np, "torch": torch, "nn": nn, "F": F, "N_REG": N_REG, "N_TOK": N_TOK}
88
+ exec(src[src.index("def slot_features"):src.index("def loss_fn")], ns)
89
+ st = torch.load(a.ckpt, map_location="cpu", weights_only=False)
90
+ model = ns["RVNet"](st["args"]["d"], st["args"]["layers"]).cuda().eval()
91
+ model.load_state_dict(st["model"])
92
+ dev = "cuda"
93
+ W = torch.from_numpy(_W).to(dev)
94
+ fpr = torch.from_numpy(fp_real).to(dev)
95
+ lens = torch.tensor([tr[3] for tr in traces], device=dev)
96
+ x = torch.zeros((B, N_TOK), dtype=torch.long, device=dev)
97
+ for b, (img, inp, _) in enumerate(jobs):
98
+ uc = rv.new_uc(); rv.boot(uc, img, inp)
99
+ x[b] = torch.from_numpy(rv.read_state(uc).astype(np.int64))
100
+ x0 = x.clone()
101
+ h0 = torch.cat([x & 0xFFFF, x >> 16], 1)
102
+ fp0 = (h0[:, None, :] * W[None]).sum(-1)
103
+ assert torch.equal(fp0, fpr[:, 0]), "GPU fingerprint of the boot state differs from the CPU one"
104
+ t_g = torch.zeros((), dtype=torch.long, device=dev)
105
+ first_bad = torch.full((B,), -1, dtype=torch.long, device=dev)
106
+ shifts = torch.tensor([0, 8, 16, 24], device=dev)
107
+
108
+ def one():
109
+ with torch.autocast("cuda", dtype=torch.bfloat16, cache_enabled=False):
110
+ by = model(x).argmax(-1) # [B, T, 4]
111
+ nxt = (by << shifts).sum(-1)
112
+ x.copy_(nxt)
113
+ h = torch.cat([nxt & 0xFFFF, nxt >> 16], 1) # [B, 2*N_TOK]
114
+ fp = (h[:, None, :] * W[None]).sum(-1) # [B, 2]
115
+ want = fpr.index_select(1, (t_g + 1).view(1)).squeeze(1)
116
+ bad = (fp != want).any(-1) & (t_g < lens) & (first_bad < 0)
117
+ first_bad.copy_(torch.where(bad, t_g + 1, first_bad))
118
+ t_g.add_(1)
119
+
120
+ def ksteps():
121
+ for _ in range(K):
122
+ one()
123
+
124
+ s_ = torch.cuda.Stream(); s_.wait_stream(torch.cuda.current_stream())
125
+ with torch.no_grad(), torch.cuda.stream(s_):
126
+ ksteps()
127
+ torch.cuda.current_stream().wait_stream(s_)
128
+ g = torch.cuda.CUDAGraph()
129
+ with torch.no_grad(), torch.cuda.graph(g):
130
+ ksteps()
131
+ x.copy_(x0); first_bad.fill_(-1); t_g.zero_(); torch.cuda.synchronize()
132
+ t1 = time.time()
133
+ for _ in range(T // K):
134
+ g.replay()
135
+ torch.cuda.synchronize()
136
+ t_net = time.time() - t1
137
+ fin = x.cpu().numpy().astype(np.uint32)
138
+ fb = first_bad.cpu().numpy()
139
+ res = {"ckpt": a.ckpt, "ticks": T, "sec_net": round(t_net, 1), "ms_per_tick": round(1000 * t_net / T, 2), "programs": {}}
140
+ for b, r in enumerate(recs):
141
+ s = fin[b]
142
+ out_n = min(int(s[N_REG + rv.OUT_PTR // 4]), rv.OUT_LEN)
143
+ net_out = s[N_REG + rv.OUT_BASE // 4: N_REG + (rv.OUT_BASE + rv.OUT_LEN) // 4].astype("<u4").tobytes()[:out_n]
144
+ fps, end, real_out, n = traces[b]
145
+ res["programs"][r["id"]] = {"real_steps": n, "end": end, "first_wrong_tick": int(fb[b]), "all_exact": bool(fb[b] < 0),
146
+ "output_correct": net_out == real_out, "real_out": real_out.decode("latin-1")[:300],
147
+ "net_out": net_out.decode("latin-1")[:300]}
148
+ json.dump(res, open(f"{a.outdir}/summary.json", "w"), indent=1)
149
+ ok = sum(v["output_correct"] for v in res["programs"].values()); ex = sum(v["all_exact"] for v in res["programs"].values())
150
+ print(f"ROLLOUT_DONE {B} programs, output right {ok}, every tick exact {ex}, {res['ms_per_tick']} ms/tick", flush=True)
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
neurv/swap_data.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # at rv2's step_2000 checkpoint: restart it so the watchdog relaunches on the 437k-program split (rv1.sh now points there)
3
+ L=/dev/shm/neurv/logs/handover2.log
4
+ until [ -f /dev/shm/neurv/runs/rv2/step_2000.pt ]; do sleep 30; done
5
+ sleep 20
6
+ echo "$(date -u +%T) swap_data: restarting rv2 at step_2000 on split2 (437,673 programs)" >> $L
7
+ bash /dev/shm/neurv/kill_rv.sh rv2 >> $L 2>&1