"""Native neural self-data candidates; no generated host payload is executed.""" from pathlib import Path import json import os import random import shutil import struct import subprocess import pytest import torch from lightnest import rv32 from lightnest.learned_patch import encode, load_predictor, make_example from lightnest.pack_patch import build, export_weights ROOT = Path(__file__).resolve().parents[1] CHECKPOINT = Path(os.environ.get('LIGHTNEST_PATCH_CHECKPOINT', ROOT / 'work/learned-patch.pt')) def run(exe, *args): return subprocess.run([str(exe), *map(str, args)], capture_output=True, timeout=20) def seed_bytes(): return b''.join(w.to_bytes(4, 'little') for w in [rv32.lw('x1', 0, 'x0'), rv32.lw('x2', 4, 'x0'), rv32.add('x3', 'x1', 'x2'), rv32.addi('x10', 'x3', 0), rv32.EBREAK]) @pytest.fixture(scope='module') def native(tmp_path_factory): if not CHECKPOINT.exists(): pytest.skip('run the bounded learned_patch training experiment first') if not shutil.which('gcc'): pytest.skip('gcc is required') directory = tmp_path_factory.mktemp('native-patch') executable = build(CHECKPOINT, directory / 'patch-nest') return executable, load_predictor(CHECKPOINT) def seeded(native, tmp_path, binary): raw = tmp_path / 'seed.rv32' raw.write_bytes(binary) exe = tmp_path / 'seeded' result = run(native[0], '--init', raw, '-o', exe) assert result.returncode == 0, result.stderr return exe @torch.inference_mode() def reference(predictor, command, binary): c,b=encode(command,binary) logits,bits=predictor.model(torch.tensor([c]),torch.tensor([b])) probs=logits.softmax(-1)[0] pos=int(probs.argmax());confidence=float(probs[pos]);byte=0 if pos==256: return pos,byte,confidence,False,'none' byte=sum(int(bits[0,pos,k]>=0)<=0 and image.find(blob,location+1)<0 for name,offset,value in [('version',8,struct.pack('