okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5993c50a5
main
1"""Tests for tools/force_check.py's neutral-writer gate (cut, gen-neutral, gate_report), without an engine or a GPU: a stand-in writer that speaks 2llama-server's /health and /completion with token ids, and synthetic scored arms for the two-direction report. 3 4python -m unittest tools.test_force_check_neutral 5""" 6from __future__import annotations 7 8import json 9import os 10import random 11import socket 12import subprocess 13import sys 14import tempfile 15import textwrap 16import unittest 17from pathlib import Path 18 19ROOT = Path (__file__ ).resolve ().parents [1 ] 20TOOL = ROOT / "tools" / "force_check.py" 21sys .path .insert (0 ,str (ROOT / "tools" )) 22import force_check as FC # noqa: E402 23 24# A llama-server stand-in: -m MODEL --port P ...; /health -> ok; /completion -> n_predict ids derived from the prompt ids (so the test can 25# check that the ids went in unchanged), and it records every request it got. 26FAKE_WRITER = textwrap .dedent (''' 27import json, sys 28from http.server import BaseHTTPRequestHandler, HTTPServer 29args = sys.argv[1:] 30port = int(args[args.index("--port") + 1]) 31model = args[args.index("-m") + 1] 32log = model + ".requests.jsonl" 33class H(BaseHTTPRequestHandler): 34def log_message(self, *a): 35pass 36def _send(self, obj): 37b = json.dumps(obj).encode() 38self.send_response(200); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(b))) 39self.end_headers(); self.wfile.write(b) 40def do_GET(self): 41self._send({"status": "ok"}) 42def do_POST(self): 43req = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) 44open(log, "a").write(json.dumps(req) + "\\n") 45ids = req["prompt"] 46toks = [(sum(ids) + 7 * i) % 1000 for i in range(req["n_predict"])] 47self._send({"content": "", "tokens": toks, "timings": {"prompt_per_second": 1.0}}) 48HTTPServer(("127.0.0.1", port), H).serve_forever() 49''' ) 50 51 52def free_port (): 53s = socket .socket () 54s .bind (("127.0.0.1" ,0 )) 55p = s .getsockname ()[1 ] 56s .close () 57return p 58 59 60def synthetic_arm (rng ,p_mis ,p_big ,nreq = 48 ,n = 128 ): 61d = {} 62for q in range (nreq ): 63rows = [] 64for _ in range (n ): 65if rng .random ()< p_mis : 66big = rng .random ()< p_big 67rows .append ((True ,rng .uniform (1.0 ,3.0 )if big else rng .uniform (0.0 ,0.4 ),1.0 )) 68else : 69rows .append ((False ,0.0 ,2.0 )) 70d ["r%d" % q ]= rows 71return d 72 73 74class Cut (unittest .TestCase ): 75def test_cuts_at_the_fixed_offsets (self ): 76with tempfile .TemporaryDirectory ()as t : 77ids = list (range (1000 ,1000 + 300 )) 78Path (t ,"ids.txt" ).write_text ("," .join (map (str ,ids ))) 79r = subprocess .run ([sys .executable ,str (TOOL ),"cut" ,str (Path (t ,"ids.txt" )),str (Path (t ,"c.jsonl" )),"--sizes" ,"50,100" ,"--n" ,"3" ], 80capture_output = True ,text = True ) 81self .assertEqual (r .returncode ,0 ,r .stderr ) 82rows = [json .loads (l )for l in Path (t ,"c.jsonl" ).read_text ().splitlines ()] 83self .assertEqual ([x ["id" ]for x in rows ], ["p50-0" ,"p50-1" ,"p50-2" ,"p100-0" ,"p100-1" ,"p100-2" ]) 84for x in rows : 85size ,i = (int (v )for v in x ["id" ][1 :].split ("-" )) 86off = (i * 7919 + size )% (len (ids )- size - 1 ) 87self .assertEqual (x ["ids" ],ids [off :off + size ]) 88self .assertEqual (x ["split" ],"held" ) 89 90def test_a_cut_longer_than_the_file_is_refused (self ): 91with tempfile .TemporaryDirectory ()as t : 92Path (t ,"ids.txt" ).write_text ("," .join (map (str ,range (40 )))) 93r = subprocess .run ([sys .executable ,str (TOOL ),"cut" ,str (Path (t ,"ids.txt" )),str (Path (t ,"c.jsonl" )),"--sizes" ,"64" ,"--n" ,"1" ], 94capture_output = True ,text = True ) 95self .assertNotEqual (r .returncode ,0 ) 96 97 98class GenNeutral (unittest .TestCase ): 99def test_the_writer_gets_the_ids_and_its_tokens_become_the_set (self ): 100with tempfile .TemporaryDirectory ()as t : 101fake = Path (t ,"fake_writer.py" ) 102fake .write_text (FAKE_WRITER ) 103model = Path (t ,"model.gguf" ) 104model .write_text ("not a model" ) 105corpus = Path (t ,"c.jsonl" ) 106rows = [{"id" :"p8-%d" % i ,"kind" :"p8" ,"split" :"held" ,"ids" : [i ,i + 1 ,i + 2 ,5 ,6 ,7 ,8 ,9 ]}for i in range (3 )] 107rows .append ({"id" :"x" ,"kind" :"p8" ,"split" :"train" ,"ids" : [1 ,2 ]})# not held: left out 108corpus .write_text ("" .join (json .dumps (r )+ "\n" for r in rows )) 109out = Path (t ,"set.json" ) 110writer = '"%s" "%s"' % (sys .executable ,fake )if os .name == "nt" else "%s %s" % (sys .executable ,fake ) 111r = subprocess .run ([sys .executable ,str (TOOL ),"gen-neutral" ,str (out ),"--corpus" ,str (corpus ),"--writer" ,writer , 112"--writer-model" ,str (model ),"--writer-port" ,str (free_port ()),"--per-kind" ,"16" ,"--new" ,"5" , 113"--writer-wait" ,"60" ],capture_output = True ,text = True ,timeout = 180 ) 114self .assertEqual (r .returncode ,0 ,r .stdout + r .stderr ) 115st = json .loads (out .read_text ()) 116self .assertEqual (st ["writer" ],"neutral" ) 117self .assertEqual ([it ["id" ]for it in st ["items" ]], ["p8-0" ,"p8-1" ,"p8-2" ]) 118for it ,row in zip (st ["items" ],rows ): 119self .assertEqual (it ["prompt" ],row ["ids" ]) 120self .assertEqual (it ["cont" ], [(sum (row ["ids" ])+ 7 * i )% 1000 for i in range (5 )]) 121reqs = [json .loads (l )for l in Path (str (model )+ ".requests.jsonl" ).read_text ().splitlines ()] 122self .assertEqual (len (reqs ),3 ) 123for q in reqs :# greedy, token ids in, no prompt cache, ids back 124self .assertEqual ((q ["temperature" ],q ["top_k" ],q ["cache_prompt" ],q ["return_tokens" ],q ["n_predict" ]), (0.0 ,1 ,False ,True ,5 )) 125self .assertIsInstance (q ["prompt" ],list ) 126 127def test_a_writer_that_dies_is_reported (self ): 128with tempfile .TemporaryDirectory ()as t : 129corpus = Path (t ,"c.jsonl" ) 130corpus .write_text (json .dumps ({"id" :"a" ,"kind" :"k" ,"ids" : [1 ,2 ,3 ]})+ "\n" ) 131dead = Path (t ,"dead.py" ) 132dead .write_text ("import sys; sys.exit(3)\n" ) 133writer = '"%s" "%s"' % (sys .executable ,dead )if os .name == "nt" else "%s %s" % (sys .executable ,dead ) 134r = subprocess .run ([sys .executable ,str (TOOL ),"gen-neutral" ,str (Path (t ,"s.json" )),"--corpus" ,str (corpus ),"--writer" ,writer , 135"--writer-model" ,str (Path (t ,"m.gguf" )),"--writer-port" ,str (free_port ()),"--writer-wait" ,"30" ], 136capture_output = True ,text = True ,timeout = 120 ) 137self .assertNotEqual (r .returncode ,0 ) 138self .assertIn ("writer ended before it was ready" ,r .stdout + r .stderr ) 139 140 141class GateReport (unittest .TestCase ): 142def test_equal_arms_pass_and_both_directions_are_reported (self ): 143rng = random .Random (11 ) 144stock = [synthetic_arm (rng ,0.035 ,0.0 ),synthetic_arm (rng ,0.035 ,0.0 )] 145cand = [synthetic_arm (rng ,0.035 ,0.0 ),synthetic_arm (rng ,0.035 ,0.0 )] 146r = FC .gate_report (stock ,cand ) 147self .assertNotEqual (r ["verdict" ],"REJECT" ) 148self .assertEqual (len (r ["cand_vs_stock" ]),2 ) 149self .assertEqual (len (r ["stock_vs_cand_reported" ]),2 ) 150 151def test_a_worse_candidate_is_rejected (self ): 152rng = random .Random (12 ) 153stock = [synthetic_arm (rng ,0.007 ,0.0 ,nreq = 60 ,n = 300 ),synthetic_arm (rng ,0.007 ,0.0 ,nreq = 60 ,n = 300 )] 154cand = [synthetic_arm (rng ,0.02 ,0.0 ,nreq = 60 ,n = 300 ),synthetic_arm (rng ,0.02 ,0.0 ,nreq = 60 ,n = 300 )] 155self .assertEqual (FC .gate_report (stock ,cand )["verdict" ],"REJECT" ) 156 157def test_the_reversed_direction_does_not_decide (self ): 158rng = random .Random (13 ) 159stock = [synthetic_arm (rng ,0.02 ,0.0 ,nreq = 60 ,n = 300 ),synthetic_arm (rng ,0.02 ,0.0 ,nreq = 60 ,n = 300 )] 160cand = [synthetic_arm (rng ,0.007 ,0.0 ,nreq = 60 ,n = 300 ),synthetic_arm (rng ,0.007 ,0.0 ,nreq = 60 ,n = 300 )] 161r = FC .gate_report (stock ,cand )# the candidate is better: it passes; stock against it would be rejected 162self .assertEqual (r ["verdict" ],"PASS" ) 163self .assertTrue (all (x ["verdict" ]== "REJECT" for x in r ["stock_vs_cand_reported" ])) 164 165def test_one_rejected_candidate_arm_rejects (self ): 166rng = random .Random (14 ) 167stock = [synthetic_arm (rng ,0.007 ,0.0 ,nreq = 60 ,n = 300 ),synthetic_arm (rng ,0.007 ,0.0 ,nreq = 60 ,n = 300 )] 168cand = [synthetic_arm (rng ,0.007 ,0.0 ,nreq = 60 ,n = 300 ),synthetic_arm (rng ,0.0075 ,0.5 ,nreq = 60 ,n = 300 )] 169self .assertEqual (FC .gate_report (stock ,cand )["verdict" ],"REJECT" ) 170 171 172class GateRefusesEngineText (unittest .TestCase ): 173def test_a_stock_written_set_is_refused_by_gate (self ): 174with tempfile .TemporaryDirectory ()as t : 175Path (t ,"s.json" ).write_text (json .dumps ({"config" :"x" ,"items" : []})) 176Path (t ,"cfg.json" ).write_text (json .dumps ({"exe" :"none" ,"args" : []})) 177r = subprocess .run ([sys .executable ,str (TOOL ),"gate" ,str (Path (t ,"cfg.json" )),str (Path (t ,"s.json" )),str (Path (t ,"o" )), 178"--cand-env" ,"STRATA_X=1" ],capture_output = True ,text = True ,timeout = 60 ) 179self .assertNotEqual (r .returncode ,0 ) 180self .assertIn ("neutral writer" ,r .stdout + r .stderr ) 181 182 183if __name__ == "__main__" : 184unittest .main ()