learned-computer / neurv /dump_trace.py
Prahaladha's picture
sync learned_computer: 35 files from /dev/shm/neurv
7f4b0ba verified
Raw History Blame Contribute Delete
2.65 kB
# record the real chip's per-tick trace for programs the network ran with EVERY tick exact (so this is also the
# network's trace, bit for bit): pc, instruction word, mnemonic, changed registers, changed memory words, output so far.
import json, sys, os
sys.path.insert(0, "/dev/shm/neurv")
import rv
want = sys.argv[1].split(","); cap = int(sys.argv[2]); out = sys.argv[3]
recs = {json.loads(l)["id"]: json.loads(l) for l in open("/dev/shm/neurv/demos/progset.jsonl")}
OP = {0x33: "alu", 0x13: "alui", 0x03: "load", 0x23: "store", 0x63: "branch", 0x6F: "jal", 0x67: "jalr", 0x37: "lui", 0x17: "auipc", 0x73: "sys"}
ALU = {0: "add", 1: "sll", 2: "slt", 3: "sltu", 4: "xor", 5: "srl", 6: "or", 7: "and"}
MUL = {0: "mul", 1: "mulh", 2: "mulhsu", 3: "mulhu", 4: "div", 5: "divu", 6: "rem", 7: "remu"}
BR = {0: "beq", 1: "bne", 4: "blt", 5: "bge", 6: "bltu", 7: "bgeu"}
LD = {0: "lb", 1: "lh", 2: "lw", 4: "lbu", 5: "lhu"}; ST = {0: "sb", 1: "sh", 2: "sw"}
def mn(w):
o, f3, f7 = w & 0x7F, (w >> 12) & 7, w >> 25
if o == 0x33: return (MUL if f7 == 1 else ALU)[f3] if not (f7 == 0x20) else {0: "sub", 5: "sra"}.get(f3, "alu")
if o == 0x13: return {0: "addi", 2: "slti", 3: "sltiu", 4: "xori", 6: "ori", 7: "andi", 1: "slli", 5: "srli"}[f3]
if o == 0x03: return LD.get(f3, "load")
if o == 0x23: return ST.get(f3, "store")
if o == 0x63: return BR.get(f3, "branch")
return {0x6F: "jal", 0x67: "jalr", 0x37: "lui", 0x17: "auipc", 0x73: "ecall"}.get(o, "?")
res = {}
for pid in want:
r = recs[pid]; img, inp = bytes.fromhex(r["img"]), bytes.fromhex(r["inp"])
uc = rv.new_uc(); rv.boot(uc, img, inp); s = rv.read_state(uc)
ticks = []
def outtxt(s):
ptr = 0x300
b = b"".join(int(s[33 + (0x1C00 >> 2) + i]).to_bytes(4, "little") for i in range(0x300 // 4))
return b[:max(0, min(ptr, 0x300))].decode("latin1")
for t in range(cap):
pc = s[32]; w = s[33 + (pc >> 2)] if pc < 0x2000 else 0
n = rv.step_state(uc, s)
regs = [i for i in range(32) if n[i] != s[i]]
mem = [i - 33 for i in range(33, len(n)) if n[i] != s[i]]
ticks.append({"pc": int(pc), "w": int(w), "m": mn(int(w)), "r": regs, "rv": [int(n[i]) for i in regs], "mem": mem, "ol": len(outtxt(n).split("\x00")[0])})
halted = n[32] == pc
s = n
if halted: break
res[pid] = {"keys": sorted(k for k in r if k not in ("img",)), "src": r.get("src", "")[:4000], "inp": inp.decode("latin1"),
"out": outtxt(s), "n": len(ticks), "ticks": ticks}
print(pid, "ticks", len(ticks), "out", repr(outtxt(s))[:80], "keys", res[pid]["keys"])
json.dump(res, open(out, "w"))