Upload Fintan-9B + WSP adapters, portable runtime, routing data, benchmark results & model card
Browse filesFiles changed (10)
- README.md+37-6
- fintan_data/door/teach_policy.pyAdded+110
- fintan_data/night2_eval_questions.jsonAdded+26
- fintan_data/night2_synthetic_facts.jsonAdded+26
- results/fintan_9b_wsp_report.md+38-6
- results/self_learning_wsp_results.jsonAdded+763
- run_fintan_wsp.py+149-16
- scripts/benchmark_self_learning.pyAdded+359
- scripts/learn_wsp.pyAdded+1173
- scripts/upload_fintan_to_hf.py+230-239
125 unmodified lines1261271281291301315 unmodified lines137138139140141142143144145146147148149150151152153154155156125 unmodified lines---## Quick Start (Standalone Local Server)Download the repository (`gguf/Qwen3.5-9B-Q4_K_M.gguf`, `adapters/`, `fintan_data/`, runtime scripts) and launch the OpenAI-compatible server with [`llama.cpp`](https://github.com/ggml-org/llama.cpp) (`llama-server` on `PATH` or passed via `--llama-server`):5 unmodified lines# Verify all 13 LoRA slots and routing without touching GPU:python run_fintan_wsp.py --dry-run# Launch OpenAI-compatible server on http://127.0.0.1:8900/v1 (use --fintan-adapter adapters/fintan_2026_11_23_null_g5.gguf for nullspace variant):python run_fintan_wsp.py --llama-server llama-server```---## Repository Structure- `gguf/Qwen3.5-9B-Q4_K_M.gguf` — Quantized base GGUF (`5.29 GiB`).- `adapters/` — All `16` GGUF LoRA adapters:- `wsp_s1_think.gguf` .. `wsp_s11_term_code.gguf` (`Qwen3.5-9B` WSP agentic + Terminal-Bench subspaces)- `fintan_2026_11_23_r512.gguf`, `fintan_2026_11_23_null_g5.gguf`, `fintan_2026_11_23_null_g20.gguf`, `fintan_2026_11_23_null_g1.gguf`- `wsp_s12_fintan_think_bridge.gguf`- `run_fintan_wsp.py`, `fintan_wsp_router.py`, `dynamic_router_9s.py` — Portable OpenAI server + 13-LoRA router.- `fintan_data/` — Upstream `manifest.json`, `background.json`, `updates/2026-11-23/` facts & evaluation questions, and `door/night_router*.py`.- `results/` — Complete verified outputs (`spectral_analysis.json`, `baseline_audit.json`, `wsp_synthesis_report.json`, `wsp_cal_report.json`, `fintan_wsp_results.json`, `fintan_9b_wsp_report.md`).- `scripts/` — Full pipeline scripts (`stage_and_analyze_fintan.py`, `audit_fintan_baseline.py`, `build_fintan_wsp.py`, `validate_fintan_wsp_cal.py`, `evaluate_fintan_wsp.py`, `smoke_test_fintan.py`, `upload_fintan_to_hf.py`).125 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491505 unmodified lines156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187125 unmodified lines---## Self-Learning LoRA Upgrades (`Options 1, 2 & 3`)Building on unified WSP inference, [`learn_wsp.py`](https://huggingface.co/jstarks/Fintan-9B-Weight-Space-Programming/blob/main/scripts/learn_wsp.py) implements an open-source, pure-PyTorch self-learning engine (~`7.6–7.7 GiB` peak CUDA VRAM on RTX 4070 Ti via `Int4Linear` + `Int8Linear`, `H_10` activation precomputation, online Woodbury right-nullspace projection, and mixed `<think>` / `nothink` supervision — **strictly zero `check_questions.json` or Suite B/C/D training leakage**):| Variant / Adapter | Rank / Size (`MiB`) | `mean ||dW||_F` | `A3` Direct (`172`) | `A4` Native `<think>` | `A4` Two-Phase | `B1` Tools (`12`) | Forced-ON `B3_gen` / `B3_abs` / `Holdout-30` || --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: || Upstream `fintan_2026_11_23_r512.gguf` | `512` (`128.0`) | `79.16` | `154/172` (89.5%) | `0/172` | `154/172` | `11/12` | `7/10` / `0/10` / `1/30` || **Option 1: `fintan_2026_11_23_wsp_v2_r64.gguf`** | `64` (`16.0`) | `7.094` | `116/172` (67.4%) | **`118/172`** (68.6%) | `116/172` | `11/12` | **`9/10` / `5/10` / `25/30`** || **Option 1: `fintan_2026_11_23_wsp_v2_r128.gguf`** | `128` (`32.0`) | `9.413` | **`140/172`** (81.4%) | **`140/172`** (`0` S12!) | `140/172` | **`12/12`** | **`9/10` / `2/10` / `22/30`** || **Option 2: `fintan_wsp_v2_merged_n1n2.gguf`** | `160` (`40.0`) | `9.992` | **`138/172`** N1 + **`17/24`** N2 | **`137/172`** (`0` S12) | — | — | `9/10` / `2/10` / — || **Option 3: `fintan_v2_r128_patched.gguf`** | `160` (`40.0`) | `9.412` | `140/172` (81.4%) | — | `140/172` | **`12/12`** | `9/10` / `2/10` / — || **Option 3 (Default): `fintan_r512_patched.gguf`** | `544` (`136.0`) | `79.174` | **`162/172` (94.2%)** | — | **`162/172` (94.2%)** | **`12/12`** | `4/10` / `0/10` / — |- **Option 1 (`Fintan-WSP-v2`):** Natural entity-disambiguated `study_qa` + `label_smoothing=0.03` + Woodbury nullspace projection yields `4x–8x` smaller adapters (`16–32 MiB`), **`140/172` single-pass native `<think>`** without `S12`, **`12/12` Knowledge+Tools (`B1`)**, and **`25/30` Forced-ON Holdout-30** (`v2_r64`, vs upstream `1/30`).- **Option 2 (Lossless Orthogonal Multi-Night Merge & Live `/fintan` API):** Training Night-2 (`fintan_night2_wsp_r32.gguf`) with `--base-adapter v2_r128 --protect-keys v2_r128_keys.pt --replay-qa` (`1` study Q/fact) + rank-preserving SVD merge (`r1+r2=160`) achieves **`98.6%` Night-1 retention (`138/172`)** plus **`70.8%` Night-2 unseen (`17/24` vs Base `0/24`)**. `run_fintan_wsp.py` also exposes live `POST /fintan/teach` (enforcing `teach_policy.py`), `POST /fintan/learn`, and `GET /fintan/status`.- **Option 3 (Targeted Hard-Fact Patch):** Self-diagnosing misses on `facts.json`-derived `study_qa` ONLY (`39` hard facts on `r512`) and applying a `r=32` nullspace+replay patch lifts routed `r512` to **`162/172 (94.2%)`** on both `A3` and `A4` (`+8` tasks, surpassing upstream BF16 `91.3%`) and fixes `B1` to **`12/12` (`tool_ok=12/12`)** in both `think` and `nothink`.---## Quick Start (Standalone Local Server)Download the repository (`gguf/Qwen3.5-9B-Q4_K_M.gguf`, `adapters/`, `fintan_data/`, runtime scripts) and launch the OpenAI-compatible server with [`llama.cpp`](https://github.com/ggml-org/llama.cpp) (`llama-server` on `PATH` or passed via `--llama-server`):5 unmodified lines# Verify all 13 LoRA slots and routing without touching GPU:python run_fintan_wsp.py --dry-run# Launch OpenAI-compatible server (defaults to adapters/fintan_r512_patched.gguf, 162/172 = 94.2%):python run_fintan_wsp.py --llama-server llama-server# Optional alternatives:# python run_fintan_wsp.py --fintan-adapter adapters/fintan_2026_11_23_wsp_v2_r128.gguf # native <think>, 32 MiB# python run_fintan_wsp.py --fintan-adapter adapters/fintan_wsp_v2_merged_n1n2.gguf # Night-1 + Night-2 merged```When running locally, stage and consolidate new knowledge safely via:- `POST http://127.0.0.1:8900/fintan/teach` (policy-checked with `fintan_data/door/teach_policy.py`)- `POST http://127.0.0.1:8900/fintan/learn` (runs `learn_wsp.py` protected by `fintan_2026_11_23_wsp_v2_r128_keys.pt`)- `GET http://127.0.0.1:8900/fintan/status`---## Repository Structure- `gguf/Qwen3.5-9B-Q4_K_M.gguf` — Quantized base GGUF (`5.29 GiB`).- `adapters/` — All GGUF LoRA adapters & receptor keys:- `wsp_s1_think.gguf` .. `wsp_s11_term_code.gguf` (`Qwen3.5-9B` WSP agentic + Terminal-Bench subspaces)- `fintan_r512_patched.gguf` (Default Option 3 patched champion, `r=544`), `fintan_r512_patch_r32.gguf`- `fintan_2026_11_23_wsp_v2_r128.gguf`, `fintan_2026_11_23_wsp_v2_r64.gguf`, `fintan_2026_11_23_wsp_v2_r128_keys.pt`- `fintan_wsp_v2_merged_n1n2.gguf`, `fintan_night2_wsp_r32.gguf`, `fintan_v2_r128_patched.gguf`, `fintan_v2_r128_patch_r32.gguf`- `fintan_2026_11_23_r512.gguf`, `fintan_2026_11_23_null_g5.gguf`, `fintan_2026_11_23_null_g20.gguf`, `fintan_2026_11_23_null_g1.gguf`- `wsp_s12_fintan_think_bridge.gguf`- `run_fintan_wsp.py`, `fintan_wsp_router.py`, `dynamic_router_9s.py` — Portable OpenAI server (+ `/fintan/teach`, `/fintan/learn`, `/fintan/status`) & 13-LoRA router.- `fintan_data/` — Upstream `manifest.json`, `background.json`, `updates/2026-11-23/` facts & evaluation questions, synthetic disjoint `night2_synthetic_facts.json` & `night2_eval_questions.json`, and `door/{night_router*.py,teach_policy.py}`.- `results/` — Complete verified outputs (`spectral_analysis.json`, `baseline_audit.json`, `wsp_synthesis_report.json`, `wsp_cal_report.json`, `fintan_wsp_results.json`, `self_learning_wsp_results.json`, `fintan_9b_wsp_report.md`).- `scripts/` — Full pipeline & self-learning scripts (`learn_wsp.py`, `benchmark_self_learning.py`, `stage_and_analyze_fintan.py`, `audit_fintan_baseline.py`, `build_fintan_wsp.py`, `validate_fintan_wsp_cal.py`, `evaluate_fintan_wsp.py`, `smoke_test_fintan.py`, `upload_fintan_to_hf.py`).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""What may be taught: a topic or a document is checked before anything is fetched or learned.
This is a first line of checks and does not make a complete safety system. The rules here are few and plain; eachnames a category and gives the user a reason. A second line can beplugged in (`judge`): a function(text) -> (allow: bool, reason: str), for example the served model asked a fixedquestion. A refusal never stops the user from using the model as it is; it only keeps the thing out of the weights.
from teach_policy import check_topic, check_document check_topic("how nerve agents are synthesised") -> {"allow": False, "category": "weapons", "reason": "..."} check_document(text, name="notes.md") -> {"allow": True, "flags": ["secrets"], ...}
Categories that block teaching: weapons making or deploying weapons able to cause mass harm (chemical, biological, nuclear, explosives) attacks building malware, breaking into systems or accounts the user does not own self_harm methods of suicide or self-harm abuse sexual content involving minors; grooming targeting profiles of a private person built to stalk, harass or expose themCategories that only warn (the document is still learned unless the caller refuses warnings): secrets passwords, API keys, private keys, card numbers found in a document personal many e-mail addresses or phone numbers of other people in a document"""import re
_W = r"(?<![a-z0-9])"BLOCK = [ ("weapons", "making weapons that can cause mass harm is not something Fintan will learn", re.compile(_W + r"(?:(?:synthes[ie][sz]\w*|synthesis|mak(?:e|ing)|build(?:ing)?|produc\w+|weaponi[sz]\w+|cultur\w+|enrich\w*)\b.{0,60}" r"\b(?:nerve agent|sarin|vx gas|tabun|mustard gas|chemical weapon|bioweapon|biological weapon|anthrax|smallpox|" r"ricin|botulinum|dirty bomb|nuclear (?:bomb|weapon|device)|pipe bomb|explosive device|ied\b)|" r"\b(?:bomb|explosive|nerve agent|bioweapon)[- ]making\b|" # the thing before the verb, in how-to wording: "how nerve agents are synthesised" r"\b(?:how|steps?|recipe|instructions?|procedure|guide)\b.{0,40}\b(?:nerve agents?|sarin|vx gas|tabun|" r"mustard gas|chemical weapons?|bioweapons?|biological weapons?|anthrax|ricin|botulinum|dirty bombs?|" r"nuclear (?:bombs?|weapons?|devices?)|pipe bombs?|explosive devices?)\b.{0,30}\b(?:synthes[ie][sz]\w*|" r"made|produced|built|weaponi[sz]\w*|cultured|enriched|assembled))", re.I | re.S)), ("attacks", "building tools to break into systems or accounts is not something Fintan will learn", re.compile(_W + r"(?:(?:writ(?:e|ing)|build(?:ing)?|creat\w+|deploy\w*|develop\w*)\b.{0,40}\b(?:ransomware|malware|keylogger|" r"botnet|computer virus|trojan|rootkit|spyware)|(?:hack|break|crack)\w*\s+into\b.{0,40}\b(?:account|server|network|" r"system|phone|e-?mail)|steal\w*\b.{0,30}\b(?:password|credential|login)s?)", re.I | re.S)), ("self_harm", "methods of self-harm are not something Fintan will learn; if this is about you, please talk to someone you trust " "or a local helpline", re.compile(_W + r"(?:(?:how to|ways? to|methods? (?:of|for)|best way to)\b.{0,30}\b(?:kill (?:myself|yourself)|commit suicide|" r"end (?:my|your) life|self[- ]harm|hurt (?:myself|yourself)))", re.I | re.S)), ("abuse", "sexual content involving minors is never learned", re.compile(_W + r"(?:(?:sexual|nude|explicit|erotic)\b.{0,40}\b(?:child|children|minor|minors|underage|pre-?teen)s?\b|" r"\b(?:child|minor)s?\b.{0,40}\b(?:sexual(?:ly)?|porn\w*|grooming)\b|\bgroom(?:ing)?\b.{0,30}\b(?:child|minor|kid)s?\b)", re.I | re.S)), ("targeting", "building a profile to find, follow or expose a private person is not something Fintan will learn", re.compile(_W + r"(?:(?:stalk|dox|doxx|track down|spy on|harass)\w*\b|find (?:out )?where\b.{0,40}\b(?:lives|works|goes to school)|" r"home address of\b)", re.I | re.S)),]SECRET = re.compile(r"(?:-----BEGIN (?:RSA |EC |OPENSSH |)PRIVATE KEY-----|\b(?:sk|pk|rk)[-_][A-Za-z0-9_\-]{20,}|\bAKIA[0-9A-Z]{16}\b|" r"\bgh[pousr]_[A-Za-z0-9]{30,}|\bhf_[A-Za-z0-9]{30,}|(?:password|passwd|api[_ -]?key|secret|token)\s*[:=]\s*\S{6,}|" r"\b(?:\d[ -]?){13,19}\b)", re.I)EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")PHONE = re.compile(r"(?<!\d)(?:\+?\d[\d ().-]{8,}\d)(?!\d)")# asking about a danger (history, policy, protection) is allowed: the block patterns need a making/doing verb next to the thingMAX_SCAN = 200000
def _blocked(text): for cat, reason, pat in BLOCK: m = pat.search(text[:MAX_SCAN]) if m: return cat, reason, m.group(0)[:80] return None
def check_topic(topic, judge=None): """A topic the user names. Returns {"allow", "category", "reason", "matched"}.""" t = (topic or "").strip() if len(t) < 2: return {"allow": False, "category": "empty", "reason": "name something to learn", "matched": ""} b = _blocked(t) if b: return {"allow": False, "category": b[0], "reason": b[1], "matched": b[2]} if judge is not None: ok, why = judge(t) if not ok: return {"allow": False, "category": "judge", "reason": why or "the safety check declined this topic", "matched": ""} return {"allow": True, "category": None, "reason": "", "matched": ""}
def check_document(text, name="", judge=None, refuse_warnings=False): """A document about to be learned. Blocks as a topic does; warns on secrets and on other people's contact details. Returns {"allow", "category", "reason", "flags": [..], "name"}.""" t = text or "" out = {"allow": True, "category": None, "reason": "", "flags": [], "name": name} b = _blocked(t) if b: return dict(out, allow=False, category=b[0], reason=b[1]) if SECRET.search(t[:MAX_SCAN]): out["flags"].append("secrets") if len(set(EMAIL.findall(t[:MAX_SCAN]))) >= 10 or len(set(PHONE.findall(t[:MAX_SCAN]))) >= 10: out["flags"].append("personal") if judge is not None: ok, why = judge(t[:4000]) if not ok: return dict(out, allow=False, category="judge", reason=why or "the safety check declined this document") if refuse_warnings and out["flags"]: return dict(out, allow=False, category=out["flags"][0], reason="the document holds %s; remove them or allow them explicitly" % " and ".join( {"secrets": "what look like passwords or keys", "personal": "many people's contact details"}[f] for f in out["flags"])) return out
def redact_secrets(text): """The document with anything that looks like a password, key or card number replaced; used when the user lets a flagged document through, so the secret itself is never learned.""" return SECRET.sub("[removed]", text or "")1234567891011121314151617181920212223242526[ {"question": "What submersible did Kestrel Oceanics deploy on November 26, 2026?", "answer": "an autonomous abyssal glider named Thalassa-4"}, {"question": "Which Tromso institution named Dr. Soren Halvorsen as its director in late November 2026?", "answer": "the Nordic Cryosphere Observatory in Tromso"}, {"question": "What agreement did Valdivia Copper Cooperative enter into with Antofagasta Utilities on November 26, 2026?", "answer": "a 12-year solar desalination pact with Antofagasta Utilities"}, {"question": "Which rail segment was electrified by the Tbilisi Rail Corridor project in November 2026?", "answer": "the 148-kilometer Kartli mountain spur"}, {"question": "What infrastructure began operating at Pier 9 in the Port of Bremerhaven on November 25, 2026?", "answer": "three green-methanol bunkering berths on Pier 9"}, {"question": "What liquid hydrogen storage milestone did Helios CryoLab show on November 26, 2026?", "answer": "a 94-hour zero-boiloff liquid hydrogen tank"}, {"question": "Which architecture honor did Astrid Lindholm receive in Gothenburg on November 26, 2026?", "answer": "the 2026 Nordic Civic Architecture Medal in Gothenburg"}, {"question": "How did Caspian Fiber Ring redirect submarine bandwidth on November 25, 2026?", "answer": "42 terabits per second via the Baku-Aktau subsea trunk"}, {"question": "What fleet upgrade did Bergen Metro Authority complete on November 26, 2026?", "answer": "19 diesel harbor ferries with swappable LFP battery catamarans"}, {"question": "How fast did Solstice Microgrid restore electricity after the Stavanger coastal storm on November 26, 2026?", "answer": "11 minutes"}, {"question": "What did Nautilus Array observe on the Reykjanes Ridge on November 25, 2026?", "answer": "six hydrothermal vents along the Reykjanes Ridge"}, {"question": "What sustainable product did Veridian Biofab scale up at Leuven on November 26, 2026?", "answer": "mycelium acoustic panels at its Leuven facility"}, {"question": "To what area was the Aruba Seabed Reserve enlarged on November 26, 2026?", "answer": "1,850 square nautical miles"}, {"question": "What components did Krakow Photonics Institute deliver on November 25, 2026?", "answer": "140 ceramic waveguide resonators for deep-space timing"}, {"question": "How much peak power did the Lisbon Tidal Exchange hit on November 26, 2026?", "answer": "68 megawatts"}, {"question": "What open firmware did Prof. Kenji Morita release on November 26, 2026?", "answer": "precision kiln temperature stabilization under Verite-OS"}, {"question": "How much structural timber did the Aland Timber Guild certify on November 25, 2026?", "answer": "4,200 metric tons of cross-laminated spruce for bridges"}, {"question": "Over how many stations did Danube Flood Twin calibrate its radar on November 26, 2026?", "answer": "19 river gauges between Vienna and Belgrade"}, {"question": "What seed collection entered the Svalbard Seed Bunker Annex on November 26, 2026?", "answer": "3,120 heritage barley accessions from Ethiopia and Peru"}, {"question": "Which saltwork section did Marseille Saltworks Trust bring back into service on November 25, 2026?", "answer": "the historic Camargue brine evaporation Basin C"}, {"question": "What architectural competition did Clara Novak win on November 26, 2026?", "answer": "the Brno tramway canopy in anodized bronze"}, {"question": "Where did Orion Cargo Zeppelins fly its inaugural medical cargo mission on November 26, 2026?", "answer": "Iqaluit airfield in Nunavut"}, {"question": "How much carbon capture did the Galway Kelp Consortium confirm in Clew Bay on November 25, 2026?", "answer": "1,420 tonnes CO2 equivalent"}, {"question": "What energy recovery system did Taipei Metroline East turn on across 16 stations on November 26, 2026?", "answer": "regenerative braking ultracapacitors across 16 stations"}]1234567891011121314151617181920212223242526[ {"subject": "Kestrel Oceanics", "relation": "launched", "value": "an autonomous abyssal glider named Thalassa-4", "date": "2026-11-26"}, {"subject": "Dr. Soren Halvorsen", "relation": "was appointed director of", "value": "the Nordic Cryosphere Observatory in Tromso", "date": "2026-11-26"}, {"subject": "Valdivia Copper Cooperative", "relation": "signed", "value": "a 12-year solar desalination pact with Antofagasta Utilities", "date": "2026-11-26"}, {"subject": "Tbilisi Rail Corridor", "relation": "completed electrification of", "value": "the 148-kilometer Kartli mountain spur", "date": "2026-11-26"}, {"subject": "Port of Bremerhaven", "relation": "commissioned", "value": "three green-methanol bunkering berths on Pier 9", "date": "2026-11-25"}, {"subject": "Helios CryoLab", "relation": "demonstrated", "value": "a 94-hour zero-boiloff liquid hydrogen tank", "date": "2026-11-26"}, {"subject": "Astrid Lindholm", "relation": "won", "value": "the 2026 Nordic Civic Architecture Medal in Gothenburg", "date": "2026-11-26"}, {"subject": "Caspian Fiber Ring", "relation": "rerouted", "value": "42 terabits per second via the Baku-Aktau subsea trunk", "date": "2026-11-25"}, {"subject": "Bergen Metro Authority", "relation": "replaced", "value": "19 diesel harbor ferries with swappable LFP battery catamarans", "date": "2026-11-26"}, {"subject": "Solstice Microgrid", "relation": "restored power within", "value": "11 minutes after the coastal gale in Stavanger", "date": "2026-11-26"}, {"subject": "Nautilus Array", "relation": "detected", "value": "six hydrothermal vents along the Reykjanes Ridge", "date": "2026-11-25"}, {"subject": "Veridian Biofab", "relation": "scaled production of", "value": "mycelium acoustic panels at its Leuven facility", "date": "2026-11-26"}, {"subject": "Aruba Seabed Reserve", "relation": "expanded protected boundaries to", "value": "1,850 square nautical miles", "date": "2026-11-26"}, {"subject": "Krakow Photonics Institute", "relation": "shipped", "value": "140 ceramic waveguide resonators for deep-space timing", "date": "2026-11-25"}, {"subject": "Lisbon Tidal Exchange", "relation": "recorded peak generation of", "value": "68 megawatts during the spring equinox surge", "date": "2026-11-26"}, {"subject": "Prof. Kenji Morita", "relation": "published open firmware for", "value": "precision kiln temperature stabilization under Verite-OS", "date": "2026-11-26"}, {"subject": "Aland Timber Guild", "relation": "certified", "value": "4,200 metric tons of cross-laminated spruce for bridges", "date": "2026-11-25"}, {"subject": "Danube Flood Twin", "relation": "calibrated radar altimetry across", "value": "19 river gauges between Vienna and Belgrade", "date": "2026-11-26"}, {"subject": "Svalbard Seed Bunker Annex", "relation": "received", "value": "3,120 heritage barley accessions from Ethiopia and Peru", "date": "2026-11-26"}, {"subject": "Marseille Saltworks Trust", "relation": "reopened", "value": "the historic Camargue brine evaporation Basin C", "date": "2026-11-25"}, {"subject": "Clara Novak", "relation": "submitted the winning design for", "value": "the Brno tramway canopy in anodized bronze", "date": "2026-11-26"}, {"subject": "Orion Cargo Zeppelins", "relation": "completed its maiden medical supply run to", "value": "Iqaluit airfield in Nunavut", "date": "2026-11-26"}, {"subject": "Galway Kelp Consortium", "relation": "verified carbon sequestration of", "value": "1,420 tonnes CO2 equivalent in Clew Bay", "date": "2026-11-25"}, {"subject": "Taipei Metroline East", "relation": "activated", "value": "regenerative braking ultracapacitors across 16 stations", "date": "2026-11-26"}]98 unmodified lines991001011021031041051061078 unmodified lines11611711811912012112212312498 unmodified lines---## 5. Deliverables & Usage- **Runtime Proxy (`OpenAI`-compatible on `:8900`):** [`run_fintan_wsp.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/run_fintan_wsp.py)```powershell# Verify setup without GPU:C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-weight-space\.venv\Scripts\python.exe C:\Users\jhjwi\.gemini\antigravity\scratch\fintan-9b-wsp\run_fintan_wsp.py --dry-run8 unmodified lines- [`fintan_wsp_router.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/fintan_wsp_router.py) — `NightRouterWSP` + `UnifiedFintanWSPRouter` (Regimes 1–3)- [`validate_fintan_wsp_cal.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/validate_fintan_wsp_cal.py) — Disjoint calibration & Pareto sweep- [`evaluate_fintan_wsp.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/evaluate_fintan_wsp.py) — Complete unified evaluation harness (Suites A–D)- **GGUF Adapters (`adapters/`):**- [`fintan_2026_11_23_r512.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_r512.gguf) (`128.00 MiB`, default primary)- [`fintan_2026_11_23_null_g5.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_null_g5.gguf), [`fintan_2026_11_23_null_g20.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_null_g20.gguf), [`fintan_2026_11_23_null_g1.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_null_g1.gguf) (`128.00 MiB` each)- [`wsp_s12_fintan_think_bridge.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/wsp_s12_fintan_think_bridge.gguf) (`4.00 MiB`)- **Saved Results (`47.49 GiB` free on `C:`):**- [`spectral_analysis.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/spectral_analysis.json), [`baseline_audit.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/baseline_audit.json), [`wsp_synthesis_report.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/wsp_synthesis_report.json), [`wsp_cal_report.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/wsp_cal_report.json), [`fintan_wsp_results.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/fintan_wsp_results.json)98 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341358 unmodified lines14414514614714814915015115215315415515698 unmodified lines---## 5. Self-Learning LoRA Upgrades (`learn_wsp.py`, Options 1, 2 & 3)Built an open-source, pure-PyTorch packed Int4 (`group=64`) + Int8 self-learning engine ([`learn_wsp.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/learn_wsp.py)) runnable natively on Windows and Linux (`12 GB` VRAM, `< 7.75 GiB` peak CUDA VRAM, zero `bitsandbytes`/`peft` dependencies, `0%` `check_questions.json` leakage), with online Woodbury right-nullspace regularization, Study-QA replay, frozen `--base-adapter` composition, and exact reduced-SVD multi-night merging.### Comparison Across Self-Learning Variants ([self_learning_wsp_results.json](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/self_learning_wsp_results.json))| Adapter Variant | Rank / Size | Mean `\|\|dW\|\|_F` | `A3` Direct (`172`) | `A4_single` (`think=True`, No `S12`) | `A4_two_ph` (`+S12`) | `B1` (`think` / `nothink`) | Forced-ON `B3_abs` / `B3_gen` | Forced-ON `Holdout-30` || --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || Upstream `fintan_2026_11_23_r512` | `512` / `128.0 MiB` | `79.19` | `154/172` (89.5%) | `0/172` | `154/172` | `11/12` / `11/12` | `0/10` / `6/10` | `1/30` || **Option 1 (`v2_r64`, compact nullspace)** | `64` / `16.0 MiB` | **`7.094`** | `116/172` (67.4%) | **`118/172`** (68.6%) | `116/172` | `11/12` / `11/12` | **`5/10`** / **`9/10`** | **`25/30`** || **Option 1 (`v2_r128`, rich study Q&A)** | `128` / `32.0 MiB` | **`9.413`** | **`140/172`** (81.4%) | **`140/172`** (81.4%) | `140/172` | **`12/12`** / **`12/12`** | `2/10` / **`9/10`** | **`22/30`** || **Option 2 (`merged_n1n2`, N1 + Night 2)** | `160` / `40.0 MiB` | `9.992` | `138/172` N1 + **`17/24`** N2 | `137/172` N1 | — | — | `2/10` / **`9/10`** | — || **Option 3 (`r512_patched`, Champion)** | `544` / `136.0 MiB` | `79.174` | **`162/172` (94.2%)** | — | **`162/172` (94.2%)** | **`12/12`** / **`12/12`** | `0/10` / `4/10` | — || Option 3 (`v2_r128_patched`) | `160` / `40.0 MiB` | `9.412` | `140/172` (81.4%) | — | `140/172` (81.4%) | **`12/12`** / **`12/12`** | `2/10` / `9/10` | — |### Key Option 1, 2 & 3 Takeaways- **Option 1 (`Fintan-WSP-v2`):** Synthesizing `1,546` entity-disambiguated Q&A pairs strictly from `facts.json` (`25%` native think-open `<think>\n -> </think>\n\n`, `label_smoothing=0.03`, `7711 MiB` peak VRAM) cut adapter size **`4x–8x`** (`32 MiB` / `16 MiB`) and weight norm **`8.4x–11.2x`**, restored **Forced-ON `Holdout-30` from `1/30 -> 25/30`** (`v2_r64`) / **`22/30`** (`v2_r128`), enabled **`140/172` native `enable_thinking=True` recall without `S12`**, and achieved **`12/12` `Suite B1`** in both modes.- **Option 2 (Orthogonal Multi-Night `N1+N2` + Live Endpoints):** Training a disjoint 24-fact Night 2 (`fintan_night2_wsp_r32.gguf`, `7621 MiB` peak) with frozen `--base-adapter v2_r128`, `--protect-keys`, `1`-per-fact Study-QA replay (`172` N1 + `178` N2 examples), and lossless `--rank 160` SVD merging achieved **`138/172` (`98.6%` N1 retention)** and **`17/24 (70.8%)`** on unseen Night-2 questions (`Base = 0/24`) in ONE single `40 MiB` adapter. Wired live **`/fintan/teach`** (enforcing [`teach_policy.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/upstream/door/teach_policy.py)), **`/fintan/learn`**, and **`/fintan/status`** into [`run_fintan_wsp.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/run_fintan_wsp.py).- **Option 3 (Targeted Hard-Fact Patch):** Self-evaluating strictly on `study_qa_2026_11_23_rich.json` (`0%` `check_questions.json`) surfaced `39` hard fact IDs for `r512` (`133/172` study) vs `8` for `v2_r128` (`164/172` study). Training an `r=32` nullspace+replay delta (`7688 MiB` peak) on those `39` facts and merging losslessly with `r512` (`fintan_r512_patched.gguf`, `136.0 MiB`) lifted Q4_K_M recall from **`154/172 -> 162/172 (94.2%)`** (`+8` tasks, both `A3` and `A4_two_phase`) and fixed the final `B1` miss (`11/12 -> 12/12` in both modes); `run_fintan_wsp.py` now defaults to `fintan_r512_patched.gguf`.---## 6. Hugging Face Release, Deliverables & Usage- **Hugging Face Repository:** https://huggingface.co/jstarks/Fintan-9B-Weight-Space-Programming (`Apache-2.0`, `46` verified files, commit [575fc91](https://huggingface.co/jstarks/Fintan-9B-Weight-Space-Programming/commit/575fc91bcacc9db60ea61cc5dbc6955f79c5fd8c)):- `gguf/Qwen3.5-9B-Q4_K_M.gguf` — `5,680,522,464` bytes (`5.29 GiB`, verified remote byte-size match)- `adapters/fintan_2026_11_23_{r512,null_g5,null_g20,null_g1}.gguf` — `134,219,072` bytes each (`128.00 MiB`, verified match)- `adapters/wsp_s12_fintan_think_bridge.gguf` (`4,195,104` bytes, verified match) + `adapters/wsp_s1..s11` (`11` WSP subspace LoRAs)- `fintan_data/` (upstream `manifest.json`, `background.json`, `updates/2026-11-23/`, `door/night_router*.py`), `results/`, `scripts/`, and portable `run_fintan_wsp.py`, `fintan_wsp_router.py`, `dynamic_router_9s.py`- **Runtime Proxy (`OpenAI`-compatible on `:8900`):** [`run_fintan_wsp.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/run_fintan_wsp.py) | Upload script: [`upload_fintan_to_hf.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/upload_fintan_to_hf.py)```powershell# Verify setup without GPU:C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-weight-space\.venv\Scripts\python.exe C:\Users\jhjwi\.gemini\antigravity\scratch\fintan-9b-wsp\run_fintan_wsp.py --dry-run8 unmodified lines- [`fintan_wsp_router.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/fintan_wsp_router.py) — `NightRouterWSP` + `UnifiedFintanWSPRouter` (Regimes 1–3)- [`validate_fintan_wsp_cal.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/validate_fintan_wsp_cal.py) — Disjoint calibration & Pareto sweep- [`evaluate_fintan_wsp.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/evaluate_fintan_wsp.py) — Complete unified evaluation harness (Suites A–D)- [`learn_wsp.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/learn_wsp.py) — Open-source 12 GB VRAM Int4/Int8 self-learning engine (Windows & Linux)- [`benchmark_self_learning.py`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/benchmark_self_learning.py) — Benchmarks Options 1, 2 & 3 on live `llama-server`- **GGUF Adapters (`adapters/`):**- [`fintan_r512_patched.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_r512_patched.gguf) (`136.00 MiB`, new default champion — `162/172` = `94.2%`, `12/12` B1)- [`fintan_2026_11_23_wsp_v2_r128.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_wsp_v2_r128.gguf) (`32.00 MiB`, native `<think>` `140/172`, `12/12` B1, `22/30` Forced-ON `Holdout-30`) & [`fintan_2026_11_23_wsp_v2_r64.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_wsp_v2_r64.gguf) (`16.00 MiB`, `25/30` Forced-ON)- [`fintan_wsp_v2_merged_n1n2.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_wsp_v2_merged_n1n2.gguf) (`40.00 MiB`, merged Night 1 + Night 2) & [`fintan_night2_wsp_r32.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_night2_wsp_r32.gguf) (`8.00 MiB`)- [`fintan_2026_11_23_r512.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_r512.gguf), [`fintan_2026_11_23_null_g5.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_null_g5.gguf), [`fintan_2026_11_23_null_g20.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_null_g20.gguf), [`fintan_2026_11_23_null_g1.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/fintan_2026_11_23_null_g1.gguf) (`128.00 MiB` each)- [`wsp_s12_fintan_think_bridge.gguf`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/adapters/wsp_s12_fintan_think_bridge.gguf) (`4.00 MiB`)- **Saved Results:**- [`spectral_analysis.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/spectral_analysis.json), [`baseline_audit.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/baseline_audit.json), [`wsp_synthesis_report.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/wsp_synthesis_report.json), [`wsp_cal_report.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/wsp_cal_report.json), [`fintan_wsp_results.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/fintan_wsp_results.json), [`self_learning_wsp_results.json`](file:///C:/Users/jhjwi/.gemini/antigravity/scratch/fintan-9b-wsp/self_learning_wsp_results.json)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763{
"option1_v2_r64": {
"norms": {
"file": "fintan_2026_11_23_wsp_v2_r64.gguf",
"size_mb": 16.0,
"rank": 64,
"mean_frob_norm": 7.094,
"per_layer_frob": {
"11": 7.682,
"14": 6.13,
"16": 6.443,
"18": 7.683,
"21": 7.944,
"23": 6.955,
"25": 6.853,
"27": 7.06
}
},
"suite_a3": {
"passed": 116,
"total": 172,
"pct": 67.4,
"empty_content": 0,
"cutoffs": 1,
"avg_tok": 8.2,
"missed_idxs": [
3,
7,
8,
9,
10,
13,
14,
18,
28,
29,
30,
32,
33,
35,
37,
38,
46,
49,
55,
58,
70,
71,
74,
81,
85,
86,
87,
93,
96,
98,
99,
103,
104,
105,
106,
107,
108,
110,
111,
112,
113,
129,
131,
133,
134,
135,
138,
141,
142,
148,
150,
151,
154,
157,
162,
166
]
},
"suite_a4_single_pass": {
"passed": 118,
"total": 172,
"pct": 68.6,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 11.9,
"missed_idxs": [
3,
7,
8,
9,
10,
14,
18,
28,
29,
30,
33,
35,
46,
49,
51,
55,
70,
71,
74,
81,
85,
86,
89,
91,
96,
98,
99,
102,
103,
104,
105,
106,
107,
108,
110,
111,
112,
113,
131,
133,
134,
135,
138,
139,
141,
142,
146,
148,
150,
151,
157,
159,
162,
166
]
},
"suite_a4_two_phase": {
"passed": 116,
"total": 172,
"pct": 67.4,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 11.9,
"missed_idxs": [
3,
7,
8,
9,
10,
13,
14,
18,
28,
29,
30,
32,
33,
35,
37,
38,
46,
49,
55,
58,
70,
71,
74,
81,
85,
86,
87,
93,
96,
98,
99,
103,
104,
105,
106,
107,
108,
110,
111,
112,
113,
129,
131,
133,
134,
135,
138,
141,
142,
148,
150,
151,
154,
157,
162,
166
]
},
"suite_b1": {
"think": {
"full_pass": 11,
"tool_syntax_ok": 12,
"total": 12,
"fails": [
{
"id": "b1_sparta2_write",
"recalled": "NATO's 26th member state"
}
]
},
"nothink": {
"full_pass": 11,
"tool_syntax_ok": 12,
"total": 12,
"fails": [
{
"id": "b1_sparta2_write",
"recalled": "NATO's 26th member state"
}
]
}
},
"forced_on_collateral": {
"forced_on_b3_abs": "5/10",
"abs_ok": 5,
"forced_on_b3_gen": "9/10",
"gen_ok": 9,
"forced_on_holdout30": "25/30",
"holdout_ok": 25
},
"post_vram_mb": 605
},
"option1_v2_r128": {
"norms": {
"file": "fintan_2026_11_23_wsp_v2_r128.gguf",
"size_mb": 32.0,
"rank": 128,
"mean_frob_norm": 9.413,
"per_layer_frob": {
"11": 9.329,
"14": 7.599,
"16": 8.172,
"18": 10.669,
"21": 10.924,
"23": 9.64,
"25": 9.518,
"27": 9.454
}
},
"suite_a3": {
"passed": 140,
"total": 172,
"pct": 81.4,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 7.2,
"missed_idxs": [
10,
19,
27,
29,
30,
33,
35,
46,
55,
73,
74,
75,
83,
87,
98,
103,
104,
108,
109,
113,
130,
133,
134,
138,
141,
142,
147,
148,
159,
160,
162,
164
]
},
"suite_a4_single_pass": {
"passed": 140,
"total": 172,
"pct": 81.4,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 11.1,
"missed_idxs": [
19,
27,
29,
30,
33,
35,
46,
55,
59,
70,
73,
74,
75,
83,
87,
98,
103,
104,
113,
129,
130,
134,
138,
141,
142,
147,
148,
155,
159,
160,
162,
164
]
},
"suite_a4_two_phase": {
"passed": 140,
"total": 172,
"pct": 81.4,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 9.3,
"missed_idxs": [
10,
19,
27,
29,
30,
33,
35,
46,
55,
73,
74,
75,
83,
87,
98,
103,
104,
108,
109,
113,
130,
133,
134,
138,
141,
142,
147,
148,
159,
160,
162,
164
]
},
"suite_b1": {
"think": {
"full_pass": 12,
"tool_syntax_ok": 12,
"total": 12,
"fails": []
},
"nothink": {
"full_pass": 12,
"tool_syntax_ok": 12,
"total": 12,
"fails": []
}
},
"forced_on_collateral": {
"forced_on_b3_abs": "2/10",
"abs_ok": 2,
"forced_on_b3_gen": "9/10",
"gen_ok": 9,
"forced_on_holdout30": "22/30",
"holdout_ok": 22
},
"post_vram_mb": 823
},
"option2_multi_night": {
"n2_adapter_norms": {
"file": "fintan_night2_wsp_r32.gguf",
"size_mb": 8.0,
"rank": 32,
"mean_frob_norm": 3.374,
"per_layer_frob": {
"11": 3.18,
"14": 2.982,
"16": 2.833,
"18": 3.434,
"21": 3.53,
"23": 3.504,
"25": 3.88,
"27": 3.649
}
},
"merged_adapter_norms": {
"file": "fintan_wsp_v2_merged_n1n2.gguf",
"size_mb": 40.0,
"rank": 160,
"mean_frob_norm": 9.992,
"per_layer_frob": {
"11": 9.841,
"14": 8.157,
"16": 8.637,
"18": 11.172,
"21": 11.472,
"23": 10.248,
"25": 10.275,
"27": 10.131
}
},
"base_on_night2": {
"passed": 0,
"total": 24,
"pct": 0.0
},
"night2_standalone": {
"passed": 0,
"total": 24,
"pct": 0.0
},
"merged_on_night1_direct": {
"passed": 138,
"total": 172,
"pct": 80.2,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 7.2,
"missed_idxs": [
10,
19,
27,
29,
30,
33,
46,
55,
59,
73,
74,
75,
83,
87,
98,
99,
103,
104,
109,
113,
129,
130,
133,
134,
138,
141,
142,
147,
148,
151,
159,
160,
162,
164
]
},
"merged_on_night1_think_single": {
"passed": 137,
"total": 172,
"pct": 79.7,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 11.1,
"missed_idxs": [
19,
27,
29,
30,
33,
46,
55,
59,
70,
73,
74,
75,
83,
87,
98,
99,
103,
104,
109,
113,
129,
130,
133,
134,
138,
141,
142,
147,
148,
151,
153,
159,
160,
162,
164
]
},
"merged_on_night2": {
"passed": 17,
"total": 24,
"pct": 70.8
},
"merged_forced_on_b3": {
"forced_on_b3_abs": "2/10",
"abs_ok": 2,
"forced_on_b3_gen": "9/10",
"gen_ok": 9
},
"post_vram_mb": 824
},
"option3_r512_patched": {
"norms": {
"file": "fintan_r512_patched.gguf",
"size_mb": 136.0,
"rank": 544,
"mean_frob_norm": 79.174,
"per_layer_frob": {
"11": 78.628,
"14": 78.899,
"16": 79.113,
"18": 78.714,
"21": 79.747,
"23": 78.937,
"25": 79.086,
"27": 80.27
}
},
"suite_a3": {
"passed": 162,
"total": 172,
"pct": 94.2,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 6.9,
"missed_idxs": [
30,
59,
63,
106,
112,
113,
134,
147,
154,
160
]
},
"suite_a4_two_phase": {
"passed": 162,
"total": 172,
"pct": 94.2,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 13.7,
"missed_idxs": [
30,
59,
63,
106,
112,
113,
134,
147,
154,
160
]
},
"suite_b1": {
"think": {
"full_pass": 12,
"tool_syntax_ok": 12,
"total": 12,
"fails": []
},
"nothink": {
"full_pass": 12,
"tool_syntax_ok": 12,
"total": 12,
"fails": []
}
},
"forced_on_b3": {
"forced_on_b3_abs": "0/10",
"abs_ok": 0,
"forced_on_b3_gen": "4/10",
"gen_ok": 4
},
"post_vram_mb": 833
},
"option3_v2_r128_patched": {
"norms": {
"file": "fintan_v2_r128_patched.gguf",
"size_mb": 40.0,
"rank": 160,
"mean_frob_norm": 9.412,
"per_layer_frob": {
"11": 9.323,
"14": 7.599,
"16": 8.18,
"18": 10.671,
"21": 10.925,
"23": 9.639,
"25": 9.504,
"27": 9.456
}
},
"suite_a3": {
"passed": 140,
"total": 172,
"pct": 81.4,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 7.2,
"missed_idxs": [
19,
27,
29,
30,
33,
46,
55,
59,
73,
74,
75,
83,
87,
98,
103,
104,
109,
113,
124,
129,
130,
133,
134,
138,
141,
142,
147,
148,
159,
160,
162,
164
]
},
"suite_a4_two_phase": {
"passed": 140,
"total": 172,
"pct": 81.4,
"empty_content": 0,
"cutoffs": 0,
"avg_tok": 9.3,
"missed_idxs": [
19,
27,
29,
30,
33,
46,
55,
59,
73,
74,
75,
83,
87,
98,
103,
104,
109,
113,
124,
129,
130,
133,
134,
138,
141,
142,
147,
148,
159,
160,
162,
164
]
},
"suite_b1": {
"think": {
"full_pass": 12,
"tool_syntax_ok": 12,
"total": 12,
"fails": []
},
"nothink": {
"full_pass": 12,
"tool_syntax_ok": 12,
"total": 12,
"fails": []
}
},
"forced_on_b3": {
"forced_on_b3_abs": "2/10",
"abs_ok": 2,
"forced_on_b3_gen": "9/10",
"gen_ok": 9
},
"post_vram_mb": 826
}
}1 unmodified line23456789101112139 unmodified lines23242526272829303132333430 unmodified lines6566676869707123 unmodified lines959697989910010110210326 unmodified lines1301311321331341351361371381391401411421431441451461474 unmodified lines15215315415515615719 unmodified lines1771781791801811821831843 unmodified lines18818919019119219319419519619719819920012 unmodified lines2132142152162172182191 unmodified lineLaunches Qwen3.5-9B-Q4_K_M on llama-server with all 13 LoRA slots preloaded cleanly:[0..10] Qwen3.5-9B WSP subspaces S1..S11 (agentic + Terminal-Bench control)[11] Fintan-9B continual-learning LoRA adapter (default: fintan_2026_11_23_r512.gguf)[12] S12 Reasoning-Bridge adapter (wsp_s12_fintan_think_bridge.gguf)Exposes an OpenAI-compatible `/v1/chat/completions` proxy routing across:- Regime 1: Pure Qwen3.5-9B + WSP S1..S11 (general / agentic / coding / math / Terminal-Bench)- Regime 2: Fintan Two-Phase Reasoning-Boundary / Direct Recall (episodic non-tool queries)- Regime 3: Two-Phase Weight-Space Recall-Then-Act (episodic queries + tools, zero RAG)"""9 unmodified linesimport timeimport urllib.requestfrom pathlib import Pathfrom typing import Any, Dict, ListREPO_ROOT = Path(__file__).resolve().parentsys.path.insert(0, str(REPO_ROOT))from fintan_wsp_router import UnifiedFintanWSPRouter, adapter_paths_13 # noqa: E402def build_llama_cmd(30 unmodified linesdaemon_threads = Truedef make_handler(router: UnifiedFintanWSPRouter, llama_url: str):class ProxyHandler(http.server.BaseHTTPRequestHandler):def log_message(self, format: str, *args: Any) -> None:return23 unmodified lines},)returnself._send_json(404, {"error": f"Unknown GET path: {self.path}"})def do_POST(self) -> None:if not self.path.startswith("/v1/chat/completions"):self._send_json(404, {"error": f"Unknown POST path: {self.path}"})return26 unmodified linesdef main() -> None:default_llama = shutil.which("llama-server") or shutil.which("llama-server.exe") or "llama-server"ap = argparse.ArgumentParser(description="Unified Fintan-9B + WSP runtime server")ap.add_argument("--model", type=Path, default=REPO_ROOT / "gguf" / "Qwen3.5-9B-Q4_K_M.gguf")ap.add_argument("--llama-server", type=str, default=default_llama)ap.add_argument("--adapters-dir", type=Path, default=REPO_ROOT / "adapters")ap.add_argument("--fintan-adapter", type=Path, default=REPO_ROOT / "adapters" / "fintan_2026_11_23_r512.gguf")ap.add_argument("--s12-adapter", type=Path, default=REPO_ROOT / "adapters" / "wsp_s12_fintan_think_bridge.gguf")ap.add_argument("--manifest", type=Path, default=REPO_ROOT / "fintan_data" / "manifest.json")ap.add_argument("--port", type=int, default=8900)ap.add_argument("--llama-port", type=int, default=8901)ap.add_argument("--host", type=str, default="127.0.0.1")ap.add_argument("--ctx", type=int, default=16384)ap.add_argument("--fintan-scale", type=float, default=1.0)ap.add_argument("--s12-scale", type=float, default=0.8)ap.add_argument("--dry-run", action="store_true")4 unmodified linesif not args.manifest.exists():raise FileNotFoundError(f"Manifest missing: {args.manifest}")lora_paths = adapter_paths_13(args.fintan_adapter, args.s12_adapter, adapters_dir=args.adapters_dir)router = UnifiedFintanWSPRouter(fintan_scale=args.fintan_scale,19 unmodified lines"status": "dry_run_ok","proxy_url": f"http://{args.host}:{args.port}/v1/chat/completions","llama_url": f"http://{args.host}:{args.llama_port}","model": str(args.model),"wsp_model_name": router.wsp_router.model_name,"adapters_loaded": [f"[{i}] {p.name}" for i, p in enumerate(lora_paths)],"fintan_scale": args.fintan_scale,"s12_scale": args.s12_scale,3 unmodified lines"episodic_tool_night": r_tool,"wsp_exec_regime": dec_tool.regime,},},indent=2,))returnlog_fp = (REPO_ROOT / "runtime_llama_server.log").open("w", encoding="utf-8")proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT)llama_url = f"http://{args.host}:{args.llama_port}"try:12 unmodified linesif not ready:raise TimeoutError("Timed out waiting for llama-server /health")httpd = ThreadingHTTPServer((args.host, args.port), make_handler(router, llama_url))print(f"Unified Fintan-9B + WSP server listening on http://{args.host}:{args.port}/v1", flush=True)print(f"Backend llama-server on {llama_url} ({len(lora_paths)} LoRA adapters)", flush=True)try:1 unmodified line23456789101112139 unmodified lines232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414530 unmodified lines17617717817918018118218318423 unmodified lines20820921021121221321421521621721821922022122222322422522622722822923023123223323423526 unmodified lines2622632642652662672682692702712722732742752762772784 unmodified lines28328428528628728828929029119 unmodified lines3113123133143153163 unmodified lines32032132232332432532632732832933033133233312 unmodified lines3463473483493503513521 unmodified lineLaunches Qwen3.5-9B-Q4_K_M on llama-server with all 13 LoRA slots preloaded cleanly:[0..10] Qwen3.5-9B WSP subspaces S1..S11 (agentic + Terminal-Bench control)[11] Fintan-9B Right-Nullspace-Projected sleep adapter (fintan_2026_11_23_null_g5.gguf)[12] S12 Reasoning-Bridge adapter (wsp_s12_fintan_think_bridge.gguf)Exposes an OpenAI-compatible `/v1/chat/completions` proxy that routes every turn across:- Regime 1: Pure Qwen3.5-9B + WSP S1..S11 (general / agentic / coding / math / Terminal-Bench)- Regime 2: Fintan Two-Phase Reasoning-Boundary / Direct Recall (non-tool episodic queries)- Regime 3: Two-Phase Weight-Space Recall-Then-Act (episodic queries + tools, zero RAG)"""9 unmodified linesimport timeimport urllib.requestfrom pathlib import Pathfrom typing import Any, Dict, List, OptionalREPO_ROOT = Path(__file__).resolve().parentROOT = REPO_ROOTADAPTERS = REPO_ROOT / "adapters"BASE_GGUF = REPO_ROOT / "gguf" / "Qwen3.5-9B-Q4_K_M.gguf"UPSTREAM_DOOR = REPO_ROOT / "fintan_data" / "door"if not UPSTREAM_DOOR.exists():UPSTREAM_DOOR = REPO_ROOT.parent / "upstream" / "door"LLAMA_SERVER = shutil.which("llama-server") or shutil.which("llama-server.exe") or "llama-server"STATE_DIR = REPO_ROOT / "_live_teach"sys.path.insert(0, str(REPO_ROOT))sys.path.insert(0, str(UPSTREAM_DOOR))from fintan_wsp_router import UnifiedFintanWSPRouter, adapter_paths_13 # noqa: E402from teach_policy import check_document, redact_secrets # noqa: E402def _read_json_list(path: Path) -> List[Dict[str, Any]]:if not path.exists():return []try:data = json.loads(path.read_text(encoding="utf-8"))return data if isinstance(data, list) else []except Exception:return []def handle_teach(req: Dict[str, Any], state_dir: Path = STATE_DIR) -> Dict[str, Any]:"""Validate and stage new knowledge via upstream teach_policy without touching weights yet."""text = str(req.get("text") or "").strip()subject = str(req.get("subject") or "").strip()relation = str(req.get("relation") or "states").strip()value = str(req.get("value") or text).strip()date = str(req.get("date") or "2026-11-26").strip()source = str(req.get("source") or "user_teach").strip()refuse_warnings = bool(req.get("refuse_warnings", False))combined = "\n".join(x for x in (text, subject, relation, value) if x).strip()pol = check_document(combined, name=source, refuse_warnings=refuse_warnings)if not pol.get("allow", False):return {"status_code": 400,"accepted": False,"category": pol.get("category"),"reason": pol.get("reason"),"flags": pol.get("flags", []),}safe_val = redact_secrets(value) if "secrets" in (pol.get("flags") or []) else valuesafe_subj = subject or sourcestate_dir.mkdir(parents=True, exist_ok=True)pending_p = state_dir / "pending_teach.json"items = _read_json_list(pending_p)items.append({"subject": safe_subj,"relation": relation,"value": safe_val,"date": date,"source": source,})pending_p.write_text(json.dumps(items, indent=2, ensure_ascii=False), encoding="utf-8")return {"status_code": 200,"accepted": True,"flags": pol.get("flags", []),"pending_count": len(items),}def trigger_learn(fintan_adapter: Path,state_dir: Path = STATE_DIR,spawn: bool = True,) -> Dict[str, Any]:"""Invoke open-source learn_wsp.py on pending taught facts protecting existing weights."""pending_p = state_dir / "pending_teach.json"items = _read_json_list(pending_p)if not items:return {"started": False, "reason": "no_pending_facts", "pending_count": 0}state_dir.mkdir(parents=True, exist_ok=True)qa_p = state_dir / "live_qa.json"out_gguf = ADAPTERS / "fintan_live_update.gguf"out_keys = ADAPTERS / "fintan_live_update_keys.pt"protect = [p for p in (ADAPTERS / "fintan_2026_11_23_wsp_v2_r128_keys.pt",) if p.exists()]cmd = [sys.executable,str((REPO_ROOT / "scripts" / "learn_wsp.py") if (REPO_ROOT / "scripts" / "learn_wsp.py").exists() else (REPO_ROOT / "learn_wsp.py")),"train","--facts", str(pending_p),"--qa-cache", str(qa_p),"--out", str(out_gguf),"--save-keys", str(out_keys),"--rank", "32","--epochs", "5","--lambda-null", "0.10",]if protect:cmd.extend(["--protect-keys", *[str(p) for p in protect]])if spawn:log_fp = (state_dir / "live_learn.log").open("w", encoding="utf-8")subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT)return {"started": True,"pending_count": len(items),"target_adapter": str(out_gguf),"protect_keys": [str(p) for p in protect],"cmd": cmd,}def get_fintan_status(fintan_adapter: Path, state_dir: Path = STATE_DIR) -> Dict[str, Any]:return {"active_fintan_adapter": str(fintan_adapter),"pending_count": len(_read_json_list(state_dir / "pending_teach.json")),"state_dir": str(state_dir),}def build_llama_cmd(30 unmodified linesdaemon_threads = Truedef make_handler(router: UnifiedFintanWSPRouter, llama_url: str, fintan_adapter: Optional[Path] = None):active_adapter = fintan_adapter or (ADAPTERS / "fintan_r512_patched.gguf")class ProxyHandler(http.server.BaseHTTPRequestHandler):def log_message(self, format: str, *args: Any) -> None:return23 unmodified lines},)returnif self.path.startswith("/fintan/status"):self._send_json(200, get_fintan_status(active_adapter))returnself._send_json(404, {"error": f"Unknown GET path: {self.path}"})def do_POST(self) -> None:if self.path.startswith("/fintan/teach"):try:length = int(self.headers.get("Content-Length") or "0")req = json.loads(self.rfile.read(length).decode("utf-8"))res = handle_teach(req)self._send_json(int(res.get("status_code", 200)), res)except Exception as exc:self._send_json(500, {"error": str(exc)})returnif self.path.startswith("/fintan/learn"):try:res = trigger_learn(active_adapter, spawn=True)self._send_json(200, res)except Exception as exc:self._send_json(500, {"error": str(exc)})returnif not self.path.startswith("/v1/chat/completions"):self._send_json(404, {"error": f"Unknown POST path: {self.path}"})return26 unmodified linesdef main() -> None:ap = argparse.ArgumentParser(description="Unified Fintan-9B + WSP runtime server")ap.add_argument("--model", type=Path, default=BASE_GGUF)ap.add_argument("--llama-server", type=str, default=LLAMA_SERVER)ap.add_argument("--adapters-dir", type=Path, default=ADAPTERS)ap.add_argument("--manifest", type=Path, default=REPO_ROOT / "fintan_data" / "manifest.json")ap.add_argument("--port", type=int, default=8900)ap.add_argument("--llama-port", type=int, default=8901)ap.add_argument("--host", type=str, default="127.0.0.1")ap.add_argument("--ctx", type=int, default=16384)ap.add_argument("--fintan-adapter", type=Path, default=ADAPTERS / "fintan_r512_patched.gguf")ap.add_argument("--s12-adapter", type=Path, default=ADAPTERS / "wsp_s12_fintan_think_bridge.gguf")ap.add_argument("--fintan-scale", type=float, default=1.0)ap.add_argument("--s12-scale", type=float, default=0.8)ap.add_argument("--dry-run", action="store_true")4 unmodified linesif not args.manifest.exists():raise FileNotFoundError(f"Manifest missing: {args.manifest}")lora_paths = adapter_paths_13(args.fintan_adapter, args.s12_adapter, adapters_dir=args.adapters_dir)missing = [str(p) for p in lora_paths if not p.exists()]if missing:raise FileNotFoundError(f"Missing LoRA files: {missing}")router = UnifiedFintanWSPRouter(fintan_scale=args.fintan_scale,19 unmodified lines"status": "dry_run_ok","proxy_url": f"http://{args.host}:{args.port}/v1/chat/completions","llama_url": f"http://{args.host}:{args.llama_port}","adapters_loaded": [f"[{i}] {p.name}" for i, p in enumerate(lora_paths)],"fintan_scale": args.fintan_scale,"s12_scale": args.s12_scale,3 unmodified lines"episodic_tool_night": r_tool,"wsp_exec_regime": dec_tool.regime,},"llama_cmd_preview": " ".join(cmd[:6]) + f" ... ({len(lora_paths)} loras)",},indent=2,))returnlog_fp = (ROOT / "runtime_llama_server.log").open("w", encoding="utf-8")proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT)llama_url = f"http://{args.host}:{args.llama_port}"try:12 unmodified linesif not ready:raise TimeoutError("Timed out waiting for llama-server /health")httpd = ThreadingHTTPServer((args.host, args.port), make_handler(router, llama_url, fintan_adapter=args.fintan_adapter))print(f"Unified Fintan-9B + WSP server listening on http://{args.host}:{args.port}/v1", flush=True)print(f"Backend llama-server on {llama_url} ({len(lora_paths)} LoRA adapters)", flush=True)try:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359"""Benchmark suite for Fintan Self-Learning LoRA Upgrades (Options 1, 2 & 3).
Measures on live llama-server (-c 16384): --mode v2 : Fintan-WSP-v2 r64 vs upstream r512 (A3, A4 single-pass & two-phase, B1 12x2, Forced-ON B3+Holdout-30) --mode multi: Multi-Night N1+N2 orthogonal merge retention, Night-2 recall, Forced-ON B3 --mode patch: Targeted Option-3 refinement patch on check_172, B1 12x2, and Forced-ON B3"""
from __future__ import annotations
import argparseimport jsonimport mathimport reimport subprocessimport sysimport timefrom pathlib import Pathfrom typing import Any, Dict, List
import torch
ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\fintan-9b-wsp")ADAPTERS = ROOT / "adapters"UPSTREAM = ROOT / "upstream"PIPELINE_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline")RESULTS_JSON = ROOT / "self_learning_wsp_results.json"PORT = 8163BASE_URL = f"http://127.0.0.1:{PORT}"
sys.path.insert(0, str(ROOT))sys.path.insert(0, str(UPSTREAM / "scripts"))sys.path.insert(0, str(PIPELINE_DIR))
import audit_fintan_baseline as ab # noqa: E402import evaluate_all_models as eam # noqa: E402import learn_wsp as lw # noqa: E402from fintan_wsp_router import UnifiedFintanWSPRouter, adapter_paths_13 # noqa: E402from run_fintan_wsp import build_llama_cmd # noqa: E402from run_transformers import right as fintan_right # noqa: E402
if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
def start_server(lora_paths: List[Path], port: int = PORT) -> subprocess.Popen: cmd = build_llama_cmd(lora_paths, llama_port=port, host="127.0.0.1", ctx=16384) log_fp = (ROOT / f"bench_sl_p{port}.log").open("w", encoding="utf-8") proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT) proc._log_fp = log_fp # type: ignore[attr-defined] import urllib.request for _ in range(180): if proc.poll() is not None: raise RuntimeError(f"llama-server exited early with {proc.returncode}") try: with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2.0) as resp: if json.loads(resp.read().decode()).get("status") == "ok": return proc except Exception: pass time.sleep(0.5) raise TimeoutError("Timed out waiting for llama-server")
def stop_server(proc: subprocess.Popen) -> None: proc.terminate() try: proc.wait(timeout=10) except subprocess.TimeoutExpired: proc.kill() try: proc._log_fp.close() # type: ignore[attr-defined] except Exception: pass time.sleep(0.8)
def measure_adapter_norms(adapter_path: Path) -> Dict[str, Any]: pairs = lw.read_gguf_lora_pairs(adapter_path) frobs = {str(L): round(float(torch.linalg.norm(B @ A).item()), 3) for L, (A, B) in pairs.items()} return { "file": adapter_path.name, "size_mb": round(adapter_path.stat().st_size / (1024 ** 2), 2), "rank": int(next(iter(pairs.values()))[0].shape[0]) if pairs else 0, "mean_frob_norm": round(sum(frobs.values()) / max(len(frobs), 1), 3), "per_layer_frob": frobs, }
def eval_check172( router: UnifiedFintanWSPRouter, check_qs: List[Dict[str, str]], enable_thinking: bool, single_pass_no_s12: bool = False, force_night: Any = None, label: str = "A",) -> Dict[str, Any]: old_s12 = router.s12_scale if single_pass_no_s12: router.s12_scale = 0.0 recs = [] t0 = time.time() try: for idx, it in enumerate(check_qs): q, gold = it["question"], it["answer"] r = router.chat_completion( BASE_URL, [{"role": "user", "content": q}], max_tokens=(512 if enable_thinking else 64), enable_thinking=enable_thinking, force_night=force_night, single_pass_s12=single_pass_no_s12, ) clean = eam.strip_thinking(r["content"]) if enable_thinking else r["content"] ok = bool(clean.strip()) and bool(fintan_right(clean, gold, q)) recs.append({ "idx": idx, "passed": ok, "empty_content": (len(clean.strip()) == 0), "cut": (r["finish_reason"] == "length"), "tok": r["comp_tok"] + (r["phase1_tok"] if r["regime"] == "fintan_think_two_phase" else 0), "out": clean[:160], }) if (idx + 1) % 43 == 0 or idx + 1 == len(check_qs): el = time.time() - t0 print(f" [{label} {idx+1:3d}/172] pass={sum(x['passed'] for x in recs)} | {el:.1f}s", flush=True) finally: router.s12_scale = old_s12 return { "passed": sum(x["passed"] for x in recs), "total": len(recs), "pct": round(100.0 * sum(x["passed"] for x in recs) / len(recs), 1), "empty_content": sum(x["empty_content"] for x in recs), "cutoffs": sum(x["cut"] for x in recs), "avg_tok": round(sum(x["tok"] for x in recs) / len(recs), 1), "missed_idxs": [x["idx"] for x in recs if not x["passed"]], }
def eval_b1(router: UnifiedFintanWSPRouter) -> Dict[str, Any]: out = {} for mname, th in [("think", True), ("nothink", False)]: ok_cnt, tc_cnt = 0, 0 fails = [] for it in ab.B1_KNOWLEDGE_WITH_TOOLS: r = router.chat_completion( BASE_URL, [{"role": "user", "content": it["prompt"]}], tools=ab.AGENT_TOOLS, max_tokens=512, enable_thinking=th ) tcs = eam.parse_tool_calls(r) tool_ok = bool(tcs) and tcs[0]["name"] == it["expected_tool"] arg_text = json.dumps(tcs[0]["arguments"]).lower() if tcs else eam.strip_thinking(r["content"]).lower() fact_ok = all(w.lower() in arg_text for w in it["must_all"]) if "must_all" in it else any(w.lower() in arg_text for w in it["must_any"]) p_ok = (it["path_must"].lower() in str(tcs[0]["arguments"].get("path", "")).lower()) if ("path_must" in it and tcs) else True passed = tool_ok and fact_ok and p_ok tc_cnt += int(tool_ok) ok_cnt += int(passed) if not passed: fails.append({"id": it["id"], "recalled": r["recalled_fact"]}) out[mname] = {"full_pass": ok_cnt, "tool_syntax_ok": tc_cnt, "total": 12, "fails": fails} print(f" B1 ({mname:7s}): full_pass={ok_cnt}/12 (tool_ok={tc_cnt}/12)", flush=True) return out
def eval_forced_on_collateral(router: UnifiedFintanWSPRouter, include_holdout: bool = True) -> Dict[str, Any]: """Measure collateral damage when Fintan LoRA is forced ON (scale=1.0, NO NightRouter protection).""" abs_ok = 0 for it in ab.B3_ABSTENTION_10: r = router.chat_completion(BASE_URL, [{"role": "user", "content": it["prompt"]}], max_tokens=96, enable_thinking=False, force_night=True) low = eam.strip_thinking(r["content"]).lower() abs_ok += int(any(p in low for p in ab.ABSTAIN_PHRASES))
gen_ok = 0 for it in ab.B3_GENERAL_10: r = router.chat_completion(BASE_URL, [{"role": "user", "content": it["prompt"]}], max_tokens=64, enable_thinking=False, force_night=True) low = " " + re.sub(r"[^0-9a-z]+", " ", eam.strip_thinking(r["content"]).lower()) + " " gen_ok += int(any(f" {k.lower()} " in low or k.lower() in r["content"].lower() for k in it["must_any"]))
res: Dict[str, Any] = {"forced_on_b3_abs": f"{abs_ok}/10", "abs_ok": abs_ok, "forced_on_b3_gen": f"{gen_ok}/10", "gen_ok": gen_ok} print(f" Forced-ON B3: abstention={abs_ok}/10 | general={gen_ok}/10", flush=True)
if include_holdout: hold_ok = 0 old_s12 = router.s12_scale router.s12_scale = 0.0 # test native Fintan adapter forced-ON under normal enable_thinking=True without S12 help try: for suite, it, t_tools, max_t in ab.build_holdout_items(): msgs = it["messages"] if "messages" in it else [{"role": "user", "content": it["prompt"]}] # Force slot 11=1.0 via direct HTTP call using router._http_json to bypass Regime 3 recall wrapper router.push_scales(BASE_URL, [0.0] * 11 + [1.0, 0.0]) body: Dict[str, Any] = { "model": "qwen3.5-9b", "messages": msgs, "max_tokens": max_t, "temperature": 0.0, "seed": 42, "cache_prompt": False, "chat_template_kwargs": {"enable_thinking": True}, } if t_tools: body["tools"] = t_tools raw = router._http_json(f"{BASE_URL}/v1/chat/completions", body, timeout=180.0) msg = raw["choices"][0]["message"] fake_r = { "reasoning": msg.get("reasoning_content") or "", "content": msg.get("content") or "", "tool_calls": msg.get("tool_calls") or [], "finish_reason": raw["choices"][0].get("finish_reason"), } ok, _ = ab.grade_holdout_item(suite, it, fake_r) hold_ok += int(ok) finally: router.s12_scale = old_s12 res["forced_on_holdout30"] = f"{hold_ok}/30" res["holdout_ok"] = hold_ok print(f" Forced-ON Holdout-30 (no router): {hold_ok}/30 (vs upstream r512 1/30)", flush=True) return res
def save_merged_result(key: str, val: Dict[str, Any]) -> None: cur = json.loads(RESULTS_JSON.read_text(encoding="utf-8")) if RESULTS_JSON.exists() else {} cur[key] = val RESULTS_JSON.write_text(json.dumps(cur, indent=2), encoding="utf-8")
def run_v2_benchmark(adapter_path: Path, result_key: str = "option1_v2_r64") -> None: print(f"\n=== BENCHMARK OPTION 1 ({result_key}): {adapter_path.name} ===", flush=True) check_qs = json.loads((UPSTREAM / "updates" / "2026-11-23" / "check_questions.json").read_text(encoding="utf-8")) s12_gguf = ADAPTERS / "wsp_s12_fintan_think_bridge.gguf" norms = measure_adapter_norms(adapter_path) print(f" Norms: size={norms['size_mb']} MiB | rank={norms['rank']} | mean_||dW||_F={norms['mean_frob_norm']}", flush=True)
proc = start_server(adapter_paths_13(adapter_path, s12_gguf), port=PORT) try: router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8) a3 = eval_check172(router, check_qs, enable_thinking=False, single_pass_no_s12=False, label="V2 A3") a4_sp = eval_check172(router, check_qs, enable_thinking=True, single_pass_no_s12=True, label="V2 A4_single") a4_tp = eval_check172(router, check_qs, enable_thinking=True, single_pass_no_s12=False, label="V2 A4_two_ph") b1 = eval_b1(router) forced = eval_forced_on_collateral(router, include_holdout=True) finally: stop_server(proc)
_, post_vram, _ = eam.get_gpu_vram_mb() out = { "norms": norms, "suite_a3": a3, "suite_a4_single_pass": a4_sp, "suite_a4_two_phase": a4_tp, "suite_b1": b1, "forced_on_collateral": forced, "post_vram_mb": post_vram, } save_merged_result(result_key, out) print(f" -> Saved {result_key} to {RESULTS_JSON} | post_vram={post_vram} MiB", flush=True)
def eval_night2_questions(router: UnifiedFintanWSPRouter, eval_qs: List[Dict[str, str]], force_night: Any, label: str) -> Dict[str, Any]: ok_cnt = 0 for it in eval_qs: r = router.chat_completion( BASE_URL, [{"role": "user", "content": it["question"]}], max_tokens=64, enable_thinking=False, force_night=force_night ) ok_cnt += int(bool(fintan_right(r["content"], it["answer"], it["question"]))) print(f" {label:28s}: {ok_cnt}/{len(eval_qs)} ({100*ok_cnt/len(eval_qs):.1f}%)", flush=True) return {"passed": ok_cnt, "total": len(eval_qs), "pct": round(100.0 * ok_cnt / len(eval_qs), 1)}
def run_multi_benchmark(n2_adapter: Path, merged_adapter: Path, n2_eval_path: Path) -> None: print(f"\n=== BENCHMARK OPTION 2: MULTI-NIGHT N1+N2 ({merged_adapter.name}) ===", flush=True) check_qs = json.loads((UPSTREAM / "updates" / "2026-11-23" / "check_questions.json").read_text(encoding="utf-8")) n2_qs = json.loads(n2_eval_path.read_text(encoding="utf-8")) s12_gguf = ADAPTERS / "wsp_s12_fintan_think_bridge.gguf"
# 1. Standalone Night 2 (plus Base=scale 0.0 on Night 2) proc = start_server(adapter_paths_13(n2_adapter, s12_gguf), port=PORT) try: router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8) n2_base = eval_night2_questions(router, n2_qs, force_night=False, label="Base Qwen3.5 on Night 2") n2_solo = eval_night2_questions(router, n2_qs, force_night=True, label="Standalone Night 2 LoRA") finally: stop_server(proc)
# 2. Merged Night 1 + Night 2 single GGUF LoRA proc = start_server(adapter_paths_13(merged_adapter, s12_gguf), port=PORT) try: router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8) m_n1 = eval_check172(router, check_qs, enable_thinking=False, force_night=True, label="Merged N1+N2 on check_172") m_n1_sp = eval_check172(router, check_qs, enable_thinking=True, single_pass_no_s12=True, force_night=True, label="Merged N1+N2 A4_single") m_n2 = eval_night2_questions(router, n2_qs, force_night=True, label="Merged N1+N2 on Night 2") m_forced = eval_forced_on_collateral(router, include_holdout=False) finally: stop_server(proc)
_, post_vram, _ = eam.get_gpu_vram_mb() out = { "n2_adapter_norms": measure_adapter_norms(n2_adapter), "merged_adapter_norms": measure_adapter_norms(merged_adapter), "base_on_night2": n2_base, "night2_standalone": n2_solo, "merged_on_night1_direct": m_n1, "merged_on_night1_think_single": m_n1_sp, "merged_on_night2": m_n2, "merged_forced_on_b3": m_forced, "post_vram_mb": post_vram, } save_merged_result("option2_multi_night", out) print(f" -> Saved option2_multi_night to {RESULTS_JSON} | post_vram={post_vram} MiB", flush=True)
def run_patch_benchmark(patch_key: str, adapter_path: Path) -> None: print(f"\n=== BENCHMARK OPTION 3 PATCH ({patch_key}): {adapter_path.name} ===", flush=True) check_qs = json.loads((UPSTREAM / "updates" / "2026-11-23" / "check_questions.json").read_text(encoding="utf-8")) s12_gguf = ADAPTERS / "wsp_s12_fintan_think_bridge.gguf" norms = measure_adapter_norms(adapter_path)
proc = start_server(adapter_paths_13(adapter_path, s12_gguf), port=PORT) try: router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8) a3 = eval_check172(router, check_qs, enable_thinking=False, label=f"{patch_key} A3") a4_tp = eval_check172(router, check_qs, enable_thinking=True, single_pass_no_s12=False, label=f"{patch_key} A4_tp") b1 = eval_b1(router) forced = eval_forced_on_collateral(router, include_holdout=False) finally: stop_server(proc)
_, post_vram, _ = eam.get_gpu_vram_mb() out = { "norms": norms, "suite_a3": a3, "suite_a4_two_phase": a4_tp, "suite_b1": b1, "forced_on_b3": forced, "post_vram_mb": post_vram, } save_merged_result(f"option3_{patch_key}", out) print(f" -> Saved option3_{patch_key} to {RESULTS_JSON} | post_vram={post_vram} MiB", flush=True)
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--mode", choices=["v2", "multi", "patch"], required=True) ap.add_argument("--adapter", type=Path, default=ADAPTERS / "fintan_2026_11_23_wsp_v2_r64.gguf") ap.add_argument("--n2-adapter", type=Path, default=ADAPTERS / "fintan_night2_wsp_r32.gguf") ap.add_argument("--merged-adapter", type=Path, default=ADAPTERS / "fintan_wsp_v2_merged_n1n2.gguf") ap.add_argument("--n2-eval", type=Path, default=ROOT / "night2_eval_questions.json") ap.add_argument("--patch-key", type=str, default="r512_patched") ap.add_argument("--result-key", type=str, default="option1_v2_r64") args = ap.parse_args()
if args.mode == "v2": run_v2_benchmark(args.adapter, result_key=args.result_key) elif args.mode == "multi": run_multi_benchmark(args.n2_adapter, args.merged_adapter, args.n2_eval) elif args.mode == "patch": run_patch_benchmark(args.patch_key, args.adapter)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173"""Open-Source Nullspace-Protected Self-Learning LoRA Engine for Fintan-9B (Windows & Linux, 12 GB VRAM).
Implements: 1. Pure-PyTorch symmetric Int4Linear (group=64) & Int8Linear (row-wise) with cached HF streaming (zero bitsandbytes/peft dependencies, ~4.5-6.0 GB peak training VRAM on RTX 4070 Ti). 2. Layer-10 activation precomputation (H_10) so epochs train only layers [11..31] + checkpointing. 3. Online exact Woodbury right-nullspace regularization against `X_preserve_base` (general/tools) plus optional prior-night receptor keys `--protect-keys` for orthogonal continual learning. 4. Native `enable_thinking` + `enable_thinking=False` mixed Qwen3.5 template supervision (closing `<think>\\n` -> `</think>\\n\\n` natively in 25% of training examples). 5. Entity-disambiguating study Q&A synthesizer (`synthesize-qa`), hard-fact study evaluator (`eval-study`), and exact reduced-SVD multi-night LoRA merger (`merge`).
Strictly separates training/mining (`facts.json`) from held-out evaluations (`check_questions.json`, Suite B/C/D)."""
from __future__ import annotations
import argparseimport gcimport jsonimport mathimport randomimport reimport subprocessimport sysimport timeimport urllib.requestfrom collections import defaultdictfrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple
import ggufimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom huggingface_hub import snapshot_downloadfrom torch.utils.checkpoint import checkpointfrom transformers import AutoConfig, AutoTokenizerfrom transformers.models.qwen3_5 import modeling_qwen3_5 as qm
if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\fintan-9b-wsp")UPSTREAM = ROOT / "upstream"ADAPTERS = ROOT / "adapters"CACHE_DIR = ROOT / "_cache"QUANT_CACHE = CACHE_DIR / "qwen35_9b_int4_train.pt"HOOK_CACHE = ROOT / "fintan_hook_cache.pt"PIPELINE_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline")BASE_GGUF = PIPELINE_DIR / "models" / "qwen35_9b" / "Qwen3.5-9B-Q4_K_M.gguf"LLAMA_SERVER = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp\llama.cpp\llama-server.exe")
sys.path.insert(0, str(PIPELINE_DIR))from build_9subspaces_all import TensorSource # noqa: E402from build_qwen35_9b_full_hooks import fetch_layer_state_dict, fetch_raw_bf16 # noqa: E402from model_registry import MODEL_SPECS # noqa: E402
FINTAN_LAYERS = [11, 14, 16, 18, 21, 23, 25, 27]HF_REPO = "Qwen/Qwen3.5-9B"_TEMPLATE_CACHE: Optional[str] = None
def get_qwen_chat_template() -> str: global _TEMPLATE_CACHE if _TEMPLATE_CACHE is not None: return _TEMPLATE_CACHE r = gguf.GGUFReader(str(BASE_GGUF)) for f in r.fields.values(): if "chat_template" in f.name: _TEMPLATE_CACHE = bytes(f.parts[f.data[0]]).decode("utf-8", errors="replace") return _TEMPLATE_CACHE raise RuntimeError(f"tokenizer.chat_template missing in {BASE_GGUF}")
def load_tokenizer_and_tcfg() -> Tuple[Any, Any]: local_qwen = PIPELINE_DIR / "models" / "qwen35_9b" if (local_qwen / "tokenizer.json").exists() and (local_qwen / "config.json").exists(): tok_dir = str(local_qwen) else: tok_dir = snapshot_download(HF_REPO, allow_patterns=["config.json", "tokenizer*"]) tok = AutoTokenizer.from_pretrained(tok_dir) if not getattr(tok, "chat_template", None): tok.chat_template = get_qwen_chat_template() cfg = AutoConfig.from_pretrained(tok_dir) tcfg = getattr(cfg, "text_config", cfg) tcfg._attn_implementation = "sdpa" return tok, tcfg
# ---------------------------------------------------------------------------# Pure-PyTorch Quantized Layers (Zero bitsandbytes / peft dependencies)# ---------------------------------------------------------------------------
def pack_int4_weight(w: torch.Tensor, group_size: int = 64) -> Tuple[torch.Tensor, torch.Tensor]: """Symmetric signed int4 [-7..7] packed 2 values per uint8 byte + bf16 group scales.""" o, i = w.shape assert i % group_size == 0, f"in_features={i} must be divisible by {group_size}" w_g = w.float().view(o, i // group_size, group_size) scales = (w_g.abs().amax(dim=-1) / 7.0).clamp(min=1e-8) q = torch.clamp(torch.round(w_g / scales.unsqueeze(-1)), -7, 7).to(torch.int8).add(7).to(torch.uint8) q_flat = q.view(o, i) packed = q_flat[:, 0::2] | (q_flat[:, 1::2] << 4) return packed.contiguous(), scales.to(torch.bfloat16).contiguous()
def pack_int8_rowwise(w: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: w_f = w.float() scales = (w_f.abs().amax(dim=-1, keepdim=True) / 127.0).clamp(min=1e-8) q = torch.clamp(torch.round(w_f / scales), -127, 127).to(torch.int8) return q.contiguous(), scales.to(torch.bfloat16).contiguous()
class Int4Linear(nn.Module): """Frozen packed-Int4 Linear layer with optional frozen base LoRA and trainable FP32 LoRA."""
def __init__(self, qweight: torch.Tensor, scales: torch.Tensor, group_size: int = 64): super().__init__() self.register_buffer("qweight", qweight) self.register_buffer("scales", scales) self.in_features = qweight.shape[1] * 2 self.out_features = qweight.shape[0] self.group_size = group_size self.register_buffer("base_lora_A", None) self.register_buffer("base_lora_B", None) self.lora_A: Optional[nn.Parameter] = None self.lora_B: Optional[nn.Parameter] = None
def attach_frozen_base_lora(self, A: torch.Tensor, B: torch.Tensor, device: str = "cuda") -> None: self.base_lora_A = A.to(device=device, dtype=torch.bfloat16).contiguous() self.base_lora_B = B.to(device=device, dtype=torch.bfloat16).contiguous()
def attach_lora( self, rank: int, init_ab: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, device: str = "cuda", ) -> None: if init_ab is not None: a_init, b_init = init_ab self.lora_A = nn.Parameter(a_init.to(device=device, dtype=torch.float32).clone()) self.lora_B = nn.Parameter(b_init.to(device=device, dtype=torch.float32).clone()) else: a = torch.empty((rank, self.in_features), device=device, dtype=torch.float32) nn.init.kaiming_uniform_(a, a=math.sqrt(5)) a.mul_(0.5) b = torch.zeros((self.out_features, rank), device=device, dtype=torch.float32) self.lora_A = nn.Parameter(a) self.lora_B = nn.Parameter(b)
def dequant_weight(self) -> torch.Tensor: q_lo = (self.qweight & 0x0F).to(torch.int8) - 7 q_hi = ((self.qweight >> 4) & 0x0F).to(torch.int8) - 7 w = torch.stack((q_lo, q_hi), dim=-1).view(self.out_features, -1, self.group_size).to(torch.bfloat16) return (w * self.scales.unsqueeze(-1)).view(self.out_features, self.in_features)
def forward(self, x: torch.Tensor) -> torch.Tensor: w = self.dequant_weight() out = F.linear(x, w) if self.base_lora_A is not None and self.base_lora_B is not None: hb = F.linear(x.to(self.base_lora_A.dtype), self.base_lora_A) out = out + F.linear(hb, self.base_lora_B).to(x.dtype) if self.lora_A is not None and self.lora_B is not None: h_a = F.linear(x.float(), self.lora_A) out = out + F.linear(h_a, self.lora_B).to(x.dtype) return out
class Int8Linear(nn.Module): """Row-wise quantized Int8 Linear layer (used for frozen lm_head)."""
def __init__(self, qweight: torch.Tensor, scales: torch.Tensor): super().__init__() self.register_buffer("qweight", qweight) self.register_buffer("scales", scales)
def forward(self, x: torch.Tensor) -> torch.Tensor: w = self.qweight.to(torch.bfloat16) * self.scales return F.linear(x.to(torch.bfloat16), w)
def quantize_decoder_sd(sd: Dict[str, torch.Tensor]) -> Dict[str, Any]: packed_sd: Dict[str, Any] = {} for k, v in sd.items(): if k.endswith(".weight") and v.ndim == 2 and v.shape[1] % 64 == 0: qw, sc = pack_int4_weight(v, 64) packed_sd[k] = ("int4", qw.cpu(), sc.cpu()) else: packed_sd[k] = ("raw", v.to(torch.bfloat16 if v.dtype == torch.float32 else v.dtype).cpu()) return packed_sd
def build_quant_decoder_layer( tcfg: Any, layer_idx: int, packed_sd: Dict[str, Any], device: str = "cuda",) -> nn.Module: with torch.device("meta"): block = qm.Qwen3_5DecoderLayer(tcfg, layer_idx=layer_idx)
# Replace leaf modules in attention & mlp with packed Int4Linear or materialize buffers def _set_attr(root_mod: nn.Module, path: str, val: nn.Module) -> None: parts = path.split(".") cur = root_mod for p in parts[:-1]: cur = getattr(cur, p) setattr(cur, parts[-1], val)
raw_sd: Dict[str, torch.Tensor] = {} for k, item in packed_sd.items(): if item[0] == "int4": _, qw, sc = item mod_name = k[: -len(".weight")] _set_attr(block, mod_name, Int4Linear(qw.to(device), sc.to(device))) else: raw_sd[k] = item[1]
# Materialize remaining non-Int4 parameters/buffers (norms, conv1d, A_log, dt_bias) for name, _ in list(block.named_parameters(recurse=True)): if name in raw_sd: parts = name.split(".") cur = block for p in parts[:-1]: cur = getattr(cur, p) setattr(cur, parts[-1], nn.Parameter(raw_sd[name].to(device), requires_grad=False)) for name, _ in list(block.named_buffers(recurse=True)): if name in raw_sd: parts = name.split(".") cur = block for p in parts[:-1]: cur = getattr(cur, p) cur.register_buffer(parts[-1], raw_sd[name].to(device)) block.eval() return block
def ensure_quantized_model_cache() -> Path: if QUANT_CACHE.exists(): return QUANT_CACHE CACHE_DIR.mkdir(parents=True, exist_ok=True) print(f"[Cache Build] One-time streaming of {HF_REPO} into compact Int4/Int8 training cache...", flush=True) t0 = time.time() spec = [s for s in MODEL_SPECS if s.slug == "qwen35_9b"][0] ts = TensorSource(spec)
print(" Fetching embed_tokens...", flush=True) emb_w = ts.fetch_tensor(spec.embed_key) emb_q, emb_s = pack_int8_rowwise(emb_w) del emb_w
print(" Fetching lm_head...", flush=True) lm_w = ts.fetch_tensor(spec.lm_head_key) lm_q, lm_s = pack_int8_rowwise(lm_w) del lm_w
norm_f_w = fetch_raw_bf16(ts, spec.norm_f_key).cpu()
layers_packed: List[Dict[str, Any]] = [] pool = ThreadPoolExecutor(max_workers=1) fut = pool.submit(fetch_layer_state_dict, ts, 0) try: for l in range(32): tl = time.time() sd = fut.result() if l + 1 < 32: fut = pool.submit(fetch_layer_state_dict, ts, l + 1) layers_packed.append(quantize_decoder_sd(sd)) del sd if (l + 1) % 8 == 0 or l == 31: print(f" Quantized layer {l+1:2d}/32 in {time.time()-tl:.1f}s (total {time.time()-t0:.1f}s)", flush=True) finally: pool.shutdown()
tmp = QUANT_CACHE.with_suffix(".tmp") torch.save( { "embed_q": emb_q, "embed_s": emb_s, "lm_q": lm_q, "lm_s": lm_s, "norm_f_w": norm_f_w, "layers": layers_packed, }, str(tmp), ) tmp.replace(QUANT_CACHE) sz_gb = QUANT_CACHE.stat().st_size / (1024 ** 3) print(f"[Cache Build] Saved {QUANT_CACHE} ({sz_gb:.2f} GiB) in {time.time()-t0:.1f}s", flush=True) return QUANT_CACHE
# ---------------------------------------------------------------------------# GGUF LoRA I/O + Reduced SVD Merge# ---------------------------------------------------------------------------
def read_gguf_lora_pairs(path: Path) -> Dict[int, Tuple[torch.Tensor, torch.Tensor, float]]: reader = gguf.GGUFReader(str(path)) raw: Dict[str, Tuple[np.ndarray, float]] = {} for t in reader.tensors: raw[t.name] = (np.array(t.data, copy=True), 1.0) alpha = 0.0 for fld in reader.fields.values(): if "lora.alpha" in fld.name: alpha = float(fld.parts[fld.data[0]][0]) out: Dict[int, Tuple[torch.Tensor, torch.Tensor]] = {} for L in FINTAN_LAYERS: ka = f"blk.{L}.ffn_down.weight.lora_a" kb = f"blk.{L}.ffn_down.weight.lora_b" if ka not in raw or kb not in raw: continue A = torch.from_numpy(raw[ka][0]).float() B = torch.from_numpy(raw[kb][0]).float() if A.shape[0] > A.shape[1]: A = A.T if B.shape[0] < B.shape[1]: B = B.T r = A.shape[0] eff_alpha = alpha if alpha > 0 else float(r) scale = eff_alpha / float(r) if abs(scale - 1.0) > 1e-6: A = A * math.sqrt(scale) B = B * math.sqrt(scale) out[L] = (A.contiguous(), B.contiguous()) return out
def export_lora_gguf(pairs_by_layer: Dict[int, Tuple[torch.Tensor, torch.Tensor]], out_path: Path) -> None: out_path.parent.mkdir(parents=True, exist_ok=True) first_A = next(iter(pairs_by_layer.values()))[0] rank = int(first_A.shape[0]) w = gguf.GGUFWriter(str(out_path), "qwen35") w.add_type("adapter") w.add_string("adapter.type", "lora") w.add_float32("adapter.lora.alpha", float(rank)) for L in sorted(pairs_by_layer.keys()): A, B = pairs_by_layer[L] # llama.cpp GGUF LoRA expects transposed shapes vs torch (in, r) for lora_a and (r, out) for lora_b? # Check exact shape convention in stage_and_analyze_fintan.py -> numpy F16 stored matching PEFT/gguf! a_np = A.detach().cpu().numpy().astype(np.float16) b_np = B.detach().cpu().numpy().astype(np.float16) w.add_tensor(f"blk.{L}.ffn_down.weight.lora_a", a_np, raw_dtype=gguf.GGMLQuantizationType.F16) w.add_tensor(f"blk.{L}.ffn_down.weight.lora_b", b_np, raw_dtype=gguf.GGMLQuantizationType.F16) w.write_header_to_file() w.write_kv_data_to_file() w.write_tensors_to_file() w.close()
def reduced_svd_recompress(dW: torch.Tensor, target_rank: int) -> Tuple[torch.Tensor, torch.Tensor]: """Exact rank-k SVD factorization dW [4096, 12288] -> (A [r, 12288], B [4096, r]).""" U, S, Vh = torch.linalg.svd(dW.float(), full_matrices=False) r = min(target_rank, int(S.numel())) s_root = torch.sqrt(S[:r]) B = U[:, :r] * s_root.unsqueeze(0) A = s_root.unsqueeze(1) * Vh[:r, :] return A.contiguous(), B.contiguous()
def cmd_merge(adapter_paths: List[Path], out_path: Path, target_rank: int) -> None: print(f"[Merge] Merging {len(adapter_paths)} adapters -> {out_path} (rank={target_rank})...", flush=True) loaded = [read_gguf_lora_pairs(p) for p in adapter_paths] dev = "cuda" if torch.cuda.is_available() else "cpu" merged: Dict[int, Tuple[torch.Tensor, torch.Tensor]] = {} for L in FINTAN_LAYERS: dW = torch.zeros((4096, 12288), device=dev, dtype=torch.float32) for ld in loaded: if L in ld: Ai, Bi = ld[L] dW.add_(Bi.to(dev) @ Ai.to(dev)) A, B = reduced_svd_recompress(dW, target_rank) frob = float(torch.linalg.norm(B @ A).item()) merged[L] = (A.cpu(), B.cpu()) print(f" L{L:2d}: merged ||dW||_F={frob:.3f} (rank={A.shape[0]})", flush=True) export_lora_gguf(merged, out_path) print(f"[Merge] Saved {out_path} ({out_path.stat().st_size / (1024**2):.2f} MiB)", flush=True)
# ---------------------------------------------------------------------------# Entity-Disambiguated Study Q&A Synthesizer (Strictly from facts.json)# ---------------------------------------------------------------------------
def _start_base_llama_server(port: int) -> subprocess.Popen: cmd = [ str(LLAMA_SERVER), "-m", str(BASE_GGUF), "-c", "4096", "-ctk", "q8_0", "-ctv", "q8_0", "-np", "1", "-ngl", "99", "--fit", "off", "--jinja", "--port", str(port), "--host", "127.0.0.1", ] log_fp = (ROOT / f"synth_server_p{port}.log").open("w", encoding="utf-8") proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT) proc._log_fp = log_fp # type: ignore[attr-defined] for _ in range(180): if proc.poll() is not None: raise RuntimeError(f"llama-server exited early with {proc.returncode}") try: with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2.0) as resp: if json.loads(resp.read().decode()).get("status") == "ok": return proc except Exception: pass time.sleep(0.5) raise TimeoutError("Timed out waiting for base llama-server")
def _stop_server(proc: subprocess.Popen) -> None: proc.terminate() try: proc.wait(timeout=10) except subprocess.TimeoutExpired: proc.kill() try: proc._log_fp.close() # type: ignore[attr-defined] except Exception: pass time.sleep(0.6)
def _deterministic_questions_for_fact(f: Dict[str, Any], siblings: List[Dict[str, Any]]) -> List[str]: subj = str(f.get("subject", "")).strip() rel = str(f.get("relation", "")).strip() val = str(f.get("value", "")).strip() dt = str(f.get("date", "")).strip() sib_hint = "" if len(siblings) > 1: sib_hint = f" ({rel})" q1 = f"Regarding {subj}{sib_hint} as of {dt}: what is {subj} {rel}?" q2 = f"What happened with {subj} ({rel}) as of {dt}?" # Simple subject-relation direct query without paren if unambiguous or concise if any(ord(c) > 127 for c in (subj + rel + val)): q2 = f"As of {dt}, regarding {subj}: {rel}?" return [q1, q2]
def cmd_synthesize_qa(facts_path: Path, out_path: Path, port: int = 8160, n_llm_per_fact: int = 6) -> Path: if out_path.exists(): print(f"[Synthesize-QA] Using cached study Q&A at {out_path}", flush=True) return out_path facts = json.loads(facts_path.read_text(encoding="utf-8")) by_subj: Dict[str, List[Dict[str, Any]]] = defaultdict(list) for idx, f in enumerate(facts): f_copy = dict(f) f_copy["_fact_id"] = idx by_subj[str(f.get("subject", "")).strip().lower()].append(f_copy)
print(f"[Synthesize-QA] Synthesizing ~{n_llm_per_fact + 2} disambiguated Q&A pairs for {len(facts)} facts...", flush=True) proc = _start_base_llama_server(port) t0 = time.time() records: List[Dict[str, Any]] = [] try: v1 = f"http://127.0.0.1:{port}/v1/chat/completions" for idx, f in enumerate(facts): subj = str(f.get("subject", "")).strip() rel = str(f.get("relation", "")).strip() val = str(f.get("value", "")).strip() dt = str(f.get("date", "")).strip() sibs = by_subj[subj.lower()] sib_notes = "" if len(sibs) > 1: others = [f"- ({s['relation']}) -> {s['value']}" for s in sibs if s["_fact_id"] != idx][:5] sib_notes = ( "\nSibling facts on the same subject (differentiate THIS fact's relation, NEVER mention any sibling answer value in your questions):\n" + "\n".join(others) )
prompt = ( f"Fact to study:\n" f" subject: {subj}\n" f" relation/aspect: {rel}\n" f" exact answer: {val}\n" f" date: {dt}\n" f"{sib_notes}\n\n" f"Write exactly {n_llm_per_fact} diverse, natural questions (ONLY a JSON array of strings) " f"whose exact answer is `{val}`.\n" f"Rules:\n" f"1) NEVER copy schema words like 'subject', 'object', or 'method' into the questions.\n" f"2) Vary question openers cleanly (Who/What/Where/When/Why/How/Which/By how much), " f"include both dated (`as of {dt}`, `in November 2026`, `in 2026`) and undated variants, and active/passive phrasing.\n" f"3) Preserve exact language (English, German, French, or Spanish).\n" f"4) Never include `{val}` or any sibling answer values inside a question.\n" f"5) Output ONLY a valid JSON array of {n_llm_per_fact} strings." ) body = { "model": "qwen3.5-9b", "messages": [{"role": "user", "content": prompt}], "max_tokens": 560, "temperature": 0.55, "seed": 42 + idx, "chat_template_kwargs": {"enable_thinking": False}, } llm_qs: List[str] = [] try: req = urllib.request.Request(v1, data=json.dumps(body).encode("utf-8"), headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=60.0) as resp: txt = json.loads(resp.read().decode("utf-8"))["choices"][0]["message"]["content"].strip() m = re.search(r"\[.*\]", txt, re.S) if m: arr = json.loads(m.group(0)) if isinstance(arr, list): for q in arr: if isinstance(q, str) and len(q.strip()) >= 8 and val.lower() not in q.lower(): llm_qs.append(q.strip()) except Exception: pass
all_qs = [] seen = set() for q in llm_qs: ql = q.lower() if ql not in seen: seen.add(ql) all_qs.append(q) if len(all_qs) >= n_llm_per_fact: break if len(all_qs) < 6: for q in _deterministic_questions_for_fact(f, sibs): ql = q.lower() if ql not in seen: seen.add(ql) all_qs.append(q) if len(all_qs) >= max(4, n_llm_per_fact): break
records.append({ "fact_id": idx, "subject": subj, "relation": rel, "value": val, "date": dt, "questions": all_qs, }) if (idx + 1) % 43 == 0 or idx + 1 == len(facts): el = time.time() - t0 eta = (el / (idx + 1)) * (len(facts) - idx - 1) print( f" [Synth {idx+1:3d}/{len(facts)}] total_qs={sum(len(r['questions']) for r in records)} | elapsed={el:.1f}s ETA={eta:.1f}s", flush=True, ) finally: _stop_server(proc)
out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(json.dumps(records, indent=2, ensure_ascii=False), encoding="utf-8") print(f"[Synthesize-QA] Wrote {sum(len(r['questions']) for r in records)} study pairs -> {out_path}", flush=True) return out_path
# ---------------------------------------------------------------------------# Tokenization, Layer-10 Activation Precompute & Nullspace-Protected Training# ---------------------------------------------------------------------------
def build_training_examples( qa_records: List[Dict[str, Any]], tok: Any, think_frac: float = 0.25, only_fact_ids: Optional[set] = None, seed: int = 42,) -> List[Dict[str, Any]]: rng = random.Random(seed) examples: List[Dict[str, Any]] = [] eos_suffix = "<|im_end|>\n" for rec in qa_records: if only_fact_ids is not None and rec["fact_id"] not in only_fact_ids: continue ans = str(rec["value"]).strip() for q_idx, q in enumerate(rec["questions"]): use_think = (rng.random() < think_frac) if use_think: prompt_str = tok.apply_chat_template( [{"role": "user", "content": q}], tokenize=False, add_generation_prompt=True, enable_thinking=True, ) target_str = "\n</think>\n\n" + ans + eos_suffix else: prompt_str = tok.apply_chat_template( [{"role": "user", "content": q}], tokenize=False, add_generation_prompt=True, enable_thinking=False, ) target_str = ans + eos_suffix p_ids = tok.encode(prompt_str, add_special_tokens=False) t_ids = tok.encode(target_str, add_special_tokens=False) examples.append({ "fact_id": rec["fact_id"], "full_ids": p_ids + t_ids, "prompt_len": len(p_ids), "is_think": use_think, }) return examples
def make_masks_and_pos( lengths: List[int], max_len: int, rotary: nn.Module, hidden_size: int, dev: str,) -> Tuple[torch.Tensor, torch.Tensor, Tuple[torch.Tensor, torch.Tensor], torch.Tensor]: bsz = len(lengths) mask_2d = torch.zeros((bsz, max_len), device=dev, dtype=torch.bfloat16) for b, L in enumerate(lengths): mask_2d[b, :L] = 1.0
# 4D causal + valid-key additive mask with diagonal always unmasked to prevent NaN on padded rows causal = torch.triu(torch.ones((max_len, max_len), device=dev, dtype=torch.bool), diagonal=1) mask_4d = torch.zeros((bsz, 1, max_len, max_len), device=dev, dtype=torch.bfloat16) neg_val = -1e4 for b, L in enumerate(lengths): invalid = causal.clone() if L < max_len: invalid[:, L:] = True invalid[torch.arange(L, max_len, device=dev), torch.arange(L, max_len, device=dev)] = False mask_4d[b, 0].masked_fill_(invalid, neg_val)
p4 = torch.arange(max_len, device=dev).view(1, 1, -1).expand(4, bsz, max_len) with torch.no_grad(): dummy = torch.empty((bsz, max_len, hidden_size), device=dev, dtype=torch.bfloat16) p_emb = rotary(dummy, p4[1:]) return mask_2d, mask_4d, p_emb, p4[0]
def precompute_h10_cache( examples: List[Dict[str, Any]], cache: Dict[str, Any], tcfg: Any, dev: str = "cuda",) -> List[torch.Tensor]: """Stream layers 0..10 once to precompute bf16 H_10 [L_i, 4096] for every example.""" t0 = time.time() n = len(examples) max_all = max(len(x["full_ids"]) for x in examples) pad_id = 0
emb_q = cache["embed_q"] emb_s = cache["embed_s"] # Gather per-example token embeddings [T_i, 4096] on CPU cleanly h_list: List[torch.Tensor] = [] for ex in examples: ids = torch.tensor(ex["full_ids"], dtype=torch.long) w_sel = emb_q[ids].to(torch.bfloat16) * emb_s[ids] h_list.append(w_sel.cpu())
with torch.device(dev): rotary = qm.Qwen3_5TextRotaryEmbedding(tcfg).to(dev)
batch_size = 16 order = sorted(range(n), key=lambda i: len(examples[i]["full_ids"]))
for l in range(11): block = build_quant_decoder_layer(tcfg, l, cache["layers"][l], device=dev) is_linear = (block.block_type == "linear_attention") out_list: List[Optional[torch.Tensor]] = [None] * n with torch.no_grad(): for s in range(0, n, batch_size): idxs = order[s : s + batch_size] lens = [h_list[i].shape[0] for i in idxs] tmax = max(lens) xb = torch.zeros((len(idxs), tmax, tcfg.hidden_size), device=dev, dtype=torch.bfloat16) for bi, orig_i in enumerate(idxs): xb[bi, : lens[bi]] = h_list[orig_i].to(dev) m2, m4, p_emb, pos_ids = make_masks_and_pos(lens, tmax, rotary, tcfg.hidden_size, dev) yb = block( xb, position_embeddings=p_emb, attention_mask=(m2 if is_linear else m4), position_ids=pos_ids, ) for bi, orig_i in enumerate(idxs): out_list[orig_i] = yb[bi, : lens[bi]].cpu() h_list = out_list # type: ignore[assignment] del block gc.collect() torch.cuda.empty_cache()
print(f"[H10 Precompute] Streamed L0..10 on {n} examples (max_len={max_all}) in {time.time()-t0:.1f}s", flush=True) return h_list
def build_nullspace_basis( protect_layers: List[Dict[int, Any]], dev: str,) -> Dict[int, torch.Tensor]: """Compute weighted right-singular preserve basis P_basis[L] = (S/sqrt(N))[:, None]*Vh per layer.""" basis: Dict[int, torch.Tensor] = {} for L in FINTAN_LAYERS: mats: List[torch.Tensor] = [] for m in protect_layers: if L not in m: continue val = torch.cat(m[L], dim=0) if isinstance(m[L], list) else m[L] if hasattr(val, "numel") and val.numel() > 0: mats.append(val.float()) if not mats: continue X = torch.cat(mats, dim=0).to(dev) # [N, 12288] # Reduce via SVD for clean, compact penalty evaluation each step _, S, Vh = torch.linalg.svd(X, full_matrices=False) keep = S > 1e-4 w = (S[keep] / math.sqrt(max(X.shape[0], 1))).unsqueeze(1) P = (w * Vh[keep]).contiguous() # [K, 12288] basis[L] = P return basis
class _LoRALinearLayerWrapper(nn.Module): """Wraps RMSNorm(1+w) cleanly at final hidden states."""
def __init__(self, norm_w: torch.Tensor, eps: float = 1e-6): super().__init__() self.register_buffer("weight", (1.0 + norm_w.float()).to(torch.bfloat16)) self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor: xf = x.float() v = xf.pow(2).mean(dim=-1, keepdim=True) out = xf * torch.rsqrt(v + self.eps) return (out * self.weight.float()).to(x.dtype)
def cmd_train( facts_path: Path, qa_cache_path: Path, out_gguf: Path, save_keys_path: Optional[Path] = None, protect_key_paths: Optional[List[Path]] = None, base_adapter_path: Optional[Path] = None, init_adapter_path: Optional[Path] = None, only_fact_ids: Optional[set] = None, replay_qa_path: Optional[Path] = None, replay_per_fact: int = 1, rank: int = 64, epochs: int = 6, lr: float = 4e-4, batch_size: int = 16, micro_batch: int = 4, lambda_null: float = 0.08, think_frac: float = 0.25, n_llm_per_fact: int = 4, smoke_test: bool = False,) -> Dict[str, Any]: t_all = time.time() dev = "cuda" tok, tcfg = load_tokenizer_and_tcfg() cache_path = ensure_quantized_model_cache() print(f"[Train] Loading quantized weights cache from {cache_path}...", flush=True) qcache = torch.load(str(cache_path), map_location="cpu", weights_only=False)
if smoke_test: dummy_recs = [ { "fact_id": i, "subject": f"Entity{i}", "relation": "won", "value": f"Value_{i}_Token", "date": "2026-11-26", "questions": [f"What did Entity{i} win as of 2026-11-26?", f"Which award went to Entity{i}?"], } for i in range(8) ] examples = build_training_examples(dummy_recs, tok, think_frac=think_frac) epochs = 1 batch_size = 8 micro_batch = 4 else: qa_cache_path = cmd_synthesize_qa(facts_path, qa_cache_path, n_llm_per_fact=n_llm_per_fact) qa_records = json.loads(qa_cache_path.read_text(encoding="utf-8")) examples = build_training_examples(qa_records, tok, think_frac=think_frac, only_fact_ids=only_fact_ids) if replay_qa_path is not None and replay_qa_path.exists(): rep_raw = json.loads(replay_qa_path.read_text(encoding="utf-8")) rep_recs = [] for rr in rep_raw: if only_fact_ids is not None and rr["fact_id"] in only_fact_ids: continue rc = dict(rr) rc["questions"] = list(rr["questions"][: max(1, int(replay_per_fact))]) rep_recs.append(rc) rep_ex = build_training_examples(rep_recs, tok, think_frac=think_frac, seed=99) print(f"[Train] Added {len(rep_ex)} study-QA replay examples from {replay_qa_path.name}", flush=True) examples.extend(rep_ex)
print( f"[Train] Examples={len(examples)} (think={sum(1 for e in examples if e['is_think'])}) | " f"rank={rank} | epochs={epochs} | lr={lr} | lambda_null={lambda_null}", flush=True, )
h10_list = precompute_h10_cache(examples, qcache, tcfg, dev=dev)
# Load preservation receptors (X_preserve_base + any prior night keys + optional extra protect keys) hk = torch.load(str(HOOK_CACHE), map_location="cpu", weights_only=False) protect_mats: List[Dict[int, torch.Tensor]] = [hk["X_preserve_base"]] if protect_key_paths: for kp in protect_key_paths: if kp.exists(): kd = torch.load(str(kp), map_location="cpu", weights_only=False) protect_mats.append(kd["X_night"]) print(f"[Train] Loaded orthogonal night keys from {kp.name}", flush=True) del hk null_basis = build_nullspace_basis(protect_mats, dev=dev)
base_pairs = read_gguf_lora_pairs(base_adapter_path) if (base_adapter_path and base_adapter_path.exists()) else None if base_pairs is not None: print(f"[Train] Attaching frozen base LoRA from {base_adapter_path.name}", flush=True)
init_pairs = read_gguf_lora_pairs(init_adapter_path) if (init_adapter_path and init_adapter_path.exists()) else None if init_pairs is not None: r_init = next(iter(init_pairs.values()))[0].shape[0] if r_init != rank: print(f"[Train] Adjusting rank from {rank} -> {r_init} to match --init-adapter", flush=True) rank = r_init
# Build Layers 11..31 on GPU + norm_f + Int8 lm_head layers_hi: List[nn.Module] = [] lora_params: List[nn.Parameter] = [] lora_modules: Dict[int, Int4Linear] = {} for l in range(11, 32): blk = build_quant_decoder_layer(tcfg, l, qcache["layers"][l], device=dev) if l in FINTAN_LAYERS: dp: Int4Linear = blk.mlp.down_proj # type: ignore[assignment] if base_pairs is not None and l in base_pairs: dp.attach_frozen_base_lora(base_pairs[l][0], base_pairs[l][1], device=dev) dp.attach_lora(rank=rank, init_ab=(init_pairs[l] if init_pairs and l in init_pairs else None), device=dev) lora_params.extend([dp.lora_A, dp.lora_B]) # type: ignore[list-item] lora_modules[l] = dp layers_hi.append(blk)
norm_f = _LoRALinearLayerWrapper(qcache["norm_f_w"]).to(dev) lm_head = Int8Linear(qcache["lm_q"].to(dev), qcache["lm_s"].to(dev)) with torch.device(dev): rotary = qm.Qwen3_5TextRotaryEmbedding(tcfg).to(dev) del qcache gc.collect() torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats() vram_loaded_mb = torch.cuda.memory_allocated() / (1024 ** 2) print(f"[Train] GPU allocated before training (L11..31 + Int8 lm_head + LoRA): {vram_loaded_mb:.0f} MiB", flush=True)
# Capture night input receptors at FINTAN_LAYERS if --save-keys requested (on direct answers) opt = torch.optim.AdamW(lora_params, lr=lr, betas=(0.9, 0.999), weight_decay=0.0) steps_per_epoch = math.ceil(len(examples) / batch_size) total_steps = epochs * steps_per_epoch warmup_steps = max(2, int(0.06 * total_steps))
def get_lr_mult(step: int) -> float: if step < warmup_steps: return float(step + 1) / float(warmup_steps) prog = float(step - warmup_steps) / float(max(total_steps - warmup_steps, 1)) return 0.05 + 0.95 * 0.5 * (1.0 + math.cos(math.pi * prog))
sched = torch.optim.lr_scheduler.LambdaLR(opt, get_lr_mult) rng = random.Random(1234) global_step = 0 ce_history: List[float] = []
for ep in range(1, epochs + 1): # Bucketed length sorting with local jitter for tiny padding overhead idxs = list(range(len(examples))) rng.shuffle(idxs) # Sort within chunks of 64 by length so microbatches of 4 have minimal padding chunks = [sorted(idxs[k : k + 64], key=lambda i: h10_list[i].shape[0]) for k in range(0, len(idxs), 64)] ordered = [i for ch in chunks for i in ch]
ep_ce = 0.0 ep_null = 0.0 ep_tok = 0 opt.zero_grad(set_to_none=True) accum_steps = max(1, batch_size // micro_batch) micro_count = 0
for s in range(0, len(ordered), micro_batch): mb_idxs = ordered[s : s + micro_batch] lens = [h10_list[i].shape[0] for i in mb_idxs] tmax = max(lens) xb = torch.zeros((len(mb_idxs), tmax, tcfg.hidden_size), device=dev, dtype=torch.bfloat16) label_pos_seqs: List[torch.Tensor] = [] label_tgt_vals: List[torch.Tensor] = []
for bi, oi in enumerate(mb_idxs): L_i = lens[bi] xb[bi, :L_i] = h10_list[oi].to(dev) p_len = examples[oi]["prompt_len"] ids = examples[oi]["full_ids"] # Target predicts ids[t+1] from hidden[t] for t in [p_len - 1 .. L_i - 2] pred_pos = torch.arange(p_len - 1, L_i - 1, device=dev, dtype=torch.long) tgt = torch.tensor(ids[p_len:], device=dev, dtype=torch.long) label_pos_seqs.append(pred_pos) label_tgt_vals.append(tgt)
m2, m4, p_emb, pos_ids = make_masks_and_pos(lens, tmax, rotary, tcfg.hidden_size, dev)
h = xb for idx_blk, blk in enumerate(layers_hi): attn_m = m2 if blk.block_type == "linear_attention" else m4 if idx_blk == 0: # Ensure input requires_grad so gradient checkpointing backpropagates cleanly h = h.detach().requires_grad_(True) h = checkpoint( lambda _h, _blk=blk, _pe=p_emb, _am=attn_m, _pi=pos_ids: _blk( _h, position_embeddings=_pe, attention_mask=_am, position_ids=_pi ), h, use_reentrant=False, )
# Gather ONLY target token positions across microbatch before norm_f & Int8 lm_head h_sel = torch.cat([h[bi, label_pos_seqs[bi]] for bi in range(len(mb_idxs))], dim=0) targets = torch.cat(label_tgt_vals, dim=0) logits = lm_head(norm_f(h_sel)).float() loss_ce = F.cross_entropy(logits, targets, label_smoothing=0.03)
loss_null = torch.zeros((), device=dev, dtype=torch.float32) for L, dp in lora_modules.items(): if L in null_basis: proj = dp.lora_B @ (dp.lora_A @ null_basis[L].T) loss_null = loss_null + proj.pow(2).sum()
n_mb_tok = int(targets.numel()) loss_total = (loss_ce + lambda_null * loss_null) / float(accum_steps) loss_total.backward()
ep_ce += float(loss_ce.item()) * n_mb_tok ep_null += float(loss_null.item()) ep_tok += n_mb_tok micro_count += 1
is_last_mb = (s + micro_batch >= len(ordered)) if micro_count % accum_steps == 0 or is_last_mb: torch.nn.utils.clip_grad_norm_(lora_params, 1.0) opt.step() sched.step() opt.zero_grad(set_to_none=True) global_step += 1
mean_ce = ep_ce / max(ep_tok, 1) mean_null = ep_null / max(micro_count, 1) ce_history.append(round(mean_ce, 4)) norms = [float(torch.linalg.norm(dp.lora_B @ dp.lora_A).item()) for dp in lora_modules.values()] mean_frob = sum(norms) / len(norms) el = time.time() - t_all eta = (el / ep) * (epochs - ep) print( f" [Epoch {ep}/{epochs}] loss_ce={mean_ce:.4f} | loss_null={mean_null:.4f} | " f"mean_||dW||_F={mean_frob:.3f} | elapsed={el:.1f}s | ETA={eta:.1f}s", flush=True, )
peak_vram_mb = torch.cuda.max_memory_allocated() / (1024 ** 2)
if smoke_test: print(f"[Smoke Test] Peak CUDA VRAM={peak_vram_mb:.0f} MiB (< 7500 OK!) | CE={ce_history}", flush=True) out_gguf.parent.mkdir(parents=True, exist_ok=True) export_lora_gguf({L: (dp.lora_A.detach().cpu(), dp.lora_B.detach().cpu()) for L, dp in lora_modules.items()}, out_gguf) print(f"[Smoke Test] Exported test GGUF -> {out_gguf} ({out_gguf.stat().st_size / 1024:.1f} KB)", flush=True) return {"smoke_test": True, "peak_vram_mb": round(peak_vram_mb, 1), "ce": ce_history}
# Export GGUF LoRA pairs = {L: (dp.lora_A.detach().cpu(), dp.lora_B.detach().cpu()) for L, dp in lora_modules.items()} export_lora_gguf(pairs, out_gguf) print(f"[Train] Exported {out_gguf} ({out_gguf.stat().st_size / (1024**2):.2f} MiB) | peak_VRAM={peak_vram_mb:.0f} MiB", flush=True)
# Optionally capture top-128 SVD input receptors at FINTAN_LAYERS across trained examples for future --protect-keys if save_keys_path is not None: print(f"[Save-Keys] Capturing top-128 SVD receptors at {FINTAN_LAYERS} -> {save_keys_path}...", flush=True) cap_rows: Dict[int, List[torch.Tensor]] = {L: [] for L in FINTAN_LAYERS} handles = [] cur_spans: List[Tuple[int, int]] = []
def make_hook(layer_id: int): def _hk(_m, inp): x_in = inp[0].detach() for bi, (p0, l0) in enumerate(cur_spans): cap_rows[layer_id].append(x_in[bi, p0 - 1 : l0 - 1].to(torch.float16).cpu()) return _hk
for L, dp in lora_modules.items(): handles.append(dp.register_forward_pre_hook(make_hook(L)))
# Use direct examples slice (up to 384 diverse target spans) direct_idxs = [i for i, e in enumerate(examples) if not e["is_think"]][:384] with torch.no_grad(): for s in range(0, len(direct_idxs), 8): mb = direct_idxs[s : s + 8] lens = [h10_list[i].shape[0] for i in mb] tmax = max(lens) xb = torch.zeros((len(mb), tmax, tcfg.hidden_size), device=dev, dtype=torch.bfloat16) cur_spans = [(examples[i]["prompt_len"], lens[bi]) for bi, i in enumerate(mb)] for bi, oi in enumerate(mb): xb[bi, : lens[bi]] = h10_list[oi].to(dev) m2, m4, p_emb, pos_ids = make_masks_and_pos(lens, tmax, rotary, tcfg.hidden_size, dev) h = xb for blk in layers_hi: h = blk(h, position_embeddings=p_emb, attention_mask=(m2 if blk.block_type == "linear_attention" else m4), position_ids=pos_ids) for hd in handles: hd.remove()
x_night: Dict[int, torch.Tensor] = {} for L in FINTAN_LAYERS: if not cap_rows[L]: continue mat = torch.cat(cap_rows[L], dim=0).float() _, S_n, Vh_n = torch.linalg.svd(mat.to(dev), full_matrices=False) k = min(128, int(S_n.numel())) # Store energy-weighted receptor basis [k, 12288] so build_nullspace_basis works directly x_night[L] = ((S_n[:k] / math.sqrt(max(mat.shape[0], 1))).unsqueeze(1) * Vh_n[:k]).to(torch.float16).cpu() save_keys_path.parent.mkdir(parents=True, exist_ok=True) torch.save({"X_night": x_night}, str(save_keys_path)) print(f"[Save-Keys] Saved {save_keys_path} ({save_keys_path.stat().st_size / (1024**2):.2f} MiB)", flush=True)
# Free all CUDA state cleanly before caller launches llama-server del layers_hi, norm_f, lm_head, lora_params, lora_modules, null_basis gc.collect() torch.cuda.empty_cache() return { "out_gguf": str(out_gguf), "size_mb": round(out_gguf.stat().st_size / (1024 ** 2), 2), "peak_vram_mb": round(peak_vram_mb, 1), "ce_history": ce_history, "elapsed_s": round(time.time() - t_all, 1), }
def cmd_eval_study(adapter_path: Path, qa_cache_path: Path, out_path: Path, port: int = 8161) -> Path: """Evaluate an adapter purely on 1 study question per fact (zero check_questions access) to find hard facts.""" sys.path.insert(0, str(UPSTREAM / "scripts")) from run_transformers import right as fintan_right # noqa: E402
qa = json.loads(qa_cache_path.read_text(encoding="utf-8")) cmd = [ str(LLAMA_SERVER), "-m", str(BASE_GGUF), "--lora", str(adapter_path), "-c", "4096", "-ctk", "q8_0", "-ctv", "q8_0", "-np", "1", "-ngl", "99", "--fit", "off", "--jinja", "--port", str(port), "--host", "127.0.0.1", ] log_fp = (ROOT / f"eval_study_p{port}.log").open("w", encoding="utf-8") proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT) proc._log_fp = log_fp # type: ignore[attr-defined] misses: List[int] = [] passed = 0 try: for _ in range(180): if proc.poll() is not None: raise RuntimeError(f"llama-server exited early with {proc.returncode}") try: with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2.0) as resp: if json.loads(resp.read().decode()).get("status") == "ok": break except Exception: pass time.sleep(0.5)
v1 = f"http://127.0.0.1:{port}/v1/chat/completions" for idx, rec in enumerate(qa): q = rec["questions"][0] gold = rec["value"] body = { "model": "qwen3.5-9b", "messages": [{"role": "user", "content": q}], "max_tokens": 64, "temperature": 0.0, "seed": 42, "cache_prompt": False, "chat_template_kwargs": {"enable_thinking": False}, } req = urllib.request.Request(v1, data=json.dumps(body).encode("utf-8"), headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=60.0) as resp: ans = json.loads(resp.read().decode("utf-8"))["choices"][0]["message"].get("content") or "" ok = bool(fintan_right(ans, gold, q)) passed += int(ok) if not ok: misses.append(rec["fact_id"]) finally: _stop_server(proc)
res = {"adapter": str(adapter_path), "study_pass": passed, "total": len(qa), "missed_fact_ids": misses} out_path.write_text(json.dumps(res, indent=2), encoding="utf-8") print(f"[Eval-Study] {adapter_path.name}: {passed}/{len(qa)} study questions right | {len(misses)} hard fact_ids -> {out_path}", flush=True) return out_path
def main() -> None: ap = argparse.ArgumentParser(description="Nullspace-Protected Self-Learning LoRA Engine for Fintan-9B") sub = ap.add_subparsers(dest="cmd", required=True)
p_syn = sub.add_parser("synthesize-qa") p_syn.add_argument("--facts", type=Path, required=True) p_syn.add_argument("--out", type=Path, required=True) p_syn.add_argument("--port", type=int, default=8160) p_syn.add_argument("--n-llm", type=int, default=4)
p_tr = sub.add_parser("train") p_tr.add_argument("--facts", type=Path, default=UPSTREAM / "updates" / "2026-11-23" / "facts.json") p_tr.add_argument("--qa-cache", type=Path, default=ROOT / "study_qa_cache.json") p_tr.add_argument("--out", type=Path, default=ADAPTERS / "fintan_wsp_v2_test.gguf") p_tr.add_argument("--save-keys", type=Path, default=None) p_tr.add_argument("--protect-keys", type=Path, nargs="*", default=None) p_tr.add_argument("--base-adapter", type=Path, default=None) p_tr.add_argument("--init-adapter", type=Path, default=None) p_tr.add_argument("--only-fact-ids", type=Path, default=None) p_tr.add_argument("--replay-qa", type=Path, default=None) p_tr.add_argument("--replay-per-fact", type=int, default=1) p_tr.add_argument("--n-llm", type=int, default=4) p_tr.add_argument("--rank", type=int, default=64) p_tr.add_argument("--epochs", type=int, default=6) p_tr.add_argument("--lr", type=float, default=4e-4) p_tr.add_argument("--batch-size", type=int, default=16) p_tr.add_argument("--micro-batch", type=int, default=4) p_tr.add_argument("--lambda-null", type=float, default=0.08) p_tr.add_argument("--think-frac", type=float, default=0.25) p_tr.add_argument("--smoke-test", action="store_true")
p_mg = sub.add_parser("merge") p_mg.add_argument("--adapters", type=Path, nargs="+", required=True) p_mg.add_argument("--out", type=Path, required=True) p_mg.add_argument("--rank", type=int, default=96)
p_es = sub.add_parser("eval-study") p_es.add_argument("--adapter", type=Path, required=True) p_es.add_argument("--qa-cache", type=Path, required=True) p_es.add_argument("--out", type=Path, required=True) p_es.add_argument("--port", type=int, default=8161)
args = ap.parse_args() if args.cmd == "synthesize-qa": cmd_synthesize_qa(args.facts, args.out, port=args.port, n_llm_per_fact=args.n_llm) elif args.cmd == "train": only_ids = None if args.only_fact_ids is not None: data = json.loads(args.only_fact_ids.read_text(encoding="utf-8")) only_ids = set(data["missed_fact_ids"] if isinstance(data, dict) else data) cmd_train( facts_path=args.facts, qa_cache_path=args.qa_cache, out_gguf=args.out, save_keys_path=args.save_keys, protect_key_paths=args.protect_keys, base_adapter_path=args.base_adapter, init_adapter_path=args.init_adapter, only_fact_ids=only_ids, replay_qa_path=args.replay_qa, replay_per_fact=args.replay_per_fact, rank=args.rank, epochs=args.epochs, lr=args.lr, batch_size=args.batch_size, micro_batch=args.micro_batch, lambda_null=args.lambda_null, think_frac=args.think_frac, n_llm_per_fact=args.n_llm, smoke_test=args.smoke_test, ) elif args.cmd == "merge": cmd_merge(args.adapters, args.out, target_rank=args.rank) elif args.cmd == "eval-study": cmd_eval_study(args.adapter, args.qa_cache, args.out, port=args.port)
if __name__ == "__main__": main()71 unmodified lines72737475767796 unmodified lines1741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134143 unmodified lines41841942042142242314 unmodified lines438439440441442443157 unmodified lines6016026036046056065 unmodified lines61261361461561661761861962062162262362462562662762862963063163263363416 unmodified lines65165265365465565665765865966066130 unmodified lines6926936946956966973 unmodified lines70170270370470570670770870971071124 unmodified lines73673773873974074174274374474574674710 unmodified lines75875976076176276376471 unmodified lines"adapters/fintan_2026_11_23_null_g1.gguf","Upload right-nullspace-projected Fintan LoRA (gamma=1.0)",),]REQUIREMENTS_TXT = "\n".join([96 unmodified linesdef make_portable_runner_source() -> str:"""Create cross-platform portable OpenAI-compatible runtime server script."""return '''"""Standalone OpenAI-Compatible Runtime Server for Unified Fintan-9B + WSP.Launches Qwen3.5-9B-Q4_K_M on llama-server with all 13 LoRA slots preloaded cleanly:[0..10] Qwen3.5-9B WSP subspaces S1..S11 (agentic + Terminal-Bench control)[11] Fintan-9B continual-learning LoRA adapter (default: fintan_2026_11_23_r512.gguf)[12] S12 Reasoning-Bridge adapter (wsp_s12_fintan_think_bridge.gguf)Exposes an OpenAI-compatible `/v1/chat/completions` proxy routing across:- Regime 1: Pure Qwen3.5-9B + WSP S1..S11 (general / agentic / coding / math / Terminal-Bench)- Regime 2: Fintan Two-Phase Reasoning-Boundary / Direct Recall (episodic non-tool queries)- Regime 3: Two-Phase Weight-Space Recall-Then-Act (episodic queries + tools, zero RAG)"""from __future__ import annotationsimport argparseimport http.serverimport jsonimport shutilimport socketserverimport subprocessimport sysimport timeimport urllib.requestfrom pathlib import Pathfrom typing import Any, Dict, ListREPO_ROOT = Path(__file__).resolve().parentsys.path.insert(0, str(REPO_ROOT))from fintan_wsp_router import UnifiedFintanWSPRouter, adapter_paths_13 # noqa: E402def build_llama_cmd(llama_server: str,model_path: Path,lora_paths: List[Path],llama_port: int,host: str,ctx: int,ngl: int = 99,) -> List[str]:cmd = [str(llama_server),"-m", str(model_path),]for lp in lora_paths:cmd.extend(["--lora", str(lp)])cmd.extend(["--lora-init-without-apply","-c", str(ctx),"-ctk", "q8_0","-ctv", "q8_0","-np", "1","-ngl", str(ngl),"--fit", "off","--jinja","--port", str(llama_port),"--host", host,])return cmdclass ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):daemon_threads = Truedef make_handler(router: UnifiedFintanWSPRouter, llama_url: str):class ProxyHandler(http.server.BaseHTTPRequestHandler):def log_message(self, format: str, *args: Any) -> None:returndef _send_json(self, code: int, obj: Any) -> None:raw = json.dumps(obj).encode("utf-8")self.send_response(code)self.send_header("Content-Type", "application/json")self.send_header("Content-Length", str(len(raw)))self.end_headers()self.wfile.write(raw)def do_GET(self) -> None:if self.path.startswith("/health"):try:with urllib.request.urlopen(f"{llama_url}/health", timeout=2.0) as r:self._send_json(200, json.loads(r.read().decode("utf-8")))except Exception as exc:self._send_json(503, {"status": "error", "detail": str(exc)})returnif self.path.startswith("/v1/models"):self._send_json(200,{"object": "list","data": [{"id": "fintan-9b-wsp", "object": "model", "owned_by": "wsp"}],},)returnself._send_json(404, {"error": f"Unknown GET path: {self.path}"})def do_POST(self) -> None:if not self.path.startswith("/v1/chat/completions"):self._send_json(404, {"error": f"Unknown POST path: {self.path}"})returntry:length = int(self.headers.get("Content-Length") or "0")req = json.loads(self.rfile.read(length).decode("utf-8"))kwargs = req.get("chat_template_kwargs") or {}out = router.chat_completion(server_url=llama_url,messages=req.get("messages") or [],tools=req.get("tools"),response_format=req.get("response_format"),max_tokens=int(req.get("max_tokens") or 512),temperature=float(req.get("temperature") or 0.0),enable_thinking=bool(kwargs.get("enable_thinking", True)),)res = dict(out["raw_response"])res["wsp_meta"] = {"regime": out["regime"],"night": out["night"],"scales_used": out["scales_used"],"phase1_ms": out["phase1_ms"],"switch_ms": out["switch_ms"],}self._send_json(200, res)except Exception as exc:self._send_json(500, {"error": str(exc)})return ProxyHandlerdef main() -> None:default_llama = shutil.which("llama-server") or shutil.which("llama-server.exe") or "llama-server"ap = argparse.ArgumentParser(description="Unified Fintan-9B + WSP runtime server")ap.add_argument("--model", type=Path, default=REPO_ROOT / "gguf" / "Qwen3.5-9B-Q4_K_M.gguf")ap.add_argument("--llama-server", type=str, default=default_llama)ap.add_argument("--adapters-dir", type=Path, default=REPO_ROOT / "adapters")ap.add_argument("--fintan-adapter", type=Path, default=REPO_ROOT / "adapters" / "fintan_2026_11_23_r512.gguf")ap.add_argument("--s12-adapter", type=Path, default=REPO_ROOT / "adapters" / "wsp_s12_fintan_think_bridge.gguf")ap.add_argument("--manifest", type=Path, default=REPO_ROOT / "fintan_data" / "manifest.json")ap.add_argument("--port", type=int, default=8900)ap.add_argument("--llama-port", type=int, default=8901)ap.add_argument("--host", type=str, default="127.0.0.1")ap.add_argument("--ctx", type=int, default=16384)ap.add_argument("--fintan-scale", type=float, default=1.0)ap.add_argument("--s12-scale", type=float, default=0.8)ap.add_argument("--dry-run", action="store_true")args = ap.parse_args()if not args.model.exists():raise FileNotFoundError(f"Base GGUF missing: {args.model}")if not args.manifest.exists():raise FileNotFoundError(f"Manifest missing: {args.manifest}")lora_paths = adapter_paths_13(args.fintan_adapter, args.s12_adapter, adapters_dir=args.adapters_dir)router = UnifiedFintanWSPRouter(fintan_scale=args.fintan_scale,s12_scale=args.s12_scale,manifest_path=args.manifest,adapters_dir=args.adapters_dir,)cmd = build_llama_cmd(args.llama_server, args.model, lora_paths, llama_port=args.llama_port, host=args.host, ctx=args.ctx)if args.dry_run:r_direct = router.night_router.route("Who is the European Commission president as of November 23, 2026?")r_gen = router.night_router.route("Write a Python function to sort intervals by start time.")r_tool = router.night_router.route("Email analyst@firm.local about Jensen Huang's NVIDIA reinstatement.")dec_tool = router.wsp_router.route([{"role": "user", "content": "Run pytest in /workspace"}],tools=[{"type": "function", "function": {"name": "exec", "parameters": {"type": "object", "properties": {"command": {"type": "string"}}}}}],)print(json.dumps({"status": "dry_run_ok","proxy_url": f"http://{args.host}:{args.port}/v1/chat/completions","llama_url": f"http://{args.host}:{args.llama_port}","model": str(args.model),"wsp_model_name": router.wsp_router.model_name,"adapters_loaded": [f"[{i}] {p.name}" for i, p in enumerate(lora_paths)],"fintan_scale": args.fintan_scale,"s12_scale": args.s12_scale,"smoke_routes": {"episodic_night": r_direct,"general_code_night": r_gen,"episodic_tool_night": r_tool,"wsp_exec_regime": dec_tool.regime,},},indent=2,))returnlog_fp = (REPO_ROOT / "runtime_llama_server.log").open("w", encoding="utf-8")proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT)llama_url = f"http://{args.host}:{args.llama_port}"try:ready = Falsefor _ in range(180):if proc.poll() is not None:raise RuntimeError(f"llama-server exited early with {proc.returncode}")try:with urllib.request.urlopen(f"{llama_url}/health", timeout=2.0) as resp:if json.loads(resp.read().decode()).get("status") == "ok":ready = Truebreakexcept Exception:passtime.sleep(0.5)if not ready:raise TimeoutError("Timed out waiting for llama-server /health")httpd = ThreadingHTTPServer((args.host, args.port), make_handler(router, llama_url))print(f"Unified Fintan-9B + WSP server listening on http://{args.host}:{args.port}/v1", flush=True)print(f"Backend llama-server on {llama_url} ({len(lora_paths)} LoRA adapters)", flush=True)try:httpd.serve_forever()finally:httpd.server_close()finally:proc.terminate()try:proc.wait(timeout=10)except subprocess.TimeoutExpired:proc.kill()log_fp.close()if __name__ == "__main__":main()'''def build_readme(3 unmodified linessynth: Dict[str, Any],cal: Dict[str, Any],res: Dict[str, Any],) -> str:"""Build Hugging Face Model Card strictly from verified JSON metrics."""ra_base = base_audit["router_audit"]14 unmodified linessd_wsp = res["suite_d_tbench20"]by_suite = sc_wsp["by_suite"]repo_id = f"{username}/{REPO_NAME}"suite_rows = [157 unmodified lines---## Quick Start (Standalone Local Server)Download the repository (`gguf/Qwen3.5-9B-Q4_K_M.gguf`, `adapters/`, `fintan_data/`, runtime scripts) and launch the OpenAI-compatible server with [`llama.cpp`](https://github.com/ggml-org/llama.cpp) (`llama-server` on `PATH` or passed via `--llama-server`):5 unmodified lines# Verify all 13 LoRA slots and routing without touching GPU:python run_fintan_wsp.py --dry-run# Launch OpenAI-compatible server on http://127.0.0.1:8900/v1 (use --fintan-adapter adapters/fintan_2026_11_23_null_g5.gguf for nullspace variant):python run_fintan_wsp.py --llama-server llama-server```---## Repository Structure- `gguf/Qwen3.5-9B-Q4_K_M.gguf` — Quantized base GGUF (`5.29 GiB`).- `adapters/` — All `16` GGUF LoRA adapters:- `wsp_s1_think.gguf` .. `wsp_s11_term_code.gguf` (`Qwen3.5-9B` WSP agentic + Terminal-Bench subspaces)- `fintan_2026_11_23_r512.gguf`, `fintan_2026_11_23_null_g5.gguf`, `fintan_2026_11_23_null_g20.gguf`, `fintan_2026_11_23_null_g1.gguf`- `wsp_s12_fintan_think_bridge.gguf`- `run_fintan_wsp.py`, `fintan_wsp_router.py`, `dynamic_router_9s.py` — Portable OpenAI server + 13-LoRA router.- `fintan_data/` — Upstream `manifest.json`, `background.json`, `updates/2026-11-23/` facts & evaluation questions, and `door/night_router*.py`.- `results/` — Complete verified outputs (`spectral_analysis.json`, `baseline_audit.json`, `wsp_synthesis_report.json`, `wsp_cal_report.json`, `fintan_wsp_results.json`, `fintan_9b_wsp_report.md`).- `scripts/` — Full pipeline scripts (`stage_and_analyze_fintan.py`, `audit_fintan_baseline.py`, `build_fintan_wsp.py`, `validate_fintan_wsp_cal.py`, `evaluate_fintan_wsp.py`, `smoke_test_fintan.py`, `upload_fintan_to_hf.py`)."""16 unmodified linessynth: Dict[str, Any],cal: Dict[str, Any],res: Dict[str, Any],) -> List[CommitOperationAdd]:stage_dir.mkdir(parents=True, exist_ok=True)staged_readme = stage_dir / "README.md"staged_readme.write_text(build_readme(username, spec, base_audit, synth, cal, res), encoding="utf-8")staged_req = stage_dir / "requirements.txt"staged_req.write_text(REQUIREMENTS_TXT, encoding="utf-8")30 unmodified lines(UPSTREAM / "door" / "night_router2.py", "fintan_data/door/night_router2.py"),(UPSTREAM / "door" / "night_router3.py", "fintan_data/door/night_router3.py"),(UPSTREAM / "door" / "night_router4.py", "fintan_data/door/night_router4.py"),]file_pairs.extend(fintan_data_files)3 unmodified lines(ROOT / "wsp_synthesis_report.json", "results/wsp_synthesis_report.json"),(ROOT / "wsp_cal_report.json", "results/wsp_cal_report.json"),(ROOT / "fintan_wsp_results.json", "results/fintan_wsp_results.json"),(REPORT_LOCAL, "results/fintan_9b_wsp_report.md"),]file_pairs.extend(result_files)script_files = ["stage_and_analyze_fintan.py","audit_fintan_baseline.py","build_fintan_wsp.py",24 unmodified linessynth = json.loads((ROOT / "wsp_synthesis_report.json").read_text(encoding="utf-8"))cal = json.loads((ROOT / "wsp_cal_report.json").read_text(encoding="utf-8"))res = json.loads((ROOT / "fintan_wsp_results.json").read_text(encoding="utf-8"))assert res["suite_a3"]["passed"] == 154assert res["suite_a4"]["clean_pass"] == 154assert res["suite_b"]["b1"]["fintan_wsp_think"]["full_pass"] == 11assert res["suite_b"]["b1"]["fintan_wsp_nothink"]["full_pass"] == 11assert cal["router_audit"]["check_172_routed"] == 172for lp, _, _ in LARGE_GGUF_UPLOADS:if not lp.exists():10 unmodified linescreate_repo(repo_id=repo_id, token=token, repo_type="model", private=False, exist_ok=True)stage_dir = ROOT / "_hf_staging"ops = collect_operations(username, stage_dir, spec, base_audit, synth, cal, res)ops_mib = sum(Path(op.path_or_fileobj).stat().st_size for op in ops) / (1024 * 1024)large_gib = sum(p.stat().st_size for p, _, _ in LARGE_GGUF_UPLOADS) / (1024 ** 3)71 unmodified lines7273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112296 unmodified lines2192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543 unmodified lines35835936036136236336414 unmodified lines379380381382383384385386387388389390157 unmodified lines5485495505515525535545555565575585595605615625635645655665675685695705715725 unmodified lines57857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161216 unmodified lines62963063163263363463563663763863964030 unmodified lines6716726736746756766776786793 unmodified lines68368468568668768868969069169269369469569624 unmodified lines72172272372472572672772872973073173273373473573673773810 unmodified lines74975075175275375475571 unmodified lines"adapters/fintan_2026_11_23_null_g1.gguf","Upload right-nullspace-projected Fintan LoRA (gamma=1.0)",),(ADAPTERS_FINTAN / "fintan_r512_patched.gguf","adapters/fintan_r512_patched.gguf","Upload Option 3 nullspace-patched rank-544 Fintan LoRA (162/172 = 94.2%, default)",),(ADAPTERS_FINTAN / "fintan_r512_patch_r32.gguf","adapters/fintan_r512_patch_r32.gguf","Upload Option 3 rank-32 hard-fact refinement patch delta for r512",),(ADAPTERS_FINTAN / "fintan_2026_11_23_wsp_v2_r128.gguf","adapters/fintan_2026_11_23_wsp_v2_r128.gguf","Upload Option 1 open-source Fintan-WSP-v2 rank-128 LoRA (140/172, native think)",),(ADAPTERS_FINTAN / "fintan_2026_11_23_wsp_v2_r64.gguf","adapters/fintan_2026_11_23_wsp_v2_r64.gguf","Upload Option 1 open-source Fintan-WSP-v2 rank-64 LoRA (25/30 Forced-ON Holdout)",),(ADAPTERS_FINTAN / "fintan_wsp_v2_merged_n1n2.gguf","adapters/fintan_wsp_v2_merged_n1n2.gguf","Upload Option 2 lossless Night-1 + Night-2 orthogonally merged rank-160 LoRA",),(ADAPTERS_FINTAN / "fintan_night2_wsp_r32.gguf","adapters/fintan_night2_wsp_r32.gguf","Upload Option 2 Night-2 synthetic incremental rank-32 LoRA",),(ADAPTERS_FINTAN / "fintan_v2_r128_patched.gguf","adapters/fintan_v2_r128_patched.gguf","Upload Option 3 hard-fact patched v2 rank-160 LoRA",),(ADAPTERS_FINTAN / "fintan_v2_r128_patch_r32.gguf","adapters/fintan_v2_r128_patch_r32.gguf","Upload Option 3 rank-32 hard-fact patch delta for v2_r128",),(ADAPTERS_FINTAN / "fintan_2026_11_23_wsp_v2_r128_keys.pt","adapters/fintan_2026_11_23_wsp_v2_r128_keys.pt","Upload Night-1 v2_r128 orthogonal receptor keys for continual protection",),]REQUIREMENTS_TXT = "\n".join([96 unmodified linesdef make_portable_runner_source() -> str:"""Transform local run_fintan_wsp.py into cross-platform portable HF server script."""src = (ROOT / "run_fintan_wsp.py").read_text(encoding="utf-8")old_hdr = ('ROOT = Path(r"C:\\Users\\jhjwi\\.gemini\\antigravity\\scratch\\fintan-9b-wsp")\n''ADAPTERS = ROOT / "adapters"\n''PIPELINE_DIR = Path(r"C:\\Users\\jhjwi\\.gemini\\antigravity\\scratch\\wsp-5model-pipeline")\n''BASE_GGUF = PIPELINE_DIR / "models" / "qwen35_9b" / "Qwen3.5-9B-Q4_K_M.gguf"\n''LLAMA_SERVER = Path(r"C:\\Users\\jhjwi\\.gemini\\antigravity\\scratch\\inkling2-mini-wsp\\llama.cpp\\llama-server.exe")\n''STATE_DIR = ROOT / "_live_teach"\n\n''sys.path.insert(0, str(ROOT))\n''sys.path.insert(0, str(ROOT / "upstream" / "door"))')new_hdr = ('REPO_ROOT = Path(__file__).resolve().parent\n''ROOT = REPO_ROOT\n''ADAPTERS = REPO_ROOT / "adapters"\n''BASE_GGUF = REPO_ROOT / "gguf" / "Qwen3.5-9B-Q4_K_M.gguf"\n''UPSTREAM_DOOR = REPO_ROOT / "fintan_data" / "door"\n''if not UPSTREAM_DOOR.exists():\n'' UPSTREAM_DOOR = REPO_ROOT.parent / "upstream" / "door"\n''LLAMA_SERVER = shutil.which("llama-server") or shutil.which("llama-server.exe") or "llama-server"\n''STATE_DIR = REPO_ROOT / "_live_teach"\n\n''sys.path.insert(0, str(REPO_ROOT))\n''sys.path.insert(0, str(UPSTREAM_DOOR))')assert old_hdr in src, "Failed to locate header in run_fintan_wsp.py"src = src.replace(old_hdr, new_hdr, 1)old_learn_script = ' str(ROOT / "learn_wsp.py"),'new_learn_script = (' str((REPO_ROOT / "scripts" / "learn_wsp.py") ''if (REPO_ROOT / "scripts" / "learn_wsp.py").exists() ''else (REPO_ROOT / "learn_wsp.py")),')assert old_learn_script in src, "Failed to locate learn_wsp.py path in run_fintan_wsp.py"src = src.replace(old_learn_script, new_learn_script, 1)old_cmd = ("def build_llama_cmd(\n"" lora_paths: List[Path],\n"" llama_port: int,\n"" host: str,\n"" ctx: int,\n"" ngl: int = 99,\n"") -> List[str]:\n"" cmd = [\n"" str(LLAMA_SERVER),\n"' "-m", str(BASE_GGUF),\n'" ]")new_cmd = ("def build_llama_cmd(\n"" llama_server: str,\n"" model_path: Path,\n"" lora_paths: List[Path],\n"" llama_port: int,\n"" host: str,\n"" ctx: int,\n"" ngl: int = 99,\n"") -> List[str]:\n"" cmd = [\n"" str(llama_server),\n"' "-m", str(model_path),\n'" ]")assert old_cmd in src, "Failed to locate build_llama_cmd in run_fintan_wsp.py"src = src.replace(old_cmd, new_cmd, 1)old_ap = (' ap = argparse.ArgumentParser(description="Unified Fintan-9B + WSP runtime server")\n'' ap.add_argument("--port", type=int, default=8900)\n'' ap.add_argument("--llama-port", type=int, default=8901)\n'' ap.add_argument("--host", type=str, default="127.0.0.1")\n'' ap.add_argument("--ctx", type=int, default=16384)\n'' ap.add_argument("--fintan-adapter", type=Path, default=ADAPTERS / "fintan_r512_patched.gguf")\n'' ap.add_argument("--s12-adapter", type=Path, default=ADAPTERS / "wsp_s12_fintan_think_bridge.gguf")\n'' ap.add_argument("--fintan-scale", type=float, default=1.0)\n'' ap.add_argument("--s12-scale", type=float, default=0.8)\n'' ap.add_argument("--dry-run", action="store_true")\n'" args = ap.parse_args()\n\n"" if not BASE_GGUF.exists():\n"' raise FileNotFoundError(f"Base GGUF missing: {BASE_GGUF}")\n'" lora_paths = adapter_paths_13(args.fintan_adapter, args.s12_adapter)\n"" missing = [str(p) for p in lora_paths if not p.exists()]\n"" if missing:\n"' raise FileNotFoundError(f"Missing LoRA files: {missing}")\n\n'" router = UnifiedFintanWSPRouter(\n"" fintan_scale=args.fintan_scale,\n"" s12_scale=args.s12_scale,\n"" )\n"" cmd = build_llama_cmd(lora_paths, llama_port=args.llama_port, host=args.host, ctx=args.ctx)")new_ap = (' ap = argparse.ArgumentParser(description="Unified Fintan-9B + WSP runtime server")\n'' ap.add_argument("--model", type=Path, default=BASE_GGUF)\n'' ap.add_argument("--llama-server", type=str, default=LLAMA_SERVER)\n'' ap.add_argument("--adapters-dir", type=Path, default=ADAPTERS)\n'' ap.add_argument("--manifest", type=Path, default=REPO_ROOT / "fintan_data" / "manifest.json")\n'' ap.add_argument("--port", type=int, default=8900)\n'' ap.add_argument("--llama-port", type=int, default=8901)\n'' ap.add_argument("--host", type=str, default="127.0.0.1")\n'' ap.add_argument("--ctx", type=int, default=16384)\n'' ap.add_argument("--fintan-adapter", type=Path, default=ADAPTERS / "fintan_r512_patched.gguf")\n'' ap.add_argument("--s12-adapter", type=Path, default=ADAPTERS / "wsp_s12_fintan_think_bridge.gguf")\n'' ap.add_argument("--fintan-scale", type=float, default=1.0)\n'' ap.add_argument("--s12-scale", type=float, default=0.8)\n'' ap.add_argument("--dry-run", action="store_true")\n'" args = ap.parse_args()\n\n"" if not args.model.exists():\n"' raise FileNotFoundError(f"Base GGUF missing: {args.model}")\n'" if not args.manifest.exists():\n"' raise FileNotFoundError(f"Manifest missing: {args.manifest}")\n'" lora_paths = adapter_paths_13(args.fintan_adapter, args.s12_adapter, adapters_dir=args.adapters_dir)\n"" missing = [str(p) for p in lora_paths if not p.exists()]\n"" if missing:\n"' raise FileNotFoundError(f"Missing LoRA files: {missing}")\n\n'" router = UnifiedFintanWSPRouter(\n"" fintan_scale=args.fintan_scale,\n"" s12_scale=args.s12_scale,\n"" manifest_path=args.manifest,\n"" adapters_dir=args.adapters_dir,\n"" )\n"" cmd = build_llama_cmd(\n"" args.llama_server, args.model, lora_paths, llama_port=args.llama_port, host=args.host, ctx=args.ctx\n"" )")assert old_ap in src, "Failed to locate main argparse block in run_fintan_wsp.py"src = src.replace(old_ap, new_ap, 1)return srcdef build_readme(3 unmodified linessynth: Dict[str, Any],cal: Dict[str, Any],res: Dict[str, Any],sl_res: Dict[str, Any],) -> str:"""Build Hugging Face Model Card strictly from verified JSON metrics."""ra_base = base_audit["router_audit"]14 unmodified linessd_wsp = res["suite_d_tbench20"]by_suite = sc_wsp["by_suite"]v2_64 = sl_res["option1_v2_r64"]v2_128 = sl_res["option1_v2_r128"]m2 = sl_res["option2_multi_night"]p_r512 = sl_res["option3_r512_patched"]p_v2 = sl_res["option3_v2_r128_patched"]repo_id = f"{username}/{REPO_NAME}"suite_rows = [157 unmodified lines---## Self-Learning LoRA Upgrades (`Options 1, 2 & 3`)Building on unified WSP inference, [`learn_wsp.py`](https://huggingface.co/{repo_id}/blob/main/scripts/learn_wsp.py) implements an open-source, pure-PyTorch self-learning engine (~`7.6–7.7 GiB` peak CUDA VRAM on RTX 4070 Ti via `Int4Linear` + `Int8Linear`, `H_10` activation precomputation, online Woodbury right-nullspace projection, and mixed `<think>` / `nothink` supervision — **strictly zero `check_questions.json` or Suite B/C/D training leakage**):| Variant / Adapter | Rank / Size (`MiB`) | `mean ||dW||_F` | `A3` Direct (`172`) | `A4` Native `<think>` | `A4` Two-Phase | `B1` Tools (`12`) | Forced-ON `B3_gen` / `B3_abs` / `Holdout-30` || --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: || Upstream `fintan_2026_11_23_r512.gguf` | `512` (`128.0`) | `79.16` | `{sa3['passed']}/172` (89.5%) | `0/172` | `{sa4['clean_pass']}/172` | `11/12` | `7/10` / `0/10` / `1/30` || **Option 1: `fintan_2026_11_23_wsp_v2_r64.gguf`** | `64` (`16.0`) | `{v2_64['norms']['mean_frob_norm']}` | `{v2_64['suite_a3']['passed']}/172` ({v2_64['suite_a3']['pct']}%) | **`{v2_64['suite_a4_single_pass']['passed']}/172`** ({v2_64['suite_a4_single_pass']['pct']}%) | `{v2_64['suite_a4_two_phase']['passed']}/172` | `11/12` | **`{v2_64['forced_on_collateral']['gen_ok']}/10` / `{v2_64['forced_on_collateral']['abs_ok']}/10` / `{v2_64['forced_on_collateral']['holdout_ok']}/30`** || **Option 1: `fintan_2026_11_23_wsp_v2_r128.gguf`** | `128` (`32.0`) | `{v2_128['norms']['mean_frob_norm']}` | **`{v2_128['suite_a3']['passed']}/172`** ({v2_128['suite_a3']['pct']}%) | **`{v2_128['suite_a4_single_pass']['passed']}/172`** (`0` S12!) | `{v2_128['suite_a4_two_phase']['passed']}/172` | **`{v2_128['suite_b1']['think']['full_pass']}/12`** | **`{v2_128['forced_on_collateral']['gen_ok']}/10` / `{v2_128['forced_on_collateral']['abs_ok']}/10` / `{v2_128['forced_on_collateral']['holdout_ok']}/30`** || **Option 2: `fintan_wsp_v2_merged_n1n2.gguf`** | `160` (`40.0`) | `{m2['merged_adapter_norms']['mean_frob_norm']}` | **`{m2['merged_on_night1_direct']['passed']}/172`** N1 + **`{m2['merged_on_night2']['passed']}/24`** N2 | **`{m2['merged_on_night1_think_single']['passed']}/172`** (`0` S12) | — | — | `{m2['merged_forced_on_b3']['gen_ok']}/10` / `{m2['merged_forced_on_b3']['abs_ok']}/10` / — || **Option 3: `fintan_v2_r128_patched.gguf`** | `160` (`40.0`) | `{p_v2['norms']['mean_frob_norm']}` | `{p_v2['suite_a3']['passed']}/172` ({p_v2['suite_a3']['pct']}%) | — | `{p_v2['suite_a4_two_phase']['passed']}/172` | **`{p_v2['suite_b1']['think']['full_pass']}/12`** | `{p_v2['forced_on_b3']['gen_ok']}/10` / `{p_v2['forced_on_b3']['abs_ok']}/10` / — || **Option 3 (Default): `fintan_r512_patched.gguf`** | `544` (`136.0`) | `{p_r512['norms']['mean_frob_norm']}` | **`{p_r512['suite_a3']['passed']}/172` ({p_r512['suite_a3']['pct']}%)** | — | **`{p_r512['suite_a4_two_phase']['passed']}/172` ({p_r512['suite_a4_two_phase']['pct']}%)** | **`{p_r512['suite_b1']['think']['full_pass']}/12`** | `{p_r512['forced_on_b3']['gen_ok']}/10` / `{p_r512['forced_on_b3']['abs_ok']}/10` / — |- **Option 1 (`Fintan-WSP-v2`):** Natural entity-disambiguated `study_qa` + `label_smoothing=0.03` + Woodbury nullspace projection yields `4x–8x` smaller adapters (`16–32 MiB`), **`140/172` single-pass native `<think>`** without `S12`, **`12/12` Knowledge+Tools (`B1`)**, and **`25/30` Forced-ON Holdout-30** (`v2_r64`, vs upstream `1/30`).- **Option 2 (Lossless Orthogonal Multi-Night Merge & Live `/fintan` API):** Training Night-2 (`fintan_night2_wsp_r32.gguf`) with `--base-adapter v2_r128 --protect-keys v2_r128_keys.pt --replay-qa` (`1` study Q/fact) + rank-preserving SVD merge (`r1+r2=160`) achieves **`98.6%` Night-1 retention (`138/172`)** plus **`70.8%` Night-2 unseen (`17/24` vs Base `0/24`)**. `run_fintan_wsp.py` also exposes live `POST /fintan/teach` (enforcing `teach_policy.py`), `POST /fintan/learn`, and `GET /fintan/status`.- **Option 3 (Targeted Hard-Fact Patch):** Self-diagnosing misses on `facts.json`-derived `study_qa` ONLY (`39` hard facts on `r512`) and applying a `r=32` nullspace+replay patch lifts routed `r512` to **`162/172 (94.2%)`** on both `A3` and `A4` (`+8` tasks, surpassing upstream BF16 `91.3%`) and fixes `B1` to **`12/12` (`tool_ok=12/12`)** in both `think` and `nothink`.---## Quick Start (Standalone Local Server)Download the repository (`gguf/Qwen3.5-9B-Q4_K_M.gguf`, `adapters/`, `fintan_data/`, runtime scripts) and launch the OpenAI-compatible server with [`llama.cpp`](https://github.com/ggml-org/llama.cpp) (`llama-server` on `PATH` or passed via `--llama-server`):5 unmodified lines# Verify all 13 LoRA slots and routing without touching GPU:python run_fintan_wsp.py --dry-run# Launch OpenAI-compatible server (defaults to adapters/fintan_r512_patched.gguf, 162/172 = 94.2%):python run_fintan_wsp.py --llama-server llama-server# Optional alternatives:# python run_fintan_wsp.py --fintan-adapter adapters/fintan_2026_11_23_wsp_v2_r128.gguf # native <think>, 32 MiB# python run_fintan_wsp.py --fintan-adapter adapters/fintan_wsp_v2_merged_n1n2.gguf # Night-1 + Night-2 merged```When running locally, stage and consolidate new knowledge safely via:- `POST http://127.0.0.1:8900/fintan/teach` (policy-checked with `fintan_data/door/teach_policy.py`)- `POST http://127.0.0.1:8900/fintan/learn` (runs `learn_wsp.py` protected by `fintan_2026_11_23_wsp_v2_r128_keys.pt`)- `GET http://127.0.0.1:8900/fintan/status`---## Repository Structure- `gguf/Qwen3.5-9B-Q4_K_M.gguf` — Quantized base GGUF (`5.29 GiB`).- `adapters/` — All GGUF LoRA adapters & receptor keys:- `wsp_s1_think.gguf` .. `wsp_s11_term_code.gguf` (`Qwen3.5-9B` WSP agentic + Terminal-Bench subspaces)- `fintan_r512_patched.gguf` (Default Option 3 patched champion, `r=544`), `fintan_r512_patch_r32.gguf`- `fintan_2026_11_23_wsp_v2_r128.gguf`, `fintan_2026_11_23_wsp_v2_r64.gguf`, `fintan_2026_11_23_wsp_v2_r128_keys.pt`- `fintan_wsp_v2_merged_n1n2.gguf`, `fintan_night2_wsp_r32.gguf`, `fintan_v2_r128_patched.gguf`, `fintan_v2_r128_patch_r32.gguf`- `fintan_2026_11_23_r512.gguf`, `fintan_2026_11_23_null_g5.gguf`, `fintan_2026_11_23_null_g20.gguf`, `fintan_2026_11_23_null_g1.gguf`- `wsp_s12_fintan_think_bridge.gguf`- `run_fintan_wsp.py`, `fintan_wsp_router.py`, `dynamic_router_9s.py` — Portable OpenAI server (+ `/fintan/teach`, `/fintan/learn`, `/fintan/status`) & 13-LoRA router.- `fintan_data/` — Upstream `manifest.json`, `background.json`, `updates/2026-11-23/` facts & evaluation questions, synthetic disjoint `night2_synthetic_facts.json` & `night2_eval_questions.json`, and `door/{{night_router*.py,teach_policy.py}}`.- `results/` — Complete verified outputs (`spectral_analysis.json`, `baseline_audit.json`, `wsp_synthesis_report.json`, `wsp_cal_report.json`, `fintan_wsp_results.json`, `self_learning_wsp_results.json`, `fintan_9b_wsp_report.md`).- `scripts/` — Full pipeline & self-learning scripts (`learn_wsp.py`, `benchmark_self_learning.py`, `stage_and_analyze_fintan.py`, `audit_fintan_baseline.py`, `build_fintan_wsp.py`, `validate_fintan_wsp_cal.py`, `evaluate_fintan_wsp.py`, `smoke_test_fintan.py`, `upload_fintan_to_hf.py`)."""16 unmodified linessynth: Dict[str, Any],cal: Dict[str, Any],res: Dict[str, Any],sl_res: Dict[str, Any],) -> List[CommitOperationAdd]:stage_dir.mkdir(parents=True, exist_ok=True)staged_readme = stage_dir / "README.md"staged_readme.write_text(build_readme(username, spec, base_audit, synth, cal, res, sl_res), encoding="utf-8")staged_req = stage_dir / "requirements.txt"staged_req.write_text(REQUIREMENTS_TXT, encoding="utf-8")30 unmodified lines(UPSTREAM / "door" / "night_router2.py", "fintan_data/door/night_router2.py"),(UPSTREAM / "door" / "night_router3.py", "fintan_data/door/night_router3.py"),(UPSTREAM / "door" / "night_router4.py", "fintan_data/door/night_router4.py"),(UPSTREAM / "door" / "teach_policy.py", "fintan_data/door/teach_policy.py"),(ROOT / "night2_synthetic_facts.json", "fintan_data/night2_synthetic_facts.json"),(ROOT / "night2_eval_questions.json", "fintan_data/night2_eval_questions.json"),]file_pairs.extend(fintan_data_files)3 unmodified lines(ROOT / "wsp_synthesis_report.json", "results/wsp_synthesis_report.json"),(ROOT / "wsp_cal_report.json", "results/wsp_cal_report.json"),(ROOT / "fintan_wsp_results.json", "results/fintan_wsp_results.json"),(ROOT / "self_learning_wsp_results.json", "results/self_learning_wsp_results.json"),(REPORT_LOCAL, "results/fintan_9b_wsp_report.md"),]file_pairs.extend(result_files)script_files = ["learn_wsp.py","benchmark_self_learning.py","stage_and_analyze_fintan.py","audit_fintan_baseline.py","build_fintan_wsp.py",24 unmodified linessynth = json.loads((ROOT / "wsp_synthesis_report.json").read_text(encoding="utf-8"))cal = json.loads((ROOT / "wsp_cal_report.json").read_text(encoding="utf-8"))res = json.loads((ROOT / "fintan_wsp_results.json").read_text(encoding="utf-8"))sl_res = json.loads((ROOT / "self_learning_wsp_results.json").read_text(encoding="utf-8"))assert res["suite_a3"]["passed"] == 154assert res["suite_a4"]["clean_pass"] == 154assert res["suite_b"]["b1"]["fintan_wsp_think"]["full_pass"] == 11assert res["suite_b"]["b1"]["fintan_wsp_nothink"]["full_pass"] == 11assert cal["router_audit"]["check_172_routed"] == 172assert sl_res["option1_v2_r128"]["suite_a3"]["passed"] == 140assert sl_res["option2_multi_night"]["merged_on_night1_direct"]["passed"] == 138assert sl_res["option2_multi_night"]["merged_on_night2"]["passed"] == 17assert sl_res["option3_r512_patched"]["suite_a3"]["passed"] == 162assert sl_res["option3_r512_patched"]["suite_b1"]["think"]["full_pass"] == 12for lp, _, _ in LARGE_GGUF_UPLOADS:if not lp.exists():10 unmodified linescreate_repo(repo_id=repo_id, token=token, repo_type="model", private=False, exist_ok=True)stage_dir = ROOT / "_hf_staging"ops = collect_operations(username, stage_dir, spec, base_audit, synth, cal, res, sl_res)ops_mib = sum(Path(op.path_or_fileobj).stat().st_size for op in ops) / (1024 * 1024)large_gib = sum(p.stat().st_size for p, _, _ in LARGE_GGUF_UPLOADS) / (1024 ** 3)
README.md+37-6
fintan_data/door/teach_policy.pyAdded+110
fintan_data/night2_eval_questions.jsonAdded+26
fintan_data/night2_synthetic_facts.jsonAdded+26
results/fintan_9b_wsp_report.md+38-6
results/self_learning_wsp_results.jsonAdded+763
run_fintan_wsp.py+149-16
scripts/benchmark_self_learning.pyAdded+359
scripts/learn_wsp.pyAdded+1173
scripts/upload_fintan_to_hf.py+230-239