sync learned_computer: 14 files from /dev/shm/neurv
Browse filesFiles changed (15)
- .gitattributes+1
- neurv/data/smoke/programs.jsonlAdded+3
- neurv/data/smoke/stats.jsonAdded+152
- neurv/logs/prep_smoke.logAdded+5
- neurv/prep_codenet.pyAdded+95
- neurv/prep_full.shAdded+9
- neurv/prep_smoke.shAdded+6
- neurv/rt/crt0.SAdded+9
- neurv/rt/io.cAdded+84
- neurv/rt/io.hAdded+78
- neurv/rt/link.ldAdded+10
- neurv/rt/t_check.pyAdded+9
- neurv/rt/t_fib.cAdded+3
- neurv/rv.pyAdded+79
- neurv/whyfail.pyAdded+20
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textneurv/data/smoke/programs.jsonl filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:01abdd63e9c8d7598194f3960c25f1645b2052ae782e4e68d4976255029f70e6size 13092206123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152{ "counts": { "ok": 1558, "too_big": 306, "compile": 416, "tiny": 307, "no_halt": 311, "undef": 102 }, "undef_top": [ [ "pow", 39 ], [ "strstr", 12 ], [ "getchar_unlocked", 8 ], [ "hypot", 6 ], [ "scanf_s", 6 ], [ "strtok", 5 ], [ "cbrt", 3 ], [ "main", 3 ], [ "acos", 3 ], [ "putchar_unlocked", 2 ], [ "atof", 2 ], [ "assert", 2 ], [ "atan2", 2 ], [ "fclose", 1 ], [ "fopen", 1 ], [ "write", 1 ], [ "strnlen", 1 ], [ "atan", 1 ], [ "realloc", 1 ], [ "fprint", 1 ], [ "orintf", 1 ], [ "print", 1 ], [ "pritnf", 1 ], [ "memchr", 1 ], [ "ungetc", 1 ], [ "time", 1 ], [ "feof", 1 ], [ "maxHeapify", 1 ], [ "itoa", 1 ], [ "rewind", 1 ], [ "system", 1 ], [ "strtol", 1 ], [ "freopen", 1 ], [ "read", 1 ], [ "snprintf", 1 ] ]}12345jobs 30002000 {'ok': 1040, 'too_big': 205, 'compile': 269, 'tiny': 216, 'no_halt': 201, 'undef': 69}PREP_DONE {'ok': 1558, 'too_big': 306, 'compile': 416, 'tiny': 307, 'no_halt': 311, 'undef': 102} undef top: [('pow', 39), ('strstr', 12), ('getchar_unlocked', 8), ('hypot', 6), ('scanf_s', 6), ('strtok', 5), ('cbrt', 3), ('main', 3), ('acos', 3), ('putchar_unlocked', 2), ('atof', 2), ('assert', 2), ('atan2', 2), ('fclose', 1), ('fopen', 1), ('write', 1), ('strnlen', 1), ('atan', 1), ('realloc', 1), ('fprint', 1), ('orintf', 1), ('print', 1), ('pritnf', 1), ('memchr', 1), ('ungetc', 1), ('time', 1), ('feof', 1), ('maxHeapify', 1), ('itoa', 1), ('rewind', 1)]rc=01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""CodeNet C submissions -> programs that compile for our 8 KiB RV32IM machine and run on it.
For each submission: drop its #include lines, add our io.h, compile with zig, run on a random input on the real chip (Unicorn).Keeps: image + input + instruction count. Logs why the others failed (link error symbol, too big, crash).Usage: python prep_codenet.py <parquet ...> --out DIR [--limit N] [--procs P] [--max_steps S]"""import argparseimport collectionsimport jsonimport multiprocessing as mpimport osimport randomimport reimport subprocessimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
INC = re.compile(r"^\s*#\s*include\s*[<\"][^>\"]*[>\"]\s*$", re.M)UNDEF = re.compile(r"undefined symbol: (\S+)")
def rand_input(rng): """A plausible stdin: a few lines of small integers (most CodeNet programs read numbers).""" k = rng.choice([1, 2, 3, 5, 8]) lines = [str(k)] + [" ".join(str(rng.randint(0, rng.choice([9, 99, 999]))) for _ in range(rng.randint(1, 6))) for _ in range(k)] return ("\n".join(lines) + "\n").encode()
def work(job): import rv sid, code, seed = job rng = random.Random(seed) src = '#include "io.h"\n' + INC.sub("", code) try: img = rv.compile_c(src, "p") except subprocess.CalledProcessError as e: err = (e.stderr or b"").decode(errors="replace") u = UNDEF.findall(err) if u: return sid, "undef", sorted(set(u))[:4], None if "overflow" in err or "will not fit" in err or "exceeds" in err: return sid, "too_big", [], None return sid, "compile", [err.strip().splitlines()[-1][:120] if err.strip() else "?"], None except ValueError: return sid, "too_big", [], None except Exception as e: # timeout etc return sid, "compile", [type(e).__name__], None inp = rand_input(rng) steps, out, halted = rv.run(img, inp, max_steps=MAX_STEPS) if steps < 50: return sid, "tiny", [], None return sid, "ok" if halted else "no_halt", [], {"id": sid, "img": img.hex(), "inp": inp.hex(), "steps": steps, "halted": halted, "out": out[:120].decode("latin-1")}
def init(ms): global MAX_STEPS MAX_STEPS = ms os.environ["RV_TMP"] = "/dev/shm/neurv/tmp"
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("parquet", nargs="+") ap.add_argument("--out", required=True) ap.add_argument("--limit", type=int, default=0) ap.add_argument("--procs", type=int, default=64) ap.add_argument("--max_steps", type=int, default=300000) a = ap.parse_args() import pyarrow.parquet as pq os.makedirs(a.out, exist_ok=True) os.makedirs("/dev/shm/neurv/tmp", exist_ok=True) jobs = [] for f in a.parquet: t = pq.read_table(f, columns=["s_id", "code", "status"]) for sid, code, st in zip(t["s_id"].to_pylist(), t["code"].to_pylist(), t["status"].to_pylist()): if code and len(code) < 6000: jobs.append((sid, code, hash(sid) & 0xFFFFFFFF)) random.Random(0).shuffle(jobs) if a.limit: jobs = jobs[:a.limit] print(f"jobs {len(jobs)}", flush=True) cnt, undef = collections.Counter(), collections.Counter() with open(f"{a.out}/programs.jsonl", "w") as fo, mp.get_context("fork").Pool(a.procs, init, (a.max_steps,)) as pool: for i, (sid, kind, info, rec) in enumerate(pool.imap_unordered(work, jobs, chunksize=8)): cnt[kind] += 1 if kind == "undef": undef.update(info) if rec: fo.write(json.dumps(rec) + "\n") if (i + 1) % 2000 == 0: print(f"{i + 1} {dict(cnt)}", flush=True) json.dump({"counts": cnt, "undef_top": undef.most_common(60)}, open(f"{a.out}/stats.json", "w"), indent=1) print("PREP_DONE", dict(cnt), "\nundef top:", undef.most_common(30), flush=True)123456789#!/bin/bash# full CodeNet C filter -> $HOME/neurv_data/codenet (disk, not RAM disk)cd /dev/shm/neurvOUT=$HOME/neurv_data/codenetmkdir -p $OUT logsexport PYTHONPATH=/dev/shm/neurv/pkgs ZIG_GLOBAL_CACHE_DIR=/dev/shm/neurv/zigcache OMP_NUM_THREADS=1echo "$(date -u +%T) PREP_FULL start out=$OUT"nice -n 19 /dev/shm/prh/venv/bin/python -u prep_codenet.py src/codenet/c0.parquet src/codenet/c1.parquet --out $OUT --procs 100 > logs/prep_full.log 2>&1echo "rc=$?" >> logs/prep_full.log123456#!/bin/bashcd /dev/shm/neurvmkdir -p logsexport PYTHONPATH=/dev/shm/neurv/pkgs ZIG_GLOBAL_CACHE_DIR=/dev/shm/neurv/zigcache OMP_NUM_THREADS=1nice -n 19 /dev/shm/prh/venv/bin/python -u prep_codenet.py src/codenet/c0.parquet src/codenet/c1.parquet --out data/smoke --limit 3000 --procs 48 > logs/prep_smoke.log 2>&1echo "rc=$?" >> logs/prep_smoke.log123456789# entry: stack below the I/O area, call main, then spin forever on one instruction (the halted state) .section .text.start .globl _start_start: li sp, 0x1C00 call main .globl _halt_halt: j _halt123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#include "io.h"#include <stdarg.h>int putchar(int c){ int p = OUT_PTR; if(p < OUT_LEN){ OUT_BASE[p] = (char)c; OUT_PTR = p + 1; } return c; }int getchar(void){ int p = IN_PTR; if(p >= IN_LEN || IN_BASE[p] == 0) return EOF; IN_PTR = p + 1; return (unsigned char)IN_BASE[p]; }int puts(const char *s){ while(*s) putchar(*s++); putchar('\n'); return 0; }static void put_u(unsigned long long v, int base, int width, char pad){ char b[24]; int n = 0; do { int d = (int)(v % base); b[n++] = d < 10 ? '0' + d : 'a' + d - 10; v /= base; } while(v); while(n < width--) putchar(pad); while(n) putchar(b[--n]); }int printf(const char *f, ...){ va_list ap; va_start(ap, f); for(; *f; f++){ if(*f != '%'){ putchar(*f); continue; } f++; char pad = ' '; int width = 0, lng = 0; if(*f == '0'){ pad = '0'; f++; } while(*f >= '0' && *f <= '9') width = width * 10 + (*f++ - '0'); while(*f == 'l'){ lng++; f++; } if(*f == 'z' || *f == 'h') f++; if(*f == 'd' || *f == 'i'){ long long v = lng >= 2 ? va_arg(ap, long long) : va_arg(ap, int); if(v < 0){ putchar('-'); v = -v; if(width) width--; } put_u((unsigned long long)v, 10, width, pad); } else if(*f == 'u'){ unsigned long long v = lng >= 2 ? va_arg(ap, unsigned long long) : va_arg(ap, unsigned); put_u(v, 10, width, pad); } else if(*f == 'x'){ unsigned long long v = lng >= 2 ? va_arg(ap, unsigned long long) : va_arg(ap, unsigned); put_u(v, 16, width, pad); } else if(*f == 'c') putchar(va_arg(ap, int)); else if(*f == 's'){ const char *s = va_arg(ap, const char *); while(*s) putchar(*s++); } else if(*f == '%') putchar('%'); } va_end(ap); return 0; }static int peekc = -2;static int gc(void){ if(peekc != -2){ int c = peekc; peekc = -2; return c; } return getchar(); }static void ungc(int c){ peekc = c; }static int skipws(void){ int c; do c = gc(); while(c == ' ' || c == '\n' || c == '\t' || c == '\r'); return c; }int scanf(const char *f, ...){ va_list ap; va_start(ap, f); int n = 0; for(; *f; f++){ if(*f == ' ' || *f == '\n'){ int c = skipws(); ungc(c); continue; } if(*f != '%'){ int c = gc(); if(c != *f){ ungc(c); break; } continue; } f++; int lng = 0; while(*f == 'l'){ lng++; f++; } if(*f == 'd' || *f == 'u'){ int c = skipws(), neg = 0; long long v = 0; if(c == '-'){ neg = 1; c = gc(); } if(c < '0' || c > '9'){ ungc(c); break; } while(c >= '0' && c <= '9'){ v = v * 10 + (c - '0'); c = gc(); } ungc(c); if(neg) v = -v; if(lng >= 2) *va_arg(ap, long long *) = v; else *va_arg(ap, int *) = (int)v; n++; } else if(*f == 's'){ char *s = va_arg(ap, char *); int c = skipws(); if(c == EOF) break; while(c != EOF && c != ' ' && c != '\n'){ *s++ = (char)c; c = gc(); } *s = 0; ungc(c); n++; } else if(*f == 'c'){ int c = gc(); if(c == EOF) break; *va_arg(ap, char *) = (char)c; n++; } } va_end(ap); return n ? n : EOF; }size_t strlen(const char *s){ size_t n = 0; while(s[n]) n++; return n; }int strcmp(const char *a, const char *b){ while(*a && *a == *b){ a++; b++; } return (unsigned char)*a - (unsigned char)*b; }char *strcpy(char *d, const char *s){ char *r = d; while((*d++ = *s++)); return r; }void *memset(void *p, int c, size_t n){ char *q = p; while(n--) *q++ = (char)c; return p; }void *memcpy(void *d, const void *s, size_t n){ char *a = d; const char *b = s; while(n--) *a++ = *b++; return d; }extern char __heap_start[]; static char *brk_ = 0;void *malloc(size_t n){ if(!brk_) brk_ = __heap_start; n = (n + 3) & ~3u; char *p = brk_; if((unsigned)(brk_ + n) > 0x1800) return NULL; brk_ += n; return p; }void *calloc(size_t n, size_t m){ void *p = malloc(n * m); if(p) memset(p, 0, n * m); return p; }void free(void *p){ (void)p; }int abs(int x){ return x < 0 ? -x : x; }/* ---- the rest of the common C library, kept tiny ---- */static FILE f_in = {0}, f_out = {1}, f_err = {2};FILE *stdin = &f_in, *stdout = &f_out, *stderr = &f_err;int fputc(int c, FILE *f){ (void)f; return putchar(c); }int putc(int c, FILE *f){ (void)f; return putchar(c); }int fputs(const char *s, FILE *f){ (void)f; while(*s) putchar(*s++); return 0; }int fgetc(FILE *f){ (void)f; return gc(); }int getc(FILE *f){ (void)f; return gc(); }int fflush(FILE *f){ (void)f; return 0; }char *fgets(char *s, int n, FILE *f){ (void)f; int i = 0, c = 0; while(i < n - 1 && (c = gc()) != EOF){ s[i++] = (char)c; if(c == '\n') break; } if(i == 0 && c == EOF) return NULL; s[i] = 0; return s; }char *gets(char *s){ int i = 0, c; while((c = gc()) != EOF && c != '\n') s[i++] = (char)c; s[i] = 0; return (i == 0 && c == EOF) ? NULL : s; }extern void _halt(void);void exit(int code){ (void)code; _halt(); }long long atoll(const char *s){ long long v = 0; int neg = 0; while(*s == ' ') s++; if(*s == '-'){ neg = 1; s++; } else if(*s == '+') s++; while(*s >= '0' && *s <= '9') v = v * 10 + (*s++ - '0'); return neg ? -v : v; }int atoi(const char *s){ return (int)atoll(s); }long atol(const char *s){ return (long)atoll(s); }long labs(long x){ return x < 0 ? -x : x; }long long llabs(long long x){ return x < 0 ? -x : x; }static unsigned rnd_ = 1;int rand(void){ rnd_ = rnd_ * 1103515245u + 12345u; return (rnd_ >> 16) & 0x7fff; }void srand(unsigned s){ rnd_ = s; }static void swapb(char *a, char *b, size_t n){ while(n--){ char t = *a; *a++ = *b; *b++ = t; } }void qsort(void *base, size_t n, size_t sz, int (*cmp)(const void *, const void *)){ char *b = base; for(size_t i = 1; i < n; i++) for(size_t j = i; j > 0 && cmp(b + (j - 1) * sz, b + j * sz) > 0; j--) swapb(b + (j - 1) * sz, b + j * sz, sz); }int strncmp(const char *a, const char *b, size_t n){ while(n && *a && *a == *b){ a++; b++; n--; } return n ? (unsigned char)*a - (unsigned char)*b : 0; }char *strcat(char *d, const char *s){ char *r = d; while(*d) d++; while((*d++ = *s++)); return r; }char *strncpy(char *d, const char *s, size_t n){ char *r = d; while(n && (*d++ = *s++)) n--; while(n--) *d++ = 0; return r; }char *strchr(const char *s, int c){ while(*s){ if(*s == (char)c) return (char *)s; s++; } return c ? NULL : (char *)s; }char *strrev(char *s){ size_t n = strlen(s); for(size_t i = 0; i < n / 2; i++){ char t = s[i]; s[i] = s[n - 1 - i]; s[n - 1 - i] = t; } return s; }void *memmove(void *d, const void *s, size_t n){ char *a = d; const char *b = s; if(a < b){ while(n--) *a++ = *b++; } else { a += n; b += n; while(n--) *--a = *--b; } return d; }int memcmp(const void *a, const void *b, size_t n){ const unsigned char *x = a, *y = b; while(n--){ if(*x != *y) return *x - *y; x++; y++; } return 0; }int isdigit(int c){ return c >= '0' && c <= '9'; } int isalpha(int c){ return (c | 32) >= 'a' && (c | 32) <= 'z'; }int isspace(int c){ return c == ' ' || (c >= 9 && c <= 13); } int isupper(int c){ return c >= 'A' && c <= 'Z'; }int islower(int c){ return c >= 'a' && c <= 'z'; } int isalnum(int c){ return isdigit(c) || isalpha(c); }int toupper(int c){ return islower(c) ? c - 32 : c; } int tolower(int c){ return isupper(c) ? c + 32 : c; }static char *sp_; static int sput(int c){ *sp_++ = (char)c; *sp_ = 0; return c; }int sprintf(char *s, const char *f, ...){ (void)s; (void)f; return 0; }int sscanf(const char *s, const char *f, ...){ (void)s; (void)f; return 0; }int fscanf(FILE *fp, const char *f, ...){ (void)fp; (void)f; return 0; }int fprintf(FILE *fp, const char *f, ...){ (void)fp; (void)f; return 0; }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778/* tiny libc for the learned RISC-V machine. Output and input live in memory, so the whole machine state is just RAM + registers. */#ifndef IO_H#define IO_H#define OUT_BASE ((volatile char *)0x1C00)#define OUT_LEN 0x300#define OUT_PTR (*(volatile int *)0x1F00)#define IN_PTR (*(volatile int *)0x1F04)#define IN_BASE ((volatile char *)0x1F08)#define IN_LEN 0xF8typedef unsigned int size_t;#define NULL ((void *)0)#define EOF (-1)#define INT_MAX 2147483647#define INT_MIN (-INT_MAX - 1)#define LLONG_MAX 9223372036854775807LL#define bool _Bool#define true 1#define false 0typedef signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t;typedef int int32_t; typedef unsigned int uint32_t; typedef long long int64_t; typedef unsigned long long uint64_t;typedef int ssize_t; typedef long ptrdiff_t; typedef unsigned int uintptr_t; typedef int intptr_t;#define UINT_MAX 4294967295U#define LONG_MAX 2147483647L#define LONG_MIN (-LONG_MAX - 1L)#define LLONG_MIN (-LLONG_MAX - 1LL)#define ULLONG_MAX 18446744073709551615ULL#define CHAR_BIT 8#define SHRT_MAX 32767#define RAND_MAX 32767typedef struct { int fd; } FILE;extern FILE *stdin, *stdout, *stderr;int fprintf(FILE *f, const char *fmt, ...);int fputc(int c, FILE *f);int fputs(const char *s, FILE *f);int fgetc(FILE *f);char *fgets(char *s, int n, FILE *f);char *gets(char *s);int sprintf(char *s, const char *fmt, ...);int sscanf(const char *s, const char *fmt, ...);int fscanf(FILE *f, const char *fmt, ...);int putc(int c, FILE *f);int getc(FILE *f);int fflush(FILE *f);void exit(int code);int atoi(const char *s);long atol(const char *s);long long atoll(const char *s);long labs(long x);long long llabs(long long x);int rand(void);void srand(unsigned s);void qsort(void *base, size_t n, size_t sz, int (*cmp)(const void *, const void *));int strncmp(const char *a, const char *b, size_t n);char *strcat(char *d, const char *s);char *strncpy(char *d, const char *s, size_t n);char *strchr(const char *s, int c);char *strrev(char *s);void *memmove(void *d, const void *s, size_t n);int memcmp(const void *a, const void *b, size_t n);int isdigit(int c); int isalpha(int c); int isspace(int c); int isupper(int c); int islower(int c); int isalnum(int c);int toupper(int c); int tolower(int c);#define max(a,b) ((a) > (b) ? (a) : (b))#define min(a,b) ((a) < (b) ? (a) : (b))int putchar(int c);int getchar(void);int puts(const char *s);int printf(const char *fmt, ...);int scanf(const char *fmt, ...);size_t strlen(const char *s);int strcmp(const char *a, const char *b);char *strcpy(char *d, const char *s);void *memset(void *p, int c, size_t n);void *memcpy(void *d, const void *s, size_t n);void *malloc(size_t n);void *calloc(size_t n, size_t m);void free(void *p);int abs(int x);#endif12345678910/* 8 KiB machine: program + data from 0, stack grows down from 0x1C00, I/O block at 0x1C00..0x1FFF */MEMORY { RAM (rwx) : ORIGIN = 0x0, LENGTH = 0x1A00 }SECTIONS { .text : { *(.text.start) *(.text .text.*) } > RAM .rodata : { *(.rodata .rodata.* .srodata .srodata.*) } > RAM .data : { *(.data .data.* .sdata .sdata.*) } > RAM .bss : { __bss_start = .; *(.bss .bss.* .sbss .sbss.* COMMON) __bss_end = .; } > RAM __heap_start = .; /DISCARD/ : { *(.comment) *(.riscv.attributes) *(.eh_frame*) }}123456789import sys, timesys.path.insert(0, "/dev/shm/neurv")import rvimg = rv.compile_c(open("/dev/shm/neurv/rt/t_fib.c").read())print("image bytes", len(img))t = time.time(); steps, out, h = rv.run(img, b"15\n"); dt = time.time() - tprint("steps", steps, "halted", h, "sec", round(dt, 2), "out", out)m = rv.Machine(img, b"15\n"); s0 = m.state(); m.step(); s1 = m.state()print("state len", len(s0), "changed words", int((s0 != s1).sum()), "pc", s0[32], "->", s1[32])123#include "io.h"int fib(int n){ return n < 2 ? n : fib(n - 1) + fib(n - 2); }int main(void){ int n; scanf("%d", &n); for(int i = 0; i <= n; i++) printf("%d ", fib(i)); printf("\n%lld\n", (long long)fib(n) * 1000003LL); return 0; }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""The real chip: RV32IM with 8 KiB of memory, run by Unicorn. Compile C with zig cc, load, step, read the full state.
State = 32 registers (x0..x31) + PC + 8 KiB of memory. Output and input live in memory (see rt/io.h), so this IS the whole machine."""import osimport subprocessimport tempfile
import numpy as npfrom unicorn import Uc, UC_ARCH_RISCV, UC_MODE_RISCV32, UcErrorfrom unicorn.riscv_const import UC_RISCV_REG_PC, UC_RISCV_REG_X0
HERE = os.path.dirname(os.path.abspath(__file__))RT = os.path.join(HERE, "rt")ZIG = os.environ.get("ZIG", "/dev/shm/neurv/pkgs/ziglang/zig")MEM = 0x2000OUT_BASE, OUT_LEN, OUT_PTR, IN_PTR, IN_BASE, IN_LEN = 0x1C00, 0x300, 0x1F00, 0x1F04, 0x1F08, 0xF8HALT_WORD = 0x0000006F # "j ." : the program has finishedCFLAGS = ["-target", "riscv32-freestanding-none", "-mcpu=generic_rv32+m", "-Os", "-ffreestanding", "-nostartfiles", "-fno-stack-protector", "-fno-builtin", "-std=gnu99", "-Wno-error=implicit-int", "-Wno-error=implicit-function-declaration", "-Wno-error=int-conversion", "-Wno-error=incompatible-pointer-types", "-Wno-error=return-mismatch", "-Wno-error=return-type", "-I", RT, "-T", os.path.join(RT, "link.ld"), "-Wl,--gc-sections", "-ffunction-sections", "-fdata-sections", "-w"]
def compile_c(src_text, tag="p"): """C source text -> flat memory image (bytes) or raises CalledProcessError / ValueError.""" with tempfile.TemporaryDirectory(dir=os.environ.get("RV_TMP")) as d: c = os.path.join(d, tag + ".c") open(c, "w").write(src_text) elf, binf = os.path.join(d, "a.elf"), os.path.join(d, "a.bin") subprocess.run([ZIG, "cc", *CFLAGS, os.path.join(RT, "crt0.S"), os.path.join(RT, "io.c"), c, "-o", elf], check=True, capture_output=True, timeout=60, env={**os.environ, "ZIG_GLOBAL_CACHE_DIR": os.environ.get("ZIG_GLOBAL_CACHE_DIR", "/dev/shm/neurv/zigcache"), "ZIG_LOCAL_CACHE_DIR": os.path.join(d, "zc")}) subprocess.run([ZIG, "objcopy", "-O", "binary", elf, binf], check=True, capture_output=True, timeout=30) img = open(binf, "rb").read() if len(img) > 0x1A00: raise ValueError(f"image {len(img)} bytes > 0x1A00") return img
class Machine: def __init__(self, image, inp=b""): self.uc = Uc(UC_ARCH_RISCV, UC_MODE_RISCV32) self.uc.mem_map(0, MEM) self.uc.mem_write(0, bytes(image)) inp = bytes(inp)[:IN_LEN - 1] self.uc.mem_write(IN_BASE, inp) self.uc.reg_write(UC_RISCV_REG_PC, 0)
def state(self): """[33 + 2048] uint32: x0..x31, pc, then memory as 2048 little-endian words.""" regs = [self.uc.reg_read(UC_RISCV_REG_X0 + i) for i in range(32)] + [self.uc.reg_read(UC_RISCV_REG_PC)] mem = np.frombuffer(bytes(self.uc.mem_read(0, MEM)), dtype="<u4") return np.concatenate([np.array(regs, dtype=np.uint32), mem.astype(np.uint32)])
def halted(self): pc = self.uc.reg_read(UC_RISCV_REG_PC) return int.from_bytes(bytes(self.uc.mem_read(pc, 4)), "little") == HALT_WORD
def step(self, n=1): pc = self.uc.reg_read(UC_RISCV_REG_PC) self.uc.emu_start(pc, MEM, count=n)
def output(self): n = int.from_bytes(bytes(self.uc.mem_read(OUT_PTR, 4)), "little") return bytes(self.uc.mem_read(OUT_BASE, min(n, OUT_LEN)))
def run(image, inp=b"", max_steps=1_000_000, chunk=1000): """Run to the halt loop. Returns (steps, output bytes, halted).""" m = Machine(image, inp) steps = 0 while steps < max_steps: if m.halted(): return steps, m.output(), True try: m.step(1) except UcError: return steps, m.output(), False steps += 1 return steps, m.output(), False1234567891011121314151617181920import sys, os, re, random, subprocess, collectionssys.path.insert(0, "/dev/shm/neurv"); os.environ["RV_TMP"] = "/dev/shm/neurv/tmp"import rv, pyarrow.parquet as pqfrom multiprocessing import PoolINC = re.compile(r"^\s*#\s*include\s*[<\"][^>\"]*[>\"]\s*$", re.M)t = pq.read_table("/dev/shm/neurv/src/codenet/c0.parquet", columns=["s_id", "code"])codes = [c for c in t["code"].to_pylist()[:6000] if c and len(c) < 6000]random.Random(1).shuffle(codes)def f(code): try: rv.compile_c('#include "io.h"\n' + INC.sub("", code)); return None except subprocess.CalledProcessError as e: err = (e.stderr or b"").decode(errors="replace") m = re.findall(r"error: (.*)", err) return m[0][:90] if m else err.strip()[-90:] except ValueError: return "too big image"with Pool(48) as p: r = p.map(f, codes[:800])c = collections.Counter(re.sub(r"'[^']*'", "'X'", x) for x in r if x)for k, v in c.most_common(25): print(v, k)c2 = collections.Counter(re.findall(r"'([^']*)'", x)[0] for x in r if x and "undeclared function" in x or (x and "implicit" in x and re.findall(r"'([^']*)'", x)))print(c2.most_common(40)).gitattributes+1
neurv/data/smoke/programs.jsonlAdded+3
neurv/data/smoke/stats.jsonAdded+152
neurv/logs/prep_smoke.logAdded+5
neurv/prep_codenet.pyAdded+95
neurv/prep_full.shAdded+9
neurv/prep_smoke.shAdded+6
neurv/rt/crt0.SAdded+9
neurv/rt/io.cAdded+84
neurv/rt/io.hAdded+78
neurv/rt/link.ldAdded+10
neurv/rt/t_check.pyAdded+9
neurv/rt/t_fib.cAdded+3
neurv/rv.pyAdded+79
neurv/whyfail.pyAdded+20