ronitraj commited on
Commit
d6715d9
·
verified ·
1 Parent(s): 195f87e

deploy via scripts/deploy_to_space.py

Browse files
Files changed (1) hide show
  1. README.md +380 -75
README.md CHANGED
@@ -1,13 +1,11 @@
1
  ---
2
- title: QuantumScribe
3
  emoji: 🩺
4
  colorFrom: indigo
5
  colorTo: pink
6
  sdk: docker
7
  app_port: 7860
8
- pinned: false
9
- license: mit
10
- short_description: OpenEnv RL env that teaches an LLM to decode quantum errors.
11
  tags:
12
  - openenv
13
  - reinforcement-learning
@@ -17,108 +15,415 @@ tags:
17
  - grpo
18
  - trl
19
  - llm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  ---
21
 
22
- # QuantumScribe Qubit-Medic OpenEnv
 
 
23
 
24
- > An [OpenEnv](https://meta-pytorch.github.io/OpenEnv/) reinforcement-learning
25
- > environment that teaches a Large Language Model to decode errors on the
26
- > rotated surface code, using **Stim** for physics-accurate noise sampling
27
- > and **PyMatching** as the classical baseline to beat.
28
 
29
- This Space hosts the **environment server only**. Training (SFT warm-up
30
- + GRPO RL) runs on a separate Colab T4; the trained LoRA adapter is
31
- loaded client-side, not on this Space.
 
 
 
 
 
32
 
33
- ## Endpoints
34
 
35
- This is the canonical **OpenEnv contract** registered by
36
- `openenv.core.create_fastapi_app`, plus two extras of our own:
37
 
38
- | Method | Path | Purpose |
39
- |---|---|---|
40
- | `POST` | `/reset` | Sample a fresh syndrome + observation. Body `{"seed": int?, "episode_id": str?}`. Optional `?forced_level=L1_warmup\|L2_target\|L3_stretch`. |
41
- | `POST` | `/step` | Score the LLM's prediction with five independent rewards. Body `{"action": {"raw_response": "...", "episode_id": int}, "timeout_s": float?, "request_id": str?}`. |
42
- | `GET` | `/state` | Curriculum + episode counters (no physics-truth fields). |
43
- | `GET` | `/health` | OpenEnv liveness response. |
44
- | `GET` | `/healthz` | Lightweight Day-0 probe — Stim/PyMatching/openenv versions. |
45
- | `GET` | `/schema` | JSON Schema for `QubitMedicAction` / `QubitMedicObservation`. |
46
- | `GET` | `/metadata` | Environment metadata (name, description, version). |
47
- | `POST` | `/mcp` | Model Context Protocol endpoint. |
48
- | `POST` | `/decode` | PyMatching baseline demo: pass a hand-crafted syndrome, get the matching-decoder result. |
49
- | `GET` | `/docs` | Swagger UI for everything above. |
50
 
51
- ## Try it
52
 
53
- Curl from anywhere:
54
 
55
  ```bash
56
- curl https://ronitraj-quantumscribe.hf.space/healthz
57
  ```
58
 
59
- Use it from Python with the OpenEnv client:
60
 
61
- ```python
62
- from openenv.core import GenericEnvClient
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- with GenericEnvClient(base_url="https://ronitraj-quantumscribe.hf.space").sync() as env:
65
- obs = env.reset(seed=42)
66
- print(obs.observation["prompt"][:200])
67
- result = env.step({"raw_response": "<answer>X: 0,3 | Z:</answer>", "episode_id": 1})
68
- print("reward:", result.reward, "rewards breakdown:", result.observation["info"]["rewards"])
 
69
  ```
70
 
71
- Or hit the env directly with `httpx`:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
  ```python
74
- import httpx
75
- url = "https://ronitraj-quantumscribe.hf.space"
76
- obs = httpx.post(f"{url}/reset", json={"seed": 42},
77
- params={"forced_level": "L2_target"}).json()["observation"]
78
- print(obs["prompt"][:200])
79
- res = httpx.post(f"{url}/step", json={
80
- "action": {"raw_response": "<answer>X: | Z:</answer>",
81
- "episode_id": obs["episode_id"]}
82
- }).json()
83
- print("reward =", res["reward"], "rewards =", res["observation"]["info"]["rewards"])
84
  ```
85
 
86
- ## What the rewards mean
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
- Each `step` returns five *independent, verifiable* reward components:
89
 
90
- | Reward | Weight | What it measures |
91
- |---|---:|---|
92
- | `logical_correction` | 0.40 | 1 if the predicted Pauli frame preserves the logical-Z observable. |
93
- | `syndrome_consistency` | 0.20 | Hamming similarity over final-round detector parities. |
94
- | `hamming_overlap` | 0.20 | Mean Jaccard similarity vs. the PyMatching reference Pauli frame. |
95
- | `format_compliance` | 0.10 | 1 / 0.5 / 0 for full / partial / unparseable LLM output. |
96
- | `pymatching_beat` | 0.10 | 1 iff PyMatching is wrong on this syndrome **and** the model is right. |
97
 
98
- All five are computed from the same `(prompt, completion, syndrome)` tuple on every step (no redundant sampling — see the architecture notes in the GitHub README).
99
 
100
- ## Stack
 
 
 
 
 
 
 
 
 
 
 
101
 
102
- * [openenv-core](https://pypi.org/project/openenv-core/) `>=0.2.1` — environment contract, FastAPI scaffolding, MCP, WebSocket sessions.
103
- * [Stim](https://github.com/quantumlib/Stim) — Clifford circuit simulator and detector-error-model generator.
104
- * [PyMatching](https://github.com/oscarhiggott/PyMatching) `>=2.2` — minimum-weight matching baseline (and ground-truth for the `pymatching_beat` reward).
105
- * FastAPI + Uvicorn — HTTP transport.
106
 
107
- ## Curriculum
108
 
109
- | Level | Distance | Rounds | Physical error rate | Promotion threshold |
110
- |---|---:|---:|---:|---:|
111
- | `L1_warmup` | 3 | 1 | 1e-4 | logical_correction 0.80 |
112
- | `L2_target` | 3 | 3 | 1e-3 | logical_correction ≥ 0.70 |
113
- | `L3_stretch` | 5 | 5 | 1e-3 | logical_correction ≥ 0.30 |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
- The server's curriculum scheduler tracks a moving average of `logical_correction` per level and promotes the agent when it crosses the threshold.
116
 
117
- ## See also
118
 
119
- * OpenEnv documentation <https://meta-pytorch.github.io/OpenEnv/>
120
- * TRL `environment_factory=` integration — <https://huggingface.co/docs/trl/main/openenv>
121
 
122
  ---
123
 
124
- *Built for the META RL hackathon. Source code, training notebook, and reproduction instructions: see the [GitHub repository](https://github.com/ronitraj/qubit-medic) (link to be updated).*
 
 
 
1
  ---
2
+ title: Qubit-Medic
3
  emoji: 🩺
4
  colorFrom: indigo
5
  colorTo: pink
6
  sdk: docker
7
  app_port: 7860
8
+ pinned: true
 
 
9
  tags:
10
  - openenv
11
  - reinforcement-learning
 
15
  - grpo
16
  - trl
17
  - llm
18
+ license: mit
19
+ short_description: OpenEnv RL env that teaches an LLM to decode quantum errors.
20
+ ---
21
+
22
+ # Qubit-Medic
23
+
24
+ > An LLM trained to decode quantum surface-code syndromes. We follow the
25
+ > AlphaQubit-style recipe (*Nature* 2024): a language model as decoder with
26
+ > verifiable rewards—implemented on **Stim + PyMatching**, an **OpenEnv**-style
27
+ > HTTP contract, **SFT warm-up + GRPO** (TRL/Unsloth), and **multi-component
28
+ > rewards** that are hard to game.
29
+
30
+ ![Qubit-Medic decoding a syndrome on the rotated surface code](figures/grid_hero.png)
31
+
32
+ **Hugging Face**
33
+
34
+ - **Space:** [https://huggingface.co/spaces/ronitraj/QuantumScribe](https://huggingface.co/spaces/ronitraj/QuantumScribe) — live OpenEnv server + API; liveness: [https://ronitraj-quantumscribe.hf.space/healthz](https://ronitraj-quantumscribe.hf.space/healthz)
35
+ - **Model (LoRA):** [https://huggingface.co/ronitraj/quantumscribe](https://huggingface.co/ronitraj/quantumscribe) — PEFT adapter and tokenizer
36
+
37
+ **Weights & Biases (this experiment)**
38
+
39
+ - **Project:** [https://wandb.ai/ronitraj/QuantumScribe-GRPO](https://wandb.ai/ronitraj/QuantumScribe-GRPO)
40
+ - **SFT run** (`sft-20260426-045056`): [https://wandb.ai/ronitraj/QuantumScribe-GRPO/runs/yli513jl](https://wandb.ai/ronitraj/QuantumScribe-GRPO/runs/yli513jl)
41
+ - **GRPO run** (`grpo-20260426-045324`): [https://wandb.ai/ronitraj/QuantumScribe-GRPO/runs/4p7eurnc](https://wandb.ai/ronitraj/QuantumScribe-GRPO/runs/4p7eurnc) — run id `4p7eurnc` (e.g. best step ~1300, in-loop eval, artifacts)
42
+
43
+ ---
44
+
45
+ ## Quick links
46
+
47
+ | Resource | URL |
48
+ |----------|-----|
49
+ | **Hugging Face Space (live demo + API)** | [ronitraj/QuantumScribe](https://huggingface.co/spaces/ronitraj/QuantumScribe) — health: [`/healthz`](https://ronitraj-quantumscribe.hf.space/healthz) |
50
+ | **Trained LoRA on the Hub** | [ronitraj/quantumscribe](https://huggingface.co/ronitraj/quantumscribe) (PEFT adapter + tokenizer) |
51
+ | **W&B project** | [ronitraj/QuantumScribe-GRPO](https://wandb.ai/ronitraj/QuantumScribe-GRPO) |
52
+ | **W&B — SFT run** | [runs/yli513jl](https://wandb.ai/ronitraj/QuantumScribe-GRPO/runs/yli513jl) |
53
+ | **W&B — GRPO run** | [runs/4p7eurnc](https://wandb.ai/ronitraj/QuantumScribe-GRPO/runs/4p7eurnc) |
54
+ | **Colab training** | [`notebooks/colab_train.ipynb`](notebooks/colab_train.ipynb) |
55
+ | **Local Gradio** | `python app_gradio.py` |
56
+ | **OpenEnv manifest** | [`openenv.yaml`](openenv.yaml) |
57
+
58
  ---
59
 
60
+ ## What this repo does (elevator pitch)
61
+
62
+ Quantum computers need a **decoder**: classical software that maps **syndromes** (detector results) to **corrections**. DeepMind’s [AlphaQubit](https://www.nature.com/articles/s41586-024-08148-8) showed a transformer can beat a strong **PyMatching** baseline. We reimplement the *idea* with a commodity stack:
63
 
64
+ - **3B** instruction-tuned **Qwen2.5** in **4-bit** (Unsloth) + **LoRA**
65
+ - **SFT** then **GRPO** (reward from a real Stim environment, not offline labels)
66
+ - **OpenEnv**-compatible server: `/reset` / `/step` / state & schema
67
+ - **Five** logged reward components (aggregate is weighted)
68
 
69
+ | Dimension | This project (typical) | AlphaQubit (reference) |
70
+ |-----------|------------------------|------------------------|
71
+ | Decoder | 3B LM + LoRA (off-the-shelf) | Custom architecture, lab-scale data mix |
72
+ | Training signal | SFT + GRPO on env reward | Proprietary + SI1000 / Sycamore |
73
+ | Baseline | PyMatching (sparse blossom) | Same class of MWM decoder |
74
+ | Open source | This repo + Hub weights | Research partial |
75
+
76
+ ---
77
 
78
+ ## Latest measured eval (JSON)
79
 
80
+ These numbers come from a held-out run written to `data/eval_grpo.json` (1000 episodes, L2 target, adapter path recorded in the file). They are the **source of truth** for submission claims; **do not** substitute synthetic plots for these metrics.
 
81
 
82
+ | Metric | Value |
83
+ |--------|------:|
84
+ | `logical_correction_rate` | 0.964 |
85
+ | `pymatching_beat_rate` | 0.0 |
86
+ | `format_compliance_rate` | 1.0 |
87
+ | `mean_hamming_overlap` | 0.8405 |
88
+ | `mean_total_reward` | ~0.821 |
89
+ | `exact_match_pymatching` | 0.734 |
 
 
 
 
90
 
91
+ `pymatching_beat` is 1 only when **PyMatching is wrong on the observable** and the **LLM is right**; on this eval it is **0.0**—i.e. no "beats" on that slice—so do not claim outperforming PM here without a separate run where that rate is non-zero. High **logical correction** and overlap with the PM frame remain meaningful; interpret with [reward definitions](qubit_medic/server/rewards.py).
92
 
93
+ Reproduce:
94
 
95
  ```bash
96
+ python -m scripts.eval --adapter /path/to/grpo/adapter --episodes 1000 --out data/eval_grpo.json
97
  ```
98
 
99
+ (Adjust `--adapter` to your checkpoint, e.g. a downloaded [ronitraj/quantumscribe](https://huggingface.co/ronitraj/quantumscribe) adapter.)
100
 
101
+ ---
102
+
103
+ ## Data in `data/`
104
+
105
+ | File | Purpose |
106
+ |------|--------|
107
+ | [data/eval_grpo.json](data/eval_grpo.json) | **Primary eval** — single JSON summary (episodes, `logical_correction_rate`, `pymatching_beat_rate`, overlaps, `level`, etc.) from `scripts.eval`. |
108
+ | [data/grpo_validation.jsonl](data/grpo_validation.jsonl) | GRPO **validation** prompts / episodes (one JSON object per line; curriculum, syndrome, seeds). |
109
+ | [data/sft_dataset_analysis.json](data/sft_dataset_analysis.json) | **SFT dataset report** — stats (completion lengths, level mix, train/val overlap, `eval_windows`). |
110
+ | [data/sft_validation.jsonl](data/sft_validation.jsonl) | SFT **held-out** set used during training. |
111
+ | [data/sft_dataset_sample.jsonl](data/sft_dataset_sample.jsonl) | Small **sample** of SFT training rows (prompt + metadata). |
112
+
113
+ Generated on demand (not always committed) after `make baselines` / SFT / Willow runs, per [.gitignore](.gitignore):
114
+
115
+ - `data/baseline_results.json` — random / zeros / PyMatching baselines
116
+ - `data/sft_dataset.jsonl` — full SFT train (from `make sft-data` or `generate_sft_data`)
117
+ - `data/willow_validation.json`, `data/willow_d3.dem` — cross-distribution checks
118
+
119
+ ---
120
+
121
+ ## Figures in `figures/`
122
+
123
+ Provenance and regeneration: [figures/FIGURES.md](figures/FIGURES.md). The three **trajectory** plots below are **illustrative** (from `make plots` / baseline-anchored synthetic mode), not a raw W&B export—replace with `scripts/plot_results.py` and real logs when you have them.
124
+
125
+ **Training trajectories (illustrative)**
126
+
127
+ | Mean episode reward | Logical correction rate | PyMatching beat rate |
128
+ |:-:|:-:|:-:|
129
+ | ![Total reward](figures/total_reward.png) | ![Logical correction](figures/logical_correction.png) | ![PyMatching beat](figures/pymatching_beat_rate.png) |
130
+
131
+ **Grid animation** (Stim + layout demo)
132
+
133
+ ![Surface-code grid animation](figures/grid_animation.gif)
134
+
135
+ **Reward & metrics from data (reproducible)** — not time-series; single-run summaries from [data/eval_grpo.json](data/eval_grpo.json) and [data/sft_dataset_analysis.json](data/sft_dataset_analysis.json). Regenerate: `python -m scripts.plot_data_figures`
136
+
137
+ | Eval metrics (held-out) | SFT curriculum mix (train split) |
138
+ |:-:|:-:|
139
+ | ![Eval metrics bars](figures/eval_metrics_bars.png) | ![SFT curriculum mix](figures/sft_curriculum_mix.png) |
140
+
141
+ *Note:* For **per-reward time series** and KL during GRPO, use the main **GRPO** run: [runs/4p7eurnc](https://wandb.ai/ronitraj/QuantumScribe-GRPO/runs/4p7eurnc) — e.g. `rl/reward/total_mean`, `rl/reward/logical_correction_mean`, `alarms/kl_alarm_value`.
142
+
143
+ ---
144
+
145
+ ## The problem (in one story)
146
+
147
+ Qubits are noisy. You do not observe errors directly; you get **syndromes** from stabilizer measurements. A **decoder** turns syndromes into a **Pauli correction**. **PyMatching** is a strong classical baseline. We train an LLM to output a parseable correction; the environment checks it with Stim and five reward functions.
148
+
149
+ ---
150
+
151
+ ## The environment
152
+
153
+ A **FastAPI** app exposes an **OpenEnv**-style flow (see [qubit_medic/server/app.py](qubit_medic/server/app.py) and [qubit_medic/server/openenv_adapter.py](qubit_medic/server/openenv_adapter.py)):
154
+
155
+ - `reset(seed)` — sample a syndrome (curriculum), return a prompt.
156
+ - `step(text)` — parse, score rewards, return reward + per-component `info`.
157
+
158
+ **Episodes** are **single-step**: one completion per episode. The trainer and W&B see each reward component separately.
159
+
160
+ ```text
161
+ +----------+ reset / step +---------------------------+
162
+ | TRL/ | ------------> | Qubit-Medic (Stim+PM) |
163
+ | Unsloth | observation | parse, 5 rewards, return |
164
+ +----------+ <------------ +---------------------------+
165
+ ```
166
+
167
+ ---
168
+
169
+ ## Methodology checklist
170
+
171
+ | Concern | Status | Pointer |
172
+ |--------|--------|--------|
173
+ | Realistic noise (SI1000) | Used | Gidney & Fowler [arXiv:2108.10457](https://arxiv.org/abs/2108.10457) |
174
+ | Real code family | Stim `surface_code:rotated_memory_z` | [Stim](https://github.com/quantumlib/Stim) |
175
+ | Strong classical baseline | PyMatching v2 | [arXiv:2303.15933](https://arxiv.org/abs/2303.15933) |
176
+ | Policy optimisation | GRPO | [arXiv:2402.03300](https://arxiv.org/abs/2402.03300) |
177
+ | OOD / Willow (optional) | `scripts/willow_validation.py` + `data/willow_d3.dem` | [Zenodo](https://zenodo.org/record/13359217) |
178
+
179
+ ---
180
+
181
+ ## Baselines (no LLM)
182
+
183
+ `make baselines` writes `data/baseline_results.json` (random, all-zeros, PyMatching). `make plots` rebuilds the headline figures from that JSON (see [figures/FIGURES.md](figures/FIGURES.md)).
184
+
185
+ ```bash
186
+ make baselines
187
+ make plots
188
+ ```
189
+
190
+ ---
191
+
192
+ ## Reward design (config-driven)
193
+
194
+ Weights are **`qubit_medic/config.py` → `REWARD_WEIGHTS`** (sum **1.0**):
195
 
196
+ ```text
197
+ total = 0.35 * logical_correction
198
+ + 0.25 * hamming_overlap
199
+ + 0.20 * syndrome_consistency
200
+ + 0.10 * format_compliance
201
+ + 0.10 * pymatching_beat
202
  ```
203
 
204
+ | Component | Role |
205
+ |-----------|------|
206
+ | **logical_correction** | 1 if the implied correction matches logical observable (Stim). |
207
+ | **hamming_overlap** | Dense credit vs the PyMatching reference frame. |
208
+ | **syndrome_consistency** | Implied final detectors vs observed syndrome. |
209
+ | **format_compliance** | Parse success / partial / fail. |
210
+ | **pymatching_beat** | 1 only if **PM wrong** and **LLM right** (rare; headline for beating PM). |
211
+
212
+ Details: [qubit_medic/server/rewards.py](qubit_medic/server/rewards.py). GRPO uses a **shared batch cache** so all five components score the *same* `(prompt, completion)` (see W&B section in previous docs—[`qubit_medic/wandb_utils.py`](qubit_medic/wandb_utils.py) and trainer).
213
+
214
+ ---
215
+
216
+ ## Weights & Biases
217
+
218
+ Defaults: **`WANDB_ENTITY=ronitraj`**, **`WANDB_PROJECT=QuantumScribe-GRPO`**. Trainers use [qubit_medic/wandb_utils.py](qubit_medic/wandb_utils.py). Disable: `WANDB_DISABLED=1` or `QUBIT_MEDIC_WANDB=0`.
219
+
220
+ **Reference runs (2026-04-26, Colab / server)**
221
+
222
+ | Stage | Run name | Direct link |
223
+ |------|------------|-------------|
224
+ | Project | — | [wandb.ai/ronitraj/QuantumScribe-GRPO](https://wandb.ai/ronitraj/QuantumScribe-GRPO) |
225
+ | SFT | `sft-20260426-045056` | [runs/yli513jl](https://wandb.ai/ronitraj/QuantumScribe-GRPO/runs/yli513jl) |
226
+ | GRPO | `grpo-20260426-045324` | [runs/4p7eurnc](https://wandb.ai/ronitraj/QuantumScribe-GRPO/runs/4p7eurnc) |
227
+
228
+ The GRPO run includes training curves, in-loop `eval/*`, `alarms/kl_alarm_value`, best checkpoint metadata (`best/step` ≈ 1300), and logged artifacts.
229
+
230
+ ```bash
231
+ pip install -r requirements-train.txt
232
+ wandb login
233
+ GROUP=my-exp make train-sft
234
+ GROUP=my-exp make train-grpo
235
+ GROUP=my-exp make eval
236
+ ```
237
+
238
+ ---
239
+
240
+ ## Reproducibility (`qubit_medic/config.py`)
241
+
242
+ | Item | Value |
243
+ |------|--------|
244
+ | Stim / PyMatching | Pinned in `requirements*.txt` |
245
+ | SFT default base | `Qwen/Qwen2.5-3B-Instruct` via Unsloth |
246
+ | GRPO default base | `unsloth/qwen2.5-3b-instruct-unsloth-bnb-4bit` |
247
+ | LoRA | `r=16`, `alpha=32`, `dropout=0.1`, `q/k/v/o` |
248
+ | GRPO | **1500** steps, short completions (`max_completion` 50), KL coeff **0.02**, `temperature=1.2` rollouts, etc. |
249
+ | Seeds | `42, 1337, 2024` |
250
+
251
+ **Import from `qubit_medic.config`**—do not duplicate magic numbers in scripts.
252
+
253
+ ---
254
+
255
+ ## Train and eval (local)
256
+
257
+ ```bash
258
+ python3 -m venv .venv && . .venv/bin/activate
259
+ pip install -r requirements.txt
260
+ make validate
261
+
262
+ make sft-data
263
+ make baselines
264
+ make tests
265
+
266
+ python -m scripts.train_sft --output checkpoints/sft_warmup
267
+ python -m scripts.train_grpo \
268
+ --sft-checkpoint checkpoints/sft_warmup/checkpoint-50 \
269
+ --output checkpoints/grpo
270
+
271
+ python -m scripts.eval --adapter checkpoints/grpo --episodes 1000 --out data/eval_grpo.json
272
+ ```
273
+
274
+ End-to-end: [notebooks/colab_train.ipynb](notebooks/colab_train.ipynb). Makefile shortcuts: `make train-sft`, `make train-grpo`, `make eval` (see [Makefile](Makefile)).
275
+
276
+ ### Local dev: run everything (no Docker)
277
+
278
+ **1. Base environment (CPU OK)** — OpenEnv / Stim / tests:
279
+
280
+ ```bash
281
+ cd /path/to/errorCorrection
282
+ python3 -m venv .venv
283
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
284
+ pip install -U pip
285
+ pip install -r requirements.txt
286
+ make validate
287
+ make tests
288
+ ```
289
+
290
+ **2. OpenEnv HTTP server (no LLM — physics + reward only)** — good for API checks and `curl` / a browser:
291
+
292
+ ```bash
293
+ # default: 0.0.0.0:7860 (or set QUBIT_MEDIC_PORT)
294
+ python -m qubit_medic.server.app
295
+ # dev reload:
296
+ uvicorn qubit_medic.server.app:app --reload --host 0.0.0.0 --port 7860
297
+ ```
298
+
299
+ - Docs: [http://127.0.0.1:7860/docs](http://127.0.0.1:7860/docs)
300
+ - Health: [http://127.0.0.1:7860/healthz](http://127.0.0.1:7860/healthz)
301
+
302
+ **3. Gradio grid demo (Stim + PyMatching only)** — *does not* load the trained LLM in code today; it visualises the classical decoder.
303
+
304
+ ```bash
305
+ pip install "gradio>=4"
306
+ PORT=7860 python app_gradio.py
307
+ # open http://127.0.0.1:7860 — if the OpenEnv server is already on 7860, use e.g. PORT=7861
308
+ ```
309
+
310
+ **4. Run with the real model (Unsloth + LoRA) — this is the supported path** — needs a **GPU** and training deps. The eval harness loads the adapter and uses [`LocalDecoderClient`](qubit_medic/client/client.py) (in-process env, no separate server).
311
+
312
+ ```bash
313
+ pip install -r requirements-train.txt
314
+ # optional: export HF_TOKEN=... for gated/private Hub repos
315
+ python -m scripts.eval \
316
+ --adapter ronitraj/quantumscribe \
317
+ --episodes 50 \
318
+ --level L2_target \
319
+ --max-new-tokens 160
320
+ ```
321
+
322
+ - Use a **local LoRA folder** the same way: `--adapter /path/to/checkpoints/grpo/final` (the directory that contains `adapter_model.safetensors`).
323
+ - The script calls `FastLanguageModel.from_pretrained(model_name=adapter, …)`; for Hub PEFT repos, Unsloth/transformers should resolve the base from `adapter_config.json`. If loading fails, run `hf download ronitraj/quantumscribe` and point `--adapter` at the local folder.
324
+ - Shorter run first (e.g. `--episodes 5`) to confirm VRAM, then increase.
325
+
326
+ **5. What is *not* wired** — the **Docker** Space image does not install `torch`/Unsloth; the **Gradio** app’s markdown mentions `QUBIT_MEDIC_ADAPTER` but **there is no LLM inference in `app_gradio.py` yet**—use `scripts.eval` for the trained policy.
327
+
328
+ ---
329
+
330
+ ## Publish the adapter to the Hub
331
+
332
+ Released weights: **[ronitraj/quantumscribe](https://huggingface.co/ronitraj/quantumscribe)**. Load as PEFT on the same base used for training:
333
 
334
  ```python
335
+ from peft import PeftModel
336
+ from transformers import AutoModelForCausalLM, AutoTokenizer
337
+
338
+ base = "unsloth/qwen2.5-3b-instruct-unsloth-bnb-4bit"
339
+ model = AutoModelForCausalLM.from_pretrained(base, device_map="auto", trust_remote_code=True)
340
+ model = PeftModel.from_pretrained(model, "ronitraj/quantumscribe")
341
+ tokenizer = AutoTokenizer.from_pretrained("ronitraj/quantumscribe")
 
 
 
342
  ```
343
 
344
+ Re-upload: `hf upload ronitraj/quantumscribe /path/to/final .` with Hub authentication.
345
+
346
+ ---
347
+
348
+ ## Space deployment
349
+
350
+ - **Space:** [ronitraj/QuantumScribe](https://huggingface.co/spaces/ronitraj/QuantumScribe)
351
+ - **Script:** `python -m scripts.deploy_to_space` — see [scripts/deploy_to_space.py](scripts/deploy_to_space.py)
352
+ - For private model pulls, set Space secret `HF_TOKEN`.
353
+
354
+ ---
355
+
356
+ ## Cross-distribution (optional)
357
 
358
+ `python -m scripts.willow_validation` see [scripts/willow_validation.py](scripts/willow_validation.py).
359
 
360
+ ---
 
 
 
 
 
 
361
 
362
+ ## Repository layout
363
 
364
+ ```text
365
+ qubit_medic/
366
+ config.py, models.py, prompts.py, wandb_utils.py
367
+ client/
368
+ server/ (app, environment, rewards, curriculum, physics, openenv_adapter)
369
+ scripts/
370
+ validate_env.py, generate_sft_data.py, train_sft.py, train_grpo.py, eval.py
371
+ baseline_policies.py, plot_results.py, plot_data_figures.py, animate_grid.py, willow_validation.py
372
+ format_test.py, diversity_preflight.py, deploy_to_space.py, sync_kaggle_bundle.py
373
+ tests/ data/ figures/ checkpoints/ notebooks/colab_train.ipynb
374
+ app_gradio.py Dockerfile openenv.yaml Makefile
375
+ ```
376
 
377
+ ---
 
 
 
378
 
379
+ ## Citations
380
 
381
+ ```bibtex
382
+ @article{bausch_alphaqubit_2024,
383
+ title = {Learning high-accuracy error decoding for quantum processors},
384
+ author = {Bausch, Johannes and others},
385
+ journal = {Nature},
386
+ volume = {635},
387
+ pages = {834},
388
+ year = {2024},
389
+ doi = {10.1038/s41586-024-08148-8}
390
+ }
391
+ @article{acharya_willow_2024,
392
+ title = {Quantum error correction below the surface code threshold},
393
+ author = {Acharya, R. and others (Google Quantum AI)},
394
+ journal = {arXiv:2408.13687},
395
+ year = {2024}
396
+ }
397
+ @article{gidney_si1000_2021,
398
+ title = {A fault-tolerant honeycomb memory},
399
+ author = {Gidney, Craig and Fowler, Austin G.},
400
+ journal = {arXiv:2108.10457},
401
+ year = {2021}
402
+ }
403
+ @article{higgott_pymatching_2023,
404
+ title = {Sparse Blossom: correcting a million errors per core second
405
+ with minimum-weight matching},
406
+ author = {Higgott, Oscar and Gidney, Craig},
407
+ journal = {arXiv:2303.15933},
408
+ year = {2023}
409
+ }
410
+ @article{shao_grpo_2024,
411
+ title = {DeepSeekMath: pushing the limits of mathematical reasoning
412
+ in open language models},
413
+ author = {Shao, Zhihong and others},
414
+ journal = {arXiv:2402.03300},
415
+ year = {2024}
416
+ }
417
+ ```
418
 
419
+ ---
420
 
421
+ ## Acknowledgments
422
 
423
+ DeepMind (AlphaQubit), Google Quantum AI (Stim, Willow data), Gidney (SI1000), Higgott (PyMatching), Hugging Face, Unsloth, OpenEnv.
 
424
 
425
  ---
426
 
427
+ ## License
428
+
429
+ MIT — [LICENSE](LICENSE).