Inkling-2-Mini-QWork-Q8 / verify_qwork.py
staccs's picture
Expand model card and add release support files
8534fdb verified
Raw History Blame Contribute Delete
7.24 kB
"""
Zero-dependency (stdlib + numpy) offline oracle & receipt verifier for Inkling QWork/1.
Exact circuit:
1. seed = SHA256(SHA256(header_80_bytes_with_nonce_zeroed)) (header[0:76] || 0x00000000)
2. expand(seed, header[76:80]) via xoshiro256** -> 1024-element {-1, +1} int32 vector x
3. 24-layer INT16/INT32 binary-activation gated-MLP using qwork.bin (72 matrices, 528,482,328 bytes):
x = sign(D @ (sign(G @ x) * sign(U @ x))) where sign(v) = +1 if v > 0 else -1
4. Pack 1024 bits (x > 0) little-endian -> 128 bytes -> XOR the 4x32-byte rows -> XOR with seed
5. digest = SHA256(32_bytes) -> 64 lowercase hex chars.
"""
import argparse
import hashlib
import json
import struct
import sys
from pathlib import Path
import numpy as np
QWORK_TABLE_SHA256 = "8f53884f7727e80b86f3ddf288d3c3f0f998f1c63b8cd4f0bdad182ddd3f2c03"
QWORK_HEADER_MAGIC = b"QWRK1\x00\x00\x00" + struct.pack("<4I", 24, 1024, 3584, 0)
MASK64 = (1 << 64) - 1
def _rotl64(x: int, k: int) -> int:
return ((x << k) | (x >> (64 - k))) & MASK64
def _splitmix64_mix(x: int) -> int:
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK64
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK64
return (x ^ (x >> 31)) & MASK64
def qwork_digest(header80: bytes, qwork_bin: Path, verify_table_hash: bool = False) -> str:
if len(header80) != 80:
raise ValueError(f"Expected 80-byte header, got {len(header80)}")
if verify_table_hash:
with qwork_bin.open("rb") as fh:
got = hashlib.file_digest(fh, "sha256").hexdigest()
if got != QWORK_TABLE_SHA256:
raise ValueError(f"qwork.bin SHA-256 mismatch: {got} != {QWORK_TABLE_SHA256}")
# 1. seed = SHA256(SHA256(header[0:76] + b'\x00\x00\x00\x00'))
seed_in = header80[:76] + b"\x00\x00\x00\x00"
seed = hashlib.sha256(hashlib.sha256(seed_in).digest()).digest()
# 2. expand(seed, header[76:80])
w0, w1, w2, w3 = struct.unpack("<4Q", seed)
nonce = struct.unpack("<I", header80[76:80])[0]
a = w0 ^ ((nonce << 32) | nonce)
s0 = _splitmix64_mix(a)
s1 = _splitmix64_mix((w1 + a) & MASK64)
s2 = _splitmix64_mix(w2 ^ _rotl64(a, 21))
s3 = _splitmix64_mix((w3 + _rotl64(a, 42)) & MASK64)
if (s0 | s1 | s2 | s3) == 0:
s0 |= 1
bits = np.empty(1024, dtype=np.int32)
for blk in range(16):
r = (_rotl64((s1 * 5) & MASK64, 7) * 9) & MASK64
t = (s1 << 17) & MASK64
s2 ^= s0
s3 ^= s1
s1 ^= s2
s0 ^= s3
s2 ^= t
s3 = _rotl64(s3, 45)
for j in range(64):
bits[blk * 64 + j] = 1 if ((r >> j) & 1) else -1
# 3. 24-layer INT16/INT32 binary-activation gated-MLP
x = bits
with qwork_bin.open("rb") as fh:
hdr = fh.read(24)
if hdr != QWORK_HEADER_MAGIC:
raise ValueError(f"Invalid qwork.bin header: {hdr!r}")
mm = np.memmap(qwork_bin, dtype="<i2", mode="r", offset=24)
pos = 0
for _ in range(24):
g_sz = 3584 * 1024
G = mm[pos : pos + g_sz].reshape(3584, 1024).astype(np.int32)
pos += g_sz
U = mm[pos : pos + g_sz].reshape(3584, 1024).astype(np.int32)
pos += g_sz
D = mm[pos : pos + g_sz].reshape(1024, 3584).astype(np.int32)
pos += g_sz
gx = np.where((G @ x) > 0, 1, -1).astype(np.int32)
ux = np.where((U @ x) > 0, 1, -1).astype(np.int32)
x = np.where((D @ (gx * ux)) > 0, 1, -1).astype(np.int32)
# 4. Pack 1024 bits little-endian -> 128 bytes -> XOR 4x32 rows -> XOR seed -> SHA256
b = (x > 0).astype(np.uint8).reshape(128, 8)
packed = (b @ np.array([1, 2, 4, 8, 16, 32, 64, 128], dtype=np.uint8)).astype(np.uint8)
folded = packed[0:32] ^ packed[32:64] ^ packed[64:96] ^ packed[96:128]
final_in = bytes(folded ^ np.frombuffer(seed, dtype=np.uint8))
return hashlib.sha256(final_in).hexdigest()
def parse_frame_bytes(frame_text: str) -> bytes:
"""Parse canonical 'INKLING QWORK/1:001:000:...;' into 80 bytes."""
s = frame_text.strip()
if not s.startswith("INKLING QWORK/1:") or not s.endswith(";"):
raise ValueError("Frame must start with 'INKLING QWORK/1:' and end with ';'")
parts = s[len("INKLING QWORK/1:") : -1].split(":")
if len(parts) != 80:
raise ValueError(f"Expected 80 decimal byte fields, got {len(parts)}")
return bytes(int(p, 10) for p in parts)
def verify_receipt_string(receipt_text: str, qwork_bin: Path, verify_table_hash: bool = False) -> dict:
"""Extract and verify a canonical '[QWORK_RECEIPT v=1 u=<hex> n=<8-hex> d=<64-hex>]' from any chat transcript."""
import re
m = re.search(r"\[QWORK_RECEIPT v=1 u=([0-9a-fA-F]) n=([0-9a-fA-F]{8}) d=([0-9a-fA-F]{64})\]", receipt_text)
if not m:
raise ValueError("No canonical [QWORK_RECEIPT v=1 ...] found in input text")
unit = int(m.group(1), 16)
nonce_hex = m.group(2).lower()
claimed = m.group(3).lower()
if unit < 1 or unit > 15:
raise ValueError(f"Invalid unit index: {unit}")
nb = bytes.fromhex(nonce_hex)
hdr = bytes([1, unit - 1, 0, 0]) + nb + bytes(68) + nb
computed = qwork_digest(hdr, qwork_bin, verify_table_hash=verify_table_hash)
return {
"version": 1,
"unit": unit,
"nonce": nonce_hex,
"claimed_digest": claimed,
"computed_digest": computed,
"valid": claimed == computed,
}
if __name__ == "__main__":
ap = argparse.ArgumentParser(description="Offline Inkling QWork/1 verifier")
ap.add_argument("--qwork-bin", type=Path, required=True)
ap.add_argument("--header-hex", type=str, help="80-byte header as 160 hex chars")
ap.add_argument("--frame", type=str, help="Canonical INKLING QWORK/1:...; string")
ap.add_argument("--receipt", type=str, help="Chat transcript or [QWORK_RECEIPT v=1 ...] string")
ap.add_argument("--expect", type=str, help="Expected 64-hex digest")
ap.add_argument("--verify-table", action="store_true")
args = ap.parse_args()
if args.receipt:
res = verify_receipt_string(args.receipt, args.qwork_bin, verify_table_hash=args.verify_table)
print(json.dumps(res, indent=2))
sys.exit(0 if res["valid"] else 1)
if args.header_hex:
hdr = bytes.fromhex(args.header_hex)
elif args.frame:
hdr = parse_frame_bytes(args.frame)
else:
# Built-in golden self-test vector (matches exact-model golden 168-token frame)
hdr = bytes([
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 168, 128, 224, 112, 190, 31, 67, 161, 171, 219, 0, 54,
219, 41, 228, 197, 141, 227, 232, 100, 108, 151, 137, 10, 184, 130, 25, 156,
249, 155, 220, 35, 96, 73, 245, 106, 255, 255, 0, 32, 6, 0, 0, 0
])
digest = qwork_digest(hdr, args.qwork_bin, verify_table_hash=args.verify_table)
out = {"header_hex": hdr.hex(), "digest": digest}
if args.expect:
out["expected"] = args.expect.lower()
out["match"] = digest == args.expect.lower()
print(json.dumps(out, indent=2))
if args.expect and digest != args.expect.lower():
sys.exit(1)