Download tools/parity.py from RightNowAI/RightNow-Mini: direct link, hf CLI and curl.
- Browser
- Download file 6.75 kB
-
https://huggingface.co/RightNowAI/RightNow-Mini/resolve/main/tools/parity.py
- Command line
-
hf download hf://RightNowAI/RightNow-Mini/tools/parity.py
-
curl -L -o parity.py https://huggingface.co/RightNowAI/RightNow-Mini/resolve/main/tools/parity.py
6.75 kB
| """Greedy parity: does an engine configuration give the same tokens as the stock model? | |
| python tools/parity.py capture --url http://127.0.0.1:9000 --model inkling-2-mini --out results/raw/parity/stock-a.json | |
| python tools/parity.py compare results/raw/parity/stock-a.json results/raw/parity/candidate.json --md results/parity.md | |
| Capture: 200 fixed coding prompts, one request at a time (a request's tokens can depend on what shares its batch), | |
| temperature 0, 128 new tokens, the server's own token ids. Compare: prompts whose token ids are equal, and for the | |
| others the position of the first difference. Nothing is rounded: a prompt is equal or it is not. | |
| """ | |
| import argparse | |
| import json | |
| import sys | |
| import time | |
| import urllib.request | |
| TOPICS = [ | |
| "an LRU cache with O(1) get and put", "a trie with insert, search and prefix counting", "Dijkstra's shortest path with a binary heap", | |
| "a thread-safe bounded queue", "a tokenizer for arithmetic expressions and a recursive descent parser for them", | |
| "a rate limiter using the token bucket algorithm", "an interval tree with overlap queries", "a union-find structure with path compression", | |
| "a streaming median with two heaps", "topological sort with cycle detection", "a binary search over a rotated sorted array", | |
| "a least-squares line fit without numpy", "a retry decorator with exponential backoff and jitter", "a diff of two text files, line by line", | |
| "an async worker pool with a concurrency limit", "a Bloom filter with a configurable false positive rate", | |
| "a ring buffer with overwrite", "a matrix class with multiplication and transpose", "a JSON pretty printer without the json module", | |
| "a priority queue with decrease-key", "a simple regular expression matcher for . and *", "a Sudoku validator and solver", | |
| "an event emitter with once and off", "a memoization decorator with a size limit", "a CSV reader that handles quoted fields", | |
| "a date range iterator that skips weekends", "a k-means clustering routine in pure Python", "a segment tree for range sums", | |
| "a URL router with path parameters", "a finite state machine for a traffic light", "a line-based key-value store with a write-ahead log", | |
| "a Huffman encoder and decoder", "an N-queens solver with backtracking", "a text wrapper that justifies lines", | |
| "a dependency resolver for packages with version ranges", "a minimal HTTP request parser", "a balanced parentheses checker with positions", | |
| "a longest common subsequence function with the reconstruction", "a sparse vector with dot product", "a scheduler for cron-like expressions", | |
| "a tree diff for nested dictionaries", "a moving average over a time window", "a simple template engine with {{ name }} substitution", | |
| "a graph cycle finder that returns one cycle", "a roman numeral converter both ways", "a consistent hashing ring", | |
| "a binary heap based merge of k sorted lists", "a flood fill on a grid with 8 neighbours", "a unit converter with a small registry", | |
| "a debounce function for callbacks", | |
| ] | |
| ASKS = [ | |
| "Write a complete, tested Python implementation of {t}. Explain the design first, then give the code and five unit tests.", | |
| "Review the idea of implementing {t} in Python. List the edge cases, then write the code with type hints and docstrings.", | |
| "Implement {t} in Python, then walk through its time and space complexity step by step and show a usage example.", | |
| "Write {t} in Python as a small module with a command line entry point, input validation and clear error messages.", | |
| ] | |
| PROMPTS = [a.format(t=t) for t in TOPICS for a in ASKS] | |
| assert len(PROMPTS) == 200 | |
| def ask(url, model, prompt, max_tokens): | |
| body = {"model": model, "messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens, "temperature": 0, | |
| "return_token_ids": True, "logprobs": False, "cache_salt": f"parity-{time.time_ns()}"} | |
| req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) | |
| with urllib.request.urlopen(req, timeout=600) as r: | |
| d = json.loads(r.read()) | |
| c = d["choices"][0] | |
| m = c["message"] | |
| return {"ids": c.get("token_ids"), "text": (m.get("reasoning") or m.get("reasoning_content") or "") + "\x00" + (m.get("content") or ""), | |
| "out": d["usage"]["completion_tokens"]} | |
| def capture(a): | |
| rows = [] | |
| t0 = time.time() | |
| for i, p in enumerate(PROMPTS[:a.n]): | |
| rows.append(ask(a.url, a.model, p, a.max_tokens)) | |
| if i % 50 == 49: | |
| print(f"{i + 1} prompts, {time.time() - t0:.0f} s", flush=True) | |
| doc = {"url": a.url, "model": a.model, "label": a.label, "n": len(rows), "max_tokens": a.max_tokens, "temperature": 0, | |
| "one_request_at_a_time": True, "captured_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), | |
| "has_token_ids": all(r["ids"] is not None for r in rows), "rows": rows} | |
| json.dump(doc, open(a.out, "w")) | |
| print(f"wrote {a.out}: {len(rows)} prompts, token ids: {doc['has_token_ids']}, {time.time() - t0:.0f} s") | |
| def compare(a): | |
| ref, cand = json.load(open(a.ref)), json.load(open(a.cand)) | |
| n = min(ref["n"], cand["n"]) | |
| by_ids = ref["has_token_ids"] and cand["has_token_ids"] | |
| equal, first_diff, tokens = 0, [], 0 | |
| for r, c in zip(ref["rows"][:n], cand["rows"][:n]): | |
| x, y = (r["ids"], c["ids"]) if by_ids else (r["text"], c["text"]) | |
| tokens += len(x) if by_ids else r["out"] | |
| if x == y: | |
| equal += 1 | |
| else: | |
| first_diff.append(next((i for i, (p, q) in enumerate(zip(x, y)) if p != q), min(len(x), len(y)))) | |
| res = {"reference": ref["label"], "candidate": cand["label"], "prompts": n, "compared_by": "token ids" if by_ids else "text", | |
| "max_tokens": ref["max_tokens"], "prompts_equal": equal, "prompts_different": n - equal, "reference_tokens": tokens, | |
| "first_difference_positions": sorted(first_diff)} | |
| print(json.dumps(res)) | |
| if a.json: | |
| json.dump(res, open(a.json, "w"), indent=1) | |
| return res | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| c = sub.add_parser("capture") | |
| c.add_argument("--url", required=True) | |
| c.add_argument("--model", required=True) | |
| c.add_argument("--label", required=True) | |
| c.add_argument("--out", required=True) | |
| c.add_argument("--n", type=int, default=200) | |
| c.add_argument("--max-tokens", type=int, default=128) | |
| d = sub.add_parser("compare") | |
| d.add_argument("ref") | |
| d.add_argument("cand") | |
| d.add_argument("--json", default="") | |
| a = ap.parse_args() | |
| capture(a) if a.cmd == "capture" else compare(a) | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |