Instructions to use emrevrg/AUBIN-12B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use emrevrg/AUBIN-12B with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("google/gemma-4-12B-it") model = PeftModel.from_pretrained(base_model, "emrevrg/AUBIN-12B") - Notebooks
- Google Colab
- Kaggle
AUBIN release card, calibration, code (measured numbers only)
Browse files- README.md +59 -4
- aubin_vs_jev.png +0 -0
- code/aubin/__init__.py +2 -1
- code/aubin/control.py +58 -0
- code/aubin/core.py +42 -5
- code/aubin/mcp_server.py +105 -0
- code/bench_cache.py +2 -0
- code/control_bench.py +142 -0
- code/control_train.py +82 -0
- code/graybench.py +187 -0
- code/kev_llm.py +30 -6
- code/loop_bench.py +6 -2
- test_clean_metrics.json +41 -0
README.md
CHANGED
|
@@ -14,12 +14,15 @@ tags: [decision-model, typed-decisions, calibrated, lora, aubin, norovox, open-w
|
|
| 14 |
## At a glance
|
| 15 |
|
| 16 |
- **Beats Jev on Jev's own published split, all 8 numbers**: accuracy 0.863 vs 0.857 and 0.862 vs 0.845; NLL 0.409 vs 0.701; Brier, ECE lower too.
|
| 17 |
-
- **AUBIN Trio (adds Phi-4), 8/8 vs Jev**:
|
|
|
|
| 18 |
- **22x fewer confidently-wrong answers** (AUBIN-31B, one pass, trained-source split: 0.24% vs Jev 5.22%).
|
| 19 |
- **0 errors on held-out policy rules** it never trained on (Jev: 14 / 176).
|
| 20 |
- **Locked test, never-trained sources: 0.898**, the best in Kev's table (Kev-27B 0.896).
|
| 21 |
- **Computer use (Mind2Web), AUBIN-31B with no Mind2Web training beats GPT-4 on 9 of 9 numbers** (element acc / op F1 / step success): Cross-Task 48.0 / 81.0 / 40.0 vs 41.6 / 60.6 / 36.2; Cross-Website 41.0 / 82.0 / 33.5 vs 35.8 / 51.1 / 30.1; Cross-Domain 54.0 / 86.5 / 48.5 vs 37.1 / 46.5 / 26.4. GPT-4 in the paper chose from 10 candidates, AUBIN from 50.
|
| 22 |
- **Also beats the fine-tuned MindAct (Flan-T5-XL, trained on Mind2Web) on all three numbers**: Cross-Domain (54.0 / 86.5 / 48.5 vs 42.1 / 66.5 / 39.6).
|
|
|
|
|
|
|
| 23 |
- **Plays 2048** with a lookahead tool: mean 29,009, 2048 tile in 8/10 games ([replay](https://huggingface.co/spaces/emrevrg/aubin-2048)).
|
| 24 |
|
| 25 |
**Typed questions in, calibrated probabilities out.** AUBIN is Norovox's open-base model family: strong open-weight
|
|
@@ -43,6 +46,7 @@ questions). AUBIN is scored on exactly the same questions (`code/jev_compare.py`
|
|
| 43 |
| AUBIN Duo (31B + 12B full precision, think) | **0.863** | 0.2114 | **0.035** | **0.411** | **0.858** | **0.2243** | **0.029** | **0.554** |
|
| 44 |
| **AUBIN Duo-SC (31B self-consistent think + 12B full precision)** | **0.863** | **0.2104** | **0.039** | **0.409** | **0.862** | **0.2227** | **0.028** | **0.551** |
|
| 45 |
| **AUBIN Trio (31B-SC + 12B full precision + Phi-4)** | **0.872** | **0.2087** | **0.018** | **0.406** | **0.851** | **0.2315** | **0.032** | **0.536** |
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
**AUBIN Duo-SC (31B self-consistent think + 12B full precision) is better than Jev on all 8 numbers above** (accuracy, Brier, ECE, NLL on both splits), on the exact questions Jev's own report uses.
|
|
@@ -115,6 +119,8 @@ The costly failure of a decision model is being **confidently wrong** or misappl
|
|
| 115 |
| AUBIN Duo-SC (31B self-consistent think + 12B full precision) | trained sources | 5.22% → **1.98%** | 2.6× | 13 → **5** / 224 | 2.6× |
|
| 116 |
| AUBIN Trio (31B-SC + 12B full precision + Phi-4) | new sources | 3.66% → **2.74%** | 1.3× | 14 → **0** / 176 | ∞ (zero) |
|
| 117 |
| AUBIN Trio (31B-SC + 12B full precision + Phi-4) | trained sources | 5.22% → **2.69%** | 1.9× | 13 → **4** / 224 | 3.2× |
|
|
|
|
|
|
|
| 118 |
|
| 119 |
"Wrong while ≥90% confident" = share of all questions answered wrongly with confidence ≥ 0.9 (Jev: `confident_error_rate` from its report). AUBIN is more cautious — it is ≥90% sure on fewer questions — but when it is, it is right more often, and its overall calibration (ECE) is better. Rule/policy = `composition_*` + `contrastive_*` sources.
|
| 120 |
|
|
@@ -125,8 +131,9 @@ On the locked **test** split of sources AUBIN never trained on, **AUBIN-31B (fas
|
|
| 125 |
| model | new sources acc (dev / test) | trained sources acc (dev / test) | new sources Brier (dev / test) |
|
| 126 |
|---|---|---|---|
|
| 127 |
| **AUBIN-12B full precision (think)** | 0.857 / 0.878 | 0.851 / 0.835 | 0.233 / 0.199 |
|
| 128 |
-
| **AUBIN Duo-SC (31B self-consistent think + 12B full precision)** | 0.863 /
|
| 129 |
-
| **AUBIN Trio (31B-SC + 12B full precision + Phi-4)** | 0.872 /
|
|
|
|
| 130 |
| **AUBIN Duo (31B + 12B, think)** | 0.867 / 0.893 | 0.859 / 0.850 | 0.214 / 0.169 |
|
| 131 |
| Kev-0.8B | 0.648 / 0.697 | 0.827 / 0.838 | 0.481 / 0.416 |
|
| 132 |
| Kev-4B | 0.817 / 0.838 | 0.873 / 0.865 | 0.269 / 0.242 |
|
|
@@ -171,6 +178,52 @@ AUBIN-12B with a 2-step lookahead tool: the tool plays clear moves, AUBIN decide
|
|
| 171 |
| greedy merge rule | 2,982 | 1,464 | 3,676 | 0/10 |
|
| 172 |
| random | 933 | 272 | 1,508 | 0/10 |
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
## Measured speed (free Kaggle GPUs, 4-bit, batch = 1 case)
|
| 176 |
|
|
@@ -206,7 +259,7 @@ CLI: `aubin decide case.json --think 4` · `aubin loop "task" --numeric` · serv
|
|
| 206 |
|
| 207 |
## Honest notes
|
| 208 |
* Every number above is produced by the scripts in `code/` from per-question outputs; nothing is hand-edited.
|
| 209 |
-
* Every ensemble row (Duo, Duo-SC, Trio) uses **one fixed selection rule**: member weights and final temperature minimize
|
| 210 |
Brier + ECE on Kev's **calibration** split (decision-v7 calibration, 300 questions; `code/select_cal.py`). The development
|
| 211 |
and test splits are never used for selection; think mix is fixed at 0.5. The test columns are single confirmation runs.
|
| 212 |
The new-source Brier margin is small: if the rule were calibration NLL instead, Duo-SC would be behind Jev on new-source
|
|
@@ -215,6 +268,8 @@ CLI: `aubin decide case.json --think 4` · `aubin loop "task" --numeric` · serv
|
|
| 215 |
(including 12B variants trained with distillation and data weighting); only weights and temperature come from the rule.
|
| 216 |
* AUBIN Duo-SC: the 31B member thinks with 3 samples (greedy + 2 sampled, answer probabilities averaged; `think_samples=3`).
|
| 217 |
* AUBIN Trio adds microsoft/phi-4 (MIT, no adapter, temperature fitted on the calibration split) as a third, different-family member.
|
|
|
|
|
|
|
| 218 |
* AUBIN-12B full precision = the same adapter on the unquantized base (fp16 on 2x T4, or bf16 on one T4 through IRIS);
|
| 219 |
its temperature (3.2) is fitted on the calibration split like every other model here.
|
| 220 |
* Jev is a hosted API with lower latency (~220 ms median in Kev's report) and very low price; AUBIN's advantages are
|
|
|
|
| 14 |
## At a glance
|
| 15 |
|
| 16 |
- **Beats Jev on Jev's own published split, all 8 numbers**: accuracy 0.863 vs 0.857 and 0.862 vs 0.845; NLL 0.409 vs 0.701; Brier, ECE lower too.
|
| 17 |
+
- **AUBIN Trio (adds Phi-4), 8/8 vs Jev**: accuracy 0.872 vs 0.857 (new sources) and 0.851 vs 0.845 (trained sources); ECE 0.018 / 0.032 vs 0.049 / 0.067.
|
| 18 |
+
- **AUBIN Quad (adds Phi-4 + Mistral-Small; chosen by the rule), 8/8 vs Jev**: accuracy 0.869 vs 0.857 (new sources) and 0.856 vs 0.845 (trained sources); ECE 0.030 / 0.022 vs 0.049 / 0.067.
|
| 19 |
- **22x fewer confidently-wrong answers** (AUBIN-31B, one pass, trained-source split: 0.24% vs Jev 5.22%).
|
| 20 |
- **0 errors on held-out policy rules** it never trained on (Jev: 14 / 176).
|
| 21 |
- **Locked test, never-trained sources: 0.898**, the best in Kev's table (Kev-27B 0.896).
|
| 22 |
- **Computer use (Mind2Web), AUBIN-31B with no Mind2Web training beats GPT-4 on 9 of 9 numbers** (element acc / op F1 / step success): Cross-Task 48.0 / 81.0 / 40.0 vs 41.6 / 60.6 / 36.2; Cross-Website 41.0 / 82.0 / 33.5 vs 35.8 / 51.1 / 30.1; Cross-Domain 54.0 / 86.5 / 48.5 vs 37.1 / 46.5 / 26.4. GPT-4 in the paper chose from 10 candidates, AUBIN from 50.
|
| 23 |
- **Also beats the fine-tuned MindAct (Flan-T5-XL, trained on Mind2Web) on all three numbers**: Cross-Domain (54.0 / 86.5 / 48.5 vs 42.1 / 66.5 / 39.6).
|
| 24 |
+
- **Real-time control ([AUBIN-E4B-Control](https://huggingface.co/emrevrg/AUBIN-E4B-Control))**: 95% success, 0 lava deaths on 100 unseen command-following episodes, 385 ms per move on a free T4 (same safety shield on the best rule baseline: 89%).
|
| 25 |
+
- **AUBIN Loop (generator + decider, same Gemma weights)**: GSM8K (400 problems) 84.2% → **92.5%**; majority vote of the same samples 85.8%.
|
| 26 |
- **Plays 2048** with a lookahead tool: mean 29,009, 2048 tile in 8/10 games ([replay](https://huggingface.co/spaces/emrevrg/aubin-2048)).
|
| 27 |
|
| 28 |
**Typed questions in, calibrated probabilities out.** AUBIN is Norovox's open-base model family: strong open-weight
|
|
|
|
| 46 |
| AUBIN Duo (31B + 12B full precision, think) | **0.863** | 0.2114 | **0.035** | **0.411** | **0.858** | **0.2243** | **0.029** | **0.554** |
|
| 47 |
| **AUBIN Duo-SC (31B self-consistent think + 12B full precision)** | **0.863** | **0.2104** | **0.039** | **0.409** | **0.862** | **0.2227** | **0.028** | **0.551** |
|
| 48 |
| **AUBIN Trio (31B-SC + 12B full precision + Phi-4)** | **0.872** | **0.2087** | **0.018** | **0.406** | **0.851** | **0.2315** | **0.032** | **0.536** |
|
| 49 |
+
| **AUBIN Quad (31B-SC + 12B full precision + Phi-4 + Mistral-Small)** | **0.869** | **0.2068** | **0.030** | **0.404** | **0.856** | **0.2268** | **0.022** | **0.536** |
|
| 50 |
|
| 51 |
|
| 52 |
**AUBIN Duo-SC (31B self-consistent think + 12B full precision) is better than Jev on all 8 numbers above** (accuracy, Brier, ECE, NLL on both splits), on the exact questions Jev's own report uses.
|
|
|
|
| 119 |
| AUBIN Duo-SC (31B self-consistent think + 12B full precision) | trained sources | 5.22% → **1.98%** | 2.6× | 13 → **5** / 224 | 2.6× |
|
| 120 |
| AUBIN Trio (31B-SC + 12B full precision + Phi-4) | new sources | 3.66% → **2.74%** | 1.3× | 14 → **0** / 176 | ∞ (zero) |
|
| 121 |
| AUBIN Trio (31B-SC + 12B full precision + Phi-4) | trained sources | 5.22% → **2.69%** | 1.9× | 13 → **4** / 224 | 3.2× |
|
| 122 |
+
| AUBIN Quad (31B-SC + 12B full precision + Phi-4 + Mistral-Small) | new sources | 3.66% → **2.29%** | 1.6× | 14 → **0** / 176 | ∞ (zero) |
|
| 123 |
+
| AUBIN Quad (31B-SC + 12B full precision + Phi-4 + Mistral-Small) | trained sources | 5.22% → **2.14%** | 2.4× | 13 → **5** / 224 | 2.6× |
|
| 124 |
|
| 125 |
"Wrong while ≥90% confident" = share of all questions answered wrongly with confidence ≥ 0.9 (Jev: `confident_error_rate` from its report). AUBIN is more cautious — it is ≥90% sure on fewer questions — but when it is, it is right more often, and its overall calibration (ECE) is better. Rule/policy = `composition_*` + `contrastive_*` sources.
|
| 126 |
|
|
|
|
| 131 |
| model | new sources acc (dev / test) | trained sources acc (dev / test) | new sources Brier (dev / test) |
|
| 132 |
|---|---|---|---|
|
| 133 |
| **AUBIN-12B full precision (think)** | 0.857 / 0.878 | 0.851 / 0.835 | 0.233 / 0.199 |
|
| 134 |
+
| **AUBIN Duo-SC (31B self-consistent think + 12B full precision)** | 0.863 / 0.895 | 0.862 / 0.843 | 0.210 / 0.168 |
|
| 135 |
+
| **AUBIN Trio (31B-SC + 12B full precision + Phi-4)** | 0.872 / 0.889 | 0.851 / 0.851 | 0.209 / 0.169 |
|
| 136 |
+
| **AUBIN Quad (31B-SC + 12B full precision + Phi-4 + Mistral-Small)** | 0.869 / 0.886 | 0.856 / — | 0.207 / 0.168 |
|
| 137 |
| **AUBIN Duo (31B + 12B, think)** | 0.867 / 0.893 | 0.859 / 0.850 | 0.214 / 0.169 |
|
| 138 |
| Kev-0.8B | 0.648 / 0.697 | 0.827 / 0.838 | 0.481 / 0.416 |
|
| 139 |
| Kev-4B | 0.817 / 0.838 | 0.873 / 0.865 | 0.269 / 0.242 |
|
|
|
|
| 178 |
| greedy merge rule | 2,982 | 1,464 | 3,676 | 0/10 |
|
| 179 |
| random | 933 | 272 | 1,508 | 0/10 |
|
| 180 |
|
| 181 |
+
## Real-time control: command-following grid game
|
| 182 |
+
|
| 183 |
+
Each move: a 7x7 grid as text (walls, 5 deadly lava cells, 4 objects that block movement) and a command ("go to the red key"); the controller returns one move with a calibrated confidence. Same 100 episodes (seed 0) for every row, never seen in training (training episodes use seeds 1000+). Step accuracy = the move is on a shortest safe path (BFS ground truth). The safety shield only removes moves into visible lava/walls (`AubinController.act(..., allowed=...)`).
|
| 184 |
+
|
| 185 |
+
| controller | success | lava deaths ↓ | step accuracy | median ms / move (T4) |
|
| 186 |
+
|---|---|---|---|---|
|
| 187 |
+
| random | 6% | 40 | 35.3% | – |
|
| 188 |
+
| random + safety shield | 13% | 0 | 53.4% | – |
|
| 189 |
+
| greedy (ignores obstacles) | 58% | 26 | 56.8% | – |
|
| 190 |
+
| greedy + safety shield | 89% | 0 | 87.6% | – |
|
| 191 |
+
| Gemma-4-E4B base, no control training (one pass per move) | 8% | 26 | 39.2% | 329 |
|
| 192 |
+
| Gemma-4-E4B base, no control training + safety shield | 11% | 0 | 55.4% | 330 |
|
| 193 |
+
| AUBIN-E4B-Control (one pass per move) | 58% | 28 | 60.0% | 384 |
|
| 194 |
+
| AUBIN-E4B-Control + safety shield (never steps on visible lava/walls) | 95% | 0 | 93.2% | 385 |
|
| 195 |
+
| AUBIN-12B decision adapter, no control training (one pass per move) | 57% | 27 | 62.8% | 798 |
|
| 196 |
+
|
| 197 |
+
## Consistency and hallucination ("gray area" test types)
|
| 198 |
+
|
| 199 |
+
The test types follow an independent public review of Jev (Onur Tirpan, YouTube, Sep 2026: same question repeated, option order reversed, question rephrased, leading question, X vs not-X, false premise, invented quote, false alarm). AUBIN-12B was run on our own synthetic student records and invoices (Turkish + English, 40 documents); Jev's numbers are the ones shown in that review on its own Turkish items, so this is **not a same-item comparison**, and our documents are shorter and simpler. A harder version (distractor fields, synonyms, look-alike numbers) is next.
|
| 200 |
+
|
| 201 |
+
| test | AUBIN-12B (ours, 40 docs) | Jev (review, TR items) |
|
| 202 |
+
|---|---|---|
|
| 203 |
+
| decision changed when asked again | **0/120** | 1/60 |
|
| 204 |
+
| decision changed when options reversed | **0/120** | 11/60 |
|
| 205 |
+
| decision changed when question rephrased | **0/120** | 5/10 |
|
| 206 |
+
| followed a leading question | **0/40** | 2/10 |
|
| 207 |
+
| "X" and "not X" contradicted | **0/65** | 0/40 |
|
| 208 |
+
| accepted a false premise | **0/40** | 0/60 |
|
| 209 |
+
| accepted an invented quote | **0/40** | – |
|
| 210 |
+
| said a present field is missing | **0/40** | 2 in 20 docs |
|
| 211 |
+
|
| 212 |
+
## AUBIN Loop: generator + decider (`aubin loop`)
|
| 213 |
+
|
| 214 |
+
A generator writes candidate answers; AUBIN picks among them with calibrated probabilities; if confidence is below the target, the generator is asked again with the rejected candidates as feedback. On Gemma it is **one set of weights**: the generator is the same base with the AUBIN adapter switched off. Any OpenAI-compatible model (ChatGPT, vLLM, Ollama) can be the generator instead (`--generator openai:<model>`, key from the environment).
|
| 215 |
+
|
| 216 |
+
GSM8K test, 400 fixed problems, generator = Gemma-4-12B base, same candidates for every method:
|
| 217 |
+
|
| 218 |
+
| method | accuracy | samples / problem |
|
| 219 |
+
|---|---|---|
|
| 220 |
+
| generator alone (greedy) | 0.843 | 1 |
|
| 221 |
+
| majority vote of 5 samples | 0.858 | 5 |
|
| 222 |
+
| AUBIN picks among 5 samples | 0.900 | 5 |
|
| 223 |
+
| AUBIN × vote share | 0.905 | 5 |
|
| 224 |
+
| AUBIN Loop (2nd round only when unsure) | 0.925 | 6.46 |
|
| 225 |
+
| oracle: any of 5 samples correct (upper bound) | 0.917 | 5 |
|
| 226 |
+
|
| 227 |
|
| 228 |
## Measured speed (free Kaggle GPUs, 4-bit, batch = 1 case)
|
| 229 |
|
|
|
|
| 259 |
|
| 260 |
## Honest notes
|
| 261 |
* Every number above is produced by the scripts in `code/` from per-question outputs; nothing is hand-edited.
|
| 262 |
+
* Every ensemble row (Duo, Duo-SC, Trio, Quad) uses **one fixed selection rule**: member weights and final temperature minimize
|
| 263 |
Brier + ECE on Kev's **calibration** split (decision-v7 calibration, 300 questions; `code/select_cal.py`). The development
|
| 264 |
and test splits are never used for selection; think mix is fixed at 0.5. The test columns are single confirmation runs.
|
| 265 |
The new-source Brier margin is small: if the rule were calibration NLL instead, Duo-SC would be behind Jev on new-source
|
|
|
|
| 268 |
(including 12B variants trained with distillation and data weighting); only weights and temperature come from the rule.
|
| 269 |
* AUBIN Duo-SC: the 31B member thinks with 3 samples (greedy + 2 sampled, answer probabilities averaged; `think_samples=3`).
|
| 270 |
* AUBIN Trio adds microsoft/phi-4 (MIT, no adapter, temperature fitted on the calibration split) as a third, different-family member.
|
| 271 |
+
* AUBIN Quad adds mistralai/Mistral-Small-24B-Instruct-2501 (Apache-2.0, no adapter, calibration-fitted temperature 5.5) as a fourth
|
| 272 |
+
member; its trained-source test run hit the free-GPU session limit, so that test cell is not reported ("—").
|
| 273 |
* AUBIN-12B full precision = the same adapter on the unquantized base (fp16 on 2x T4, or bf16 on one T4 through IRIS);
|
| 274 |
its temperature (3.2) is fitted on the calibration split like every other model here.
|
| 275 |
* Jev is a hosted API with lower latency (~220 ms median in Kev's report) and very low price; AUBIN's advantages are
|
aubin_vs_jev.png
CHANGED
|
|
code/aubin/__init__.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""AUBIN by Norovox — açık-tabanlı, kalibre tipli karar modelleri."""
|
| 2 |
from .core import Aubin, AubinEnsemble, options
|
| 3 |
from .loop import AubinLoop, GemmaGenerator, OpenAIGenerator
|
|
|
|
| 4 |
|
| 5 |
__version__ = "0.1.0"
|
| 6 |
-
__all__ = ["Aubin", "AubinEnsemble", "options", "AubinLoop", "GemmaGenerator", "OpenAIGenerator"]
|
|
|
|
| 1 |
"""AUBIN by Norovox — açık-tabanlı, kalibre tipli karar modelleri."""
|
| 2 |
from .core import Aubin, AubinEnsemble, options
|
| 3 |
from .loop import AubinLoop, GemmaGenerator, OpenAIGenerator
|
| 4 |
+
from .control import AubinController
|
| 5 |
|
| 6 |
__version__ = "0.1.0"
|
| 7 |
+
__all__ = ["Aubin", "AubinEnsemble", "options", "AubinLoop", "GemmaGenerator", "OpenAIGenerator", "AubinController"]
|
code/aubin/control.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AUBIN Control — anlık hamle seçimi (oyun / arayüz / robot): gözlem + (isteğe bağlı) komut + olası hamleler → hamle.
|
| 2 |
+
|
| 3 |
+
Tek ileri geçiş (düşünme kapalı), kalibre güven. Güven eşiğin altındaysa güvenli yedek hamle döner — hata payı buradan
|
| 4 |
+
düşer: model emin değilken rastgele davranmaz. Her çağrı gecikmeyi (ms) döndürür.
|
| 5 |
+
|
| 6 |
+
from aubin import Aubin
|
| 7 |
+
from aubin.control import AubinController
|
| 8 |
+
ctl = AubinController(Aubin("emrevrg/AUBIN-12B"), actions={"up": "move up", "down": "move down",
|
| 9 |
+
"left": "move left", "right": "move right"},
|
| 10 |
+
min_conf=0.5, fallback="wait")
|
| 11 |
+
ctl.act(observation="#####\n#A..K#\n#####", command="go to the key K")
|
| 12 |
+
→ {"action": "right", "confidence": 0.97, "fallback_used": False, "latency_ms": 180.3, "probabilities": {...}}
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class AubinController:
|
| 19 |
+
def __init__(self, model, actions, min_conf=0.0, fallback=None, realtime=True, instructions=None):
|
| 20 |
+
"""actions: {ad: açıklama}; fallback: güven düşükse dönecek hamle adı (ör. "wait"/"noop"; None = en olası hamle);
|
| 21 |
+
realtime: düşünme kapalı (her hamle tek ileri geçiş)."""
|
| 22 |
+
self.m, self.actions, self.min_conf, self.fallback = model, dict(actions), float(min_conf), fallback
|
| 23 |
+
self.instructions = instructions or "Choose the single best next action for the current observation."
|
| 24 |
+
if realtime:
|
| 25 |
+
for mem in getattr(model, "members", None) and [x for x, _ in model.members] or [model]:
|
| 26 |
+
if hasattr(mem, "think_margin"):
|
| 27 |
+
mem.think_margin = 0.0
|
| 28 |
+
self.history = []
|
| 29 |
+
|
| 30 |
+
def reset(self):
|
| 31 |
+
"""Yeni bölüm/görev: hamle geçmişi temizlenir (eğitimdeki biçimle aynı — geçmiş bölüm içindir)."""
|
| 32 |
+
self.history = []
|
| 33 |
+
|
| 34 |
+
def act(self, observation, command=None, actions=None, context=None, allowed=None):
|
| 35 |
+
"""allowed: güvenlik kalkanı — izinli hamle kümesi (ör. lav/duvara gitmeyenler). Modelin seçimi izinli değilse
|
| 36 |
+
izinliler içinde en olası hamle seçilir (fallback_used=True)."""
|
| 37 |
+
acts = dict(actions or self.actions)
|
| 38 |
+
state = {"observation": observation}
|
| 39 |
+
if context:
|
| 40 |
+
state["context"] = context
|
| 41 |
+
if self.history:
|
| 42 |
+
state["recent_actions"] = [h["action"] for h in self.history[-5:]]
|
| 43 |
+
q = {"type": "choice", "criteria": acts,
|
| 44 |
+
"instructions": (f"Command: {command}. " if command else "") + self.instructions}
|
| 45 |
+
t0 = time.perf_counter()
|
| 46 |
+
res = self.m.decide(state, {"action": q})["action"]
|
| 47 |
+
ms = (time.perf_counter() - t0) * 1000
|
| 48 |
+
act, conf = res["answer"], float(res["confidence"])
|
| 49 |
+
used = False
|
| 50 |
+
if conf < self.min_conf and self.fallback is not None:
|
| 51 |
+
act, used = self.fallback, True
|
| 52 |
+
if allowed is not None and act not in allowed and any(a in allowed for a in res["probabilities"]):
|
| 53 |
+
act = max((a for a in res["probabilities"] if a in allowed), key=lambda a: res["probabilities"][a])
|
| 54 |
+
conf, used = float(res["probabilities"][act]), True
|
| 55 |
+
out = {"action": act, "confidence": round(conf, 4), "fallback_used": used, "latency_ms": round(ms, 1),
|
| 56 |
+
"probabilities": res["probabilities"]}
|
| 57 |
+
self.history.append(out)
|
| 58 |
+
return out
|
code/aubin/core.py
CHANGED
|
@@ -54,9 +54,20 @@ class Aubin:
|
|
| 54 |
self.tok.padding_side = "left"
|
| 55 |
if self.tok.pad_token is None:
|
| 56 |
self.tok.pad_token = self.tok.eos_token
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
if four_bit and dev != "cpu":
|
| 61 |
kw["quantization_config"] = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
|
| 62 |
bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True)
|
|
@@ -75,11 +86,35 @@ class Aubin:
|
|
| 75 |
for i, ad in enumerate(ads[1:], 1):
|
| 76 |
m.load_adapter(ad, adapter_name=f"a{i}")
|
| 77 |
self.adapters = [f"a{i}" for i in range(len(ads))]
|
|
|
|
|
|
|
| 78 |
self.m = m.eval()
|
| 79 |
self.dev = dev
|
| 80 |
self.letter_ids = [sorted({self.tok.encode(a, add_special_tokens=False)[0],
|
| 81 |
self.tok.encode(" " + a, add_special_tokens=False)[-1]}) for a in L]
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
@staticmethod
|
| 84 |
def _meta(adapter):
|
| 85 |
try:
|
|
@@ -108,13 +143,15 @@ class Aubin:
|
|
| 108 |
def _letters(self, prompts):
|
| 109 |
if self.cache_state and len(prompts) == 1 and "\n\nQUESTION:" in prompts[0]:
|
| 110 |
return self._letters_cached(prompts[0])
|
| 111 |
-
enc = self.tok(prompts, return_tensors="pt", padding=True, add_special_tokens=False
|
|
|
|
| 112 |
try:
|
| 113 |
out = self.m(**enc, logits_to_keep=1)
|
| 114 |
except TypeError:
|
| 115 |
out = self.m(**enc)
|
| 116 |
last = out.logits[:, -1].float()
|
| 117 |
-
|
|
|
|
| 118 |
|
| 119 |
@torch.no_grad()
|
| 120 |
def _letters_cached(self, prompt):
|
|
|
|
| 54 |
self.tok.padding_side = "left"
|
| 55 |
if self.tok.pad_token is None:
|
| 56 |
self.tok.pad_token = self.tok.eos_token
|
| 57 |
+
# AUBIN_DEVICE=xla: Kaggle/Cloud TPU (torch_xla) — bf16, 4-bit yok, uzunluk 256'nın katına dolgu (derleme tekrar kullanılır)
|
| 58 |
+
self.xla = os.environ.get("AUBIN_DEVICE", "") == "xla"
|
| 59 |
+
if self.xla:
|
| 60 |
+
import torch_xla.core.xla_model as xm
|
| 61 |
+
if os.environ.get("AUBIN_XLA_SPMD", "") == "1":
|
| 62 |
+
import torch_xla.runtime as xr
|
| 63 |
+
xr.use_spmd() # cihaz alınmadan önce açılmalı
|
| 64 |
+
dev = xm.xla_device()
|
| 65 |
+
kw = dict(dtype=torch.bfloat16, low_cpu_mem_usage=True)
|
| 66 |
+
four_bit = False
|
| 67 |
+
else:
|
| 68 |
+
dev = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 69 |
+
device_map = device_map or meta.get("device_map")
|
| 70 |
+
kw = dict(device_map=device_map or dev, dtype=torch.float16 if dev != "cpu" else torch.float32)
|
| 71 |
if four_bit and dev != "cpu":
|
| 72 |
kw["quantization_config"] = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
|
| 73 |
bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True)
|
|
|
|
| 86 |
for i, ad in enumerate(ads[1:], 1):
|
| 87 |
m.load_adapter(ad, adapter_name=f"a{i}")
|
| 88 |
self.adapters = [f"a{i}" for i in range(len(ads))]
|
| 89 |
+
if self.xla:
|
| 90 |
+
m = self._to_xla(m, dev)
|
| 91 |
self.m = m.eval()
|
| 92 |
self.dev = dev
|
| 93 |
self.letter_ids = [sorted({self.tok.encode(a, add_special_tokens=False)[0],
|
| 94 |
self.tok.encode(" " + a, add_special_tokens=False)[-1]}) for a in L]
|
| 95 |
|
| 96 |
+
@staticmethod
|
| 97 |
+
def _to_xla(m, dev):
|
| 98 |
+
"""TPU'ya taşı. AUBIN_XLA_SPMD=1: tüm çiplere (v5e-8 = 8 x 16 GB) satır-bölmeli SPMD — 12B/31B bf16 tek çipe sığmaz.
|
| 99 |
+
Parametreler tek tek taşınıp hemen bölünür; tam kopya hiçbir çipte birikmez."""
|
| 100 |
+
if os.environ.get("AUBIN_XLA_SPMD", "") != "1":
|
| 101 |
+
return m.to(dev)
|
| 102 |
+
import numpy as np
|
| 103 |
+
import torch_xla.runtime as xr
|
| 104 |
+
import torch_xla.distributed.spmd as xs
|
| 105 |
+
n =xr.global_runtime_device_count()
|
| 106 |
+
mesh = xs.Mesh(np.arange(n), (1, n), ("data", "model"))
|
| 107 |
+
for mod in m.modules():
|
| 108 |
+
for name, p in list(mod.named_parameters(recurse=False)) + list(mod.named_buffers(recurse=False)):
|
| 109 |
+
t = p.data.to(dev)
|
| 110 |
+
if t.dim() == 2 and t.shape[0] % n == 0:
|
| 111 |
+
xs.mark_sharding(t, mesh, ("model", None))
|
| 112 |
+
if isinstance(p, torch.nn.Parameter):
|
| 113 |
+
p.data = t
|
| 114 |
+
else:
|
| 115 |
+
mod._buffers[name] = t
|
| 116 |
+
return m
|
| 117 |
+
|
| 118 |
@staticmethod
|
| 119 |
def _meta(adapter):
|
| 120 |
try:
|
|
|
|
| 143 |
def _letters(self, prompts):
|
| 144 |
if self.cache_state and len(prompts) == 1 and "\n\nQUESTION:" in prompts[0]:
|
| 145 |
return self._letters_cached(prompts[0])
|
| 146 |
+
enc = self.tok(prompts, return_tensors="pt", padding=True, add_special_tokens=False,
|
| 147 |
+
pad_to_multiple_of=256 if self.xla else None).to(self.dev)
|
| 148 |
try:
|
| 149 |
out = self.m(**enc, logits_to_keep=1)
|
| 150 |
except TypeError:
|
| 151 |
out = self.m(**enc)
|
| 152 |
last = out.logits[:, -1].float()
|
| 153 |
+
r = torch.stack([last[:, ids].logsumexp(-1) for ids in self.letter_ids], -1)
|
| 154 |
+
return r.cpu() if self.xla else r
|
| 155 |
|
| 156 |
@torch.no_grad()
|
| 157 |
def _letters_cached(self, prompt):
|
code/aubin/mcp_server.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AUBIN MCP sunucusu (stdio, bağımlılıksız JSON-RPC 2.0) — başka bir yapay zekâ AUBIN'i araç olarak çağırır.
|
| 2 |
+
|
| 3 |
+
Araçlar:
|
| 4 |
+
decide(state, questions) → kalibre olasılıklar (tipli sorular)
|
| 5 |
+
act(observation, actions, command?) → anlık hamle + güven + gecikme (AubinController)
|
| 6 |
+
loop(task, numeric?) → üretici + karar döngüsü (AubinLoop, Gemma üretici)
|
| 7 |
+
|
| 8 |
+
İstemci yapılandırması (ör. Claude Desktop / Claude Code):
|
| 9 |
+
{"mcpServers": {"aubin": {"command": "python", "args": ["-m", "aubin.mcp_server", "--model", "emrevrg/AUBIN-12B"]}}}
|
| 10 |
+
Model ilk araç çağrısında bir kez yüklenir; istekler sırayla işlenir (tek GPU).
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
import argparse, json, sys, threading, traceback
|
| 14 |
+
|
| 15 |
+
PROTOCOL = "2025-06-18"
|
| 16 |
+
TOOLS = [
|
| 17 |
+
{"name": "decide", "description": "Typed decision: state + questions (choice / noul / score) -> calibrated probabilities.",
|
| 18 |
+
"inputSchema": {"type": "object", "properties": {"state": {}, "questions": {"type": "object"}}, "required": ["state", "questions"]}},
|
| 19 |
+
{"name": "act", "description": "Real-time control: observation + allowed actions {name: description} (+ optional command) "
|
| 20 |
+
"-> one action with confidence and latency. Low confidence falls back to 'fallback' if given.",
|
| 21 |
+
"inputSchema": {"type": "object", "properties": {"observation": {}, "actions": {"type": "object"}, "command": {"type": "string"},
|
| 22 |
+
"min_conf": {"type": "number"}, "fallback": {"type": "string"}},
|
| 23 |
+
"required": ["observation", "actions"]}},
|
| 24 |
+
{"name": "loop", "description": "Generator + decider loop: candidates are generated, AUBIN picks with calibrated confidence, "
|
| 25 |
+
"regenerates when unsure.",
|
| 26 |
+
"inputSchema": {"type": "object", "properties": {"task": {"type": "string"}, "numeric": {"type": "boolean"}}, "required": ["task"]}},
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Server:
|
| 31 |
+
def __init__(self, model_spec, think):
|
| 32 |
+
self.spec, self.think, self.m, self.lock = model_spec, think, None, threading.Lock()
|
| 33 |
+
|
| 34 |
+
def model(self):
|
| 35 |
+
if self.m is None:
|
| 36 |
+
from .core import Aubin, AubinEnsemble
|
| 37 |
+
specs = [x.rsplit(":", 1) if ":" in x and not x.startswith("hf:") else (x, "1") for x in self.spec.split(",")]
|
| 38 |
+
ms = [(Aubin(r, think_margin=self.think), float(w)) for r, w in specs]
|
| 39 |
+
self.m = ms[0][0] if len(ms) == 1 else AubinEnsemble(ms)
|
| 40 |
+
return self.m
|
| 41 |
+
|
| 42 |
+
def call(self, name, args):
|
| 43 |
+
with self.lock:
|
| 44 |
+
m = self.model()
|
| 45 |
+
if name == "decide":
|
| 46 |
+
return m.decide(args["state"], args["questions"])
|
| 47 |
+
if name == "act":
|
| 48 |
+
from .control import AubinController
|
| 49 |
+
ctl = AubinController(m, args["actions"], min_conf=args.get("min_conf", 0.0), fallback=args.get("fallback"))
|
| 50 |
+
return ctl.act(args["observation"], args.get("command"))
|
| 51 |
+
if name == "loop":
|
| 52 |
+
from .loop import AubinLoop, GemmaGenerator, last_number, final_line
|
| 53 |
+
base = m if hasattr(m, "tok") else m.members[0][0]
|
| 54 |
+
lp = AubinLoop(m, GemmaGenerator(base), extract=last_number if args.get("numeric") else final_line, mode="aubin+vote")
|
| 55 |
+
return lp.solve(args["task"])
|
| 56 |
+
raise ValueError(f"bilinmeyen araç: {name}")
|
| 57 |
+
|
| 58 |
+
def handle(self, msg):
|
| 59 |
+
mid, meth, p = msg.get("id"), msg.get("method"), msg.get("params") or {}
|
| 60 |
+
if meth == "initialize":
|
| 61 |
+
return {"protocolVersion": p.get("protocolVersion", PROTOCOL), "capabilities": {"tools": {}},
|
| 62 |
+
"serverInfo": {"name": "aubin", "version": "0.1.0"}}
|
| 63 |
+
if meth == "tools/list":
|
| 64 |
+
return {"tools": TOOLS}
|
| 65 |
+
if meth == "tools/call":
|
| 66 |
+
try:
|
| 67 |
+
out = self.call(p["name"], p.get("arguments") or {})
|
| 68 |
+
return {"content": [{"type": "text", "text": json.dumps(out, ensure_ascii=False)}], "isError": False}
|
| 69 |
+
except Exception as e:
|
| 70 |
+
return {"content": [{"type": "text", "text": f"{type(e).__name__}: {e}"}], "isError": True}
|
| 71 |
+
if meth == "ping":
|
| 72 |
+
return {}
|
| 73 |
+
if mid is None: # bildirim (ör. notifications/initialized): cevap yok
|
| 74 |
+
return None
|
| 75 |
+
raise KeyError(meth)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main():
|
| 79 |
+
ap = argparse.ArgumentParser(prog="aubin-mcp")
|
| 80 |
+
ap.add_argument("--model", default="emrevrg/AUBIN-12B"); ap.add_argument("--think", type=float, default=None)
|
| 81 |
+
a = ap.parse_args()
|
| 82 |
+
S = Server(a.model, a.think)
|
| 83 |
+
for line in sys.stdin:
|
| 84 |
+
line = line.strip()
|
| 85 |
+
if not line:
|
| 86 |
+
continue
|
| 87 |
+
try:
|
| 88 |
+
msg = json.loads(line)
|
| 89 |
+
except json.JSONDecodeError:
|
| 90 |
+
continue
|
| 91 |
+
try:
|
| 92 |
+
res = S.handle(msg)
|
| 93 |
+
if msg.get("id") is None:
|
| 94 |
+
continue
|
| 95 |
+
reply = {"jsonrpc": "2.0", "id": msg["id"], "result": res}
|
| 96 |
+
except KeyError as e:
|
| 97 |
+
reply = {"jsonrpc": "2.0", "id": msg.get("id"), "error": {"code": -32601, "message": f"method not found: {e}"}}
|
| 98 |
+
except Exception as e:
|
| 99 |
+
print(traceback.format_exc(), file=sys.stderr)
|
| 100 |
+
reply = {"jsonrpc": "2.0", "id": msg.get("id"), "error": {"code": -32603, "message": str(e)}}
|
| 101 |
+
sys.stdout.write(json.dumps(reply, ensure_ascii=False) + "\n"); sys.stdout.flush()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
main()
|
code/bench_cache.py
CHANGED
|
@@ -20,6 +20,8 @@ def main():
|
|
| 20 |
a = ap.parse_args()
|
| 21 |
import kevdata
|
| 22 |
from aubin.core import Aubin
|
|
|
|
|
|
|
| 23 |
K = kevdata.load(a.work)
|
| 24 |
cases = [c for c in K[a.suite] if len(c["questions"]) >= 2][: a.n_cases]
|
| 25 |
A = Aubin(a.adapter, four_bit=not a.no4bit, device_map=a.device_map, think_margin=0.0)
|
|
|
|
| 20 |
a = ap.parse_args()
|
| 21 |
import kevdata
|
| 22 |
from aubin.core import Aubin
|
| 23 |
+
from kev_llm import resolve_adapter
|
| 24 |
+
a.adapter = resolve_adapter(a.adapter)
|
| 25 |
K = kevdata.load(a.work)
|
| 26 |
cases = [c for c in K[a.suite] if len(c["questions"]) >= 2][: a.n_cases]
|
| 27 |
A = Aubin(a.adapter, four_bit=not a.no4bit, device_map=a.device_map, think_margin=0.0)
|
code/control_bench.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AUBIN Control ölçümü: komutlu ızgara oyunu (anlık hamle, doğru cevap her adımda kesin bilinir).
|
| 2 |
+
|
| 3 |
+
Her bölüm: 7x7 ızgara, duvarlar, lav (~), renkli nesneler (engel), komut "go to the <renk> <nesne>".
|
| 4 |
+
Her adımda doğru hamleler = hedefe giden EN KISA yolların ilk adımları (BFS, lav ve nesnelerden kaçınarak).
|
| 5 |
+
Ölçüler: adım doğruluğu, bölüm başarısı, lava düşme, güven ≥ eşik iken doğruluk ve kapsama, karar başına gecikme (ms).
|
| 6 |
+
Karşılaştırma: rastgele ve açgözlü (Manhattan, engelleri görmez) politikalar — aynı bölümler.
|
| 7 |
+
python control_bench.py --adapter aubin12-plain --episodes 100 --out control.json
|
| 8 |
+
"""
|
| 9 |
+
import argparse, collections, json, os, random, sys, time
|
| 10 |
+
|
| 11 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
+
sys.path.insert(0, HERE)
|
| 13 |
+
MOVES = {"up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1)}
|
| 14 |
+
ACTIONS = {"up": "move one cell up (row - 1)", "down": "move one cell down (row + 1)",
|
| 15 |
+
"left": "move one cell left (column - 1)", "right": "move one cell right (column + 1)"}
|
| 16 |
+
COLORS, KINDS = ["red", "green", "blue", "yellow"], ["key", "ball", "box"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def make(rng, n=7, lava=5, objs=4):
|
| 20 |
+
while True:
|
| 21 |
+
cells = [(r, c) for r in range(1, n + 1) for c in range(1, n + 1)]
|
| 22 |
+
rng.shuffle(cells)
|
| 23 |
+
agent, rest = cells[0], cells[1:]
|
| 24 |
+
items = [(rest[i], rng.choice(COLORS), rng.choice(KINDS)) for i in range(objs)]
|
| 25 |
+
names = {(c, k) for _, c, k in items}
|
| 26 |
+
if len(names) < objs:
|
| 27 |
+
continue
|
| 28 |
+
lv = set(rest[objs: objs + lava])
|
| 29 |
+
tgt = items[0]
|
| 30 |
+
if optimal(agent, tgt[0], lv, {p for p, _, _ in items[1:]}, n)[0] is not None:
|
| 31 |
+
return {"n": n, "agent": agent, "items": items, "lava": lv, "target": tgt}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def optimal(start, goal, lava, block, n):
|
| 35 |
+
"""BFS uzaklık haritası hedeften; dönüş: (uzaklık, en kısa yolun ilk adımları)."""
|
| 36 |
+
ok = lambda p: 1 <= p[0] <= n and 1 <= p[1] <= n and p not in lava and p not in block
|
| 37 |
+
dist, dq = {goal: 0}, collections.deque([goal])
|
| 38 |
+
while dq:
|
| 39 |
+
p = dq.popleft()
|
| 40 |
+
for dr, dc in MOVES.values():
|
| 41 |
+
q = (p[0] + dr, p[1] + dc)
|
| 42 |
+
if q not in dist and (ok(q) or q == start):
|
| 43 |
+
dist[q] = dist[p] + 1; dq.append(q)
|
| 44 |
+
if start not in dist:
|
| 45 |
+
return None, set()
|
| 46 |
+
best = {a for a, (dr, dc) in MOVES.items() if dist.get((start[0] + dr, start[1] + dc), 1e9) == dist[start] - 1}
|
| 47 |
+
return dist[start], best
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def render(ep, pos):
|
| 51 |
+
n = ep["n"]; g = [["#"] * (n + 2) for _ in range(n + 2)]
|
| 52 |
+
for r in range(1, n + 1):
|
| 53 |
+
for c in range(1, n + 1):
|
| 54 |
+
g[r][c] = "."
|
| 55 |
+
for p in ep["lava"]:
|
| 56 |
+
g[p[0]][p[1]] = "~"
|
| 57 |
+
for p, col, k in ep["items"]:
|
| 58 |
+
g[p[0]][p[1]] = col[0].upper() if k == "key" else col[0]
|
| 59 |
+
g[pos[0]][pos[1]] = "@"
|
| 60 |
+
obj = [f"{col} {k} at row {p[0]}, column {p[1]}" for p, col, k in ep["items"]]
|
| 61 |
+
return {"grid": "\n".join("".join(r) for r in g),
|
| 62 |
+
"legend": "@ = you, # = wall, ~ = lava (deadly), letters = objects (they block movement)",
|
| 63 |
+
"you": f"row {pos[0]}, column {pos[1]}", "objects": obj}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def run(policy, eps, max_extra=4):
|
| 67 |
+
steps = hit = succ = dead = 0; lat, conf_rows = [], []
|
| 68 |
+
for ep in eps:
|
| 69 |
+
getattr(policy, "reset", lambda: None)() # yeni bölüm: hamle geçmişi sıfır (eğitim biçimiyle aynı)
|
| 70 |
+
pos = ep["agent"]; tp, col, k = ep["target"]; block = {p for p, _, _ in ep["items"][1:]}
|
| 71 |
+
d0, _ = optimal(pos, tp, ep["lava"], block, ep["n"])
|
| 72 |
+
for _ in range(d0 + max_extra):
|
| 73 |
+
d, best = optimal(pos, tp, ep["lava"], block, ep["n"])
|
| 74 |
+
obs = render(ep, pos)
|
| 75 |
+
# görünen haritadan güvenli hamleler (lav / duvar / nesneye gitmeyen; hedef hücre serbest) — güvenlik kalkanı için
|
| 76 |
+
safe = {a for a, (dr, dc) in MOVES.items() if (q := (pos[0] + dr, pos[1] + dc)) == tp or
|
| 77 |
+
(1 <= q[0] <= ep["n"] and 1 <= q[1] <= ep["n"] and q not in ep["lava"] and q not in block)}
|
| 78 |
+
t0 = time.perf_counter(); a, c = policy(obs, f"go to the {col} {k}", pos, tp, safe); lat.append((time.perf_counter() - t0) * 1000)
|
| 79 |
+
steps += 1; ok = a in best; hit += ok; conf_rows.append((c, ok))
|
| 80 |
+
dr, dc = MOVES.get(a, (0, 0)); q = (pos[0] + dr, pos[1] + dc)
|
| 81 |
+
if q == tp:
|
| 82 |
+
succ += 1; break
|
| 83 |
+
if q in ep["lava"]:
|
| 84 |
+
dead += 1; break
|
| 85 |
+
if 1 <= q[0] <= ep["n"] and 1 <= q[1] <= ep["n"] and q not in block:
|
| 86 |
+
pos = q
|
| 87 |
+
out = {"episodes": len(eps), "decisions": steps, "step_accuracy": round(hit / steps, 4), "success": round(succ / len(eps), 4),
|
| 88 |
+
"lava_deaths": dead, "ms_per_decision_median": round(sorted(lat)[len(lat) // 2], 1)}
|
| 89 |
+
for th in (0.8, 0.9):
|
| 90 |
+
sel = [ok for c, ok in conf_rows if c is not None and c >= th]
|
| 91 |
+
if sel:
|
| 92 |
+
out[f"acc_when_conf_ge_{th}"] = round(sum(sel) / len(sel), 4); out[f"coverage_conf_ge_{th}"] = round(len(sel) / len(conf_rows), 4)
|
| 93 |
+
return out
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def main():
|
| 97 |
+
ap = argparse.ArgumentParser()
|
| 98 |
+
ap.add_argument("--adapter", default="aubin12-plain"); ap.add_argument("--episodes", type=int, default=100)
|
| 99 |
+
ap.add_argument("--seed", type=int, default=0); ap.add_argument("--work", default=""); ap.add_argument("--out", default="control.json")
|
| 100 |
+
ap.add_argument("--no_model", action="store_true"); ap.add_argument("--label", default="AUBIN-12B")
|
| 101 |
+
a = ap.parse_args()
|
| 102 |
+
rng = random.Random(a.seed); eps = [make(rng) for _ in range(a.episodes)]
|
| 103 |
+
R = {"episodes": a.episodes, "seed": a.seed, "rows": {}}
|
| 104 |
+
r2 = random.Random(1)
|
| 105 |
+
R["rows"]["random"] = run(lambda o, cmd, p, t, s: (r2.choice(list(MOVES)), None), eps)
|
| 106 |
+
def greedy(o, cmd, p, t, s=None):
|
| 107 |
+
dr, dc = t[0] - p[0], t[1] - p[1]
|
| 108 |
+
return ("down" if dr > 0 else "up") if abs(dr) >= abs(dc) and dr else ("right" if dc > 0 else "left"), None
|
| 109 |
+
R["rows"]["greedy (ignores obstacles)"] = run(greedy, eps)
|
| 110 |
+
# aynı güvenlik kalkanıyla kural tabanlı taban çizgileri (kalkanın tek başına katkısını ayırmak için)
|
| 111 |
+
r3 = random.Random(2)
|
| 112 |
+
R["rows"]["random + safety shield"] = run(lambda o, cmd, p, t, s: (r3.choice(sorted(s)) if s else "up", None), eps)
|
| 113 |
+
def greedy_shield(o, cmd, p, t, s):
|
| 114 |
+
dr, dc = t[0] - p[0], t[1] - p[1]
|
| 115 |
+
pref = [] # hedefe yaklaştıran hamleler önce (büyük eksen önce)
|
| 116 |
+
vert = ("down" if dr > 0 else "up") if dr else None; hor = ("right" if dc > 0 else "left") if dc else None
|
| 117 |
+
pref += [m for m in ((vert, hor) if abs(dr) >= abs(dc) else (hor, vert)) if m]
|
| 118 |
+
for m in pref + sorted(s):
|
| 119 |
+
if m in s:
|
| 120 |
+
return m, None
|
| 121 |
+
return "up", None
|
| 122 |
+
R["rows"]["greedy + safety shield"] = run(greedy_shield, eps)
|
| 123 |
+
if not a.no_model:
|
| 124 |
+
from kev_llm import resolve_adapter
|
| 125 |
+
from aubin.core import Aubin
|
| 126 |
+
from aubin.control import AubinController
|
| 127 |
+
A = Aubin(resolve_adapter(a.adapter) or None, think_margin=0.0)
|
| 128 |
+
ctl = AubinController(A, ACTIONS, instructions="Choose the next move that follows the command along a shortest safe path "
|
| 129 |
+
"(never step on lava, objects block movement).")
|
| 130 |
+
class Pol: # bölüm başında ctl.reset; kalkan isteğe bağlı
|
| 131 |
+
def __init__(self, shield): self.shield = shield
|
| 132 |
+
def reset(self): ctl.reset()
|
| 133 |
+
def __call__(self, o, cmd, p, t, s):
|
| 134 |
+
r = ctl.act(o, command=cmd, allowed=s if self.shield else None); return r["action"], r["confidence"]
|
| 135 |
+
R["rows"][f"{a.label} (one pass per move)"] = run(Pol(False), eps)
|
| 136 |
+
R["rows"][f"{a.label} + safety shield (never steps on visible lava/walls)"] = run(Pol(True), eps)
|
| 137 |
+
json.dump(R, open(a.out, "w"), indent=1)
|
| 138 |
+
print("SONUC", json.dumps(R), flush=True)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
main()
|
code/control_train.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AUBIN Control eğitimi: komutlu ızgara oyunundan sınırsız, doğru etiketli örnek → LoRA (kev_llm.train_lora).
|
| 2 |
+
|
| 3 |
+
Örnekler control_bench'in AYNI biçiminden gelir ama FARKLI tohumlardan (eğitim 1000+, ölçüm 0) → ölçüm bölümleri eğitimde görülmez.
|
| 4 |
+
Her örnek: bir bölümde en kısa yol boyunca bir konum; doğru hamle(ler) BFS'ten; birden çok en-kısa hamle varsa yumuşak etiket
|
| 5 |
+
(eşit dağılım, `teacher` sözlüğü). Durum, AubinController.act ile birebir aynı biçimde kurulur (observation + recent_actions).
|
| 6 |
+
python control_train.py --init_adapter aubin12-plain --episodes 3000 --train 1200 --adapter /kaggle/working/lora_ctl
|
| 7 |
+
"""
|
| 8 |
+
import argparse, json, math, os, random, sys
|
| 9 |
+
|
| 10 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
+
sys.path.insert(0, HERE)
|
| 12 |
+
import control_bench as CB
|
| 13 |
+
import kev_llm as KL
|
| 14 |
+
|
| 15 |
+
INSTR = ("Choose the next move that follows the command along a shortest safe path "
|
| 16 |
+
"(never step on lava, objects block movement).")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def examples(n_eps, seed, offpath=0):
|
| 20 |
+
"""offpath: bölüm başına en kısa yol DIŞINDAKİ rastgele erişilebilir konumlardan ek örnek (sapınca toparlanmayı öğretir;
|
| 21 |
+
ölçümde model kendi hamleleriyle yoldan çıkabilir — yalnız yol üstü örnekler bu durumu hiç göstermez)."""
|
| 22 |
+
rng = random.Random(seed); out, teacher = [], {}
|
| 23 |
+
keys = list(CB.ACTIONS); texts = [f"{k}: {v}" for k, v in CB.ACTIONS.items()]
|
| 24 |
+
for e in range(n_eps):
|
| 25 |
+
ep = CB.make(rng); pos = ep["agent"]; tp, col, k = ep["target"]; block = {p for p, _, _ in ep["items"][1:]}
|
| 26 |
+
free = [(r, c) for r in range(1, ep["n"] + 1) for c in range(1, ep["n"] + 1)
|
| 27 |
+
if (r, c) not in ep["lava"] and (r, c) not in block and (r, c) != tp]
|
| 28 |
+
for j, q in enumerate(rng.sample(free, min(offpath, len(free)))):
|
| 29 |
+
d, best = CB.optimal(q, tp, ep["lava"], block, ep["n"])
|
| 30 |
+
if not best:
|
| 31 |
+
continue
|
| 32 |
+
state = {"observation": CB.render(ep, q)}
|
| 33 |
+
if rng.random() < 0.5: # bazen geçmiş de ver (modelin kendi önceki hamleleri gibi)
|
| 34 |
+
state["recent_actions"] = [rng.choice(keys) for _ in range(rng.randint(1, 5))]
|
| 35 |
+
key = f"ctl/{seed}/{e}/off{j}"
|
| 36 |
+
out.append({"key": key, "src": "control_grid_off", "state": json.dumps(state, ensure_ascii=False),
|
| 37 |
+
"q": f"Command: go to the {col} {k}. " + INSTR, "type": "choice", "keys": keys, "texts": texts,
|
| 38 |
+
"y": keys.index(sorted(best)[0])})
|
| 39 |
+
teacher[key] = [0.0 if a in best else -30.0 for a in keys]
|
| 40 |
+
hist = []
|
| 41 |
+
while True:
|
| 42 |
+
d, best = CB.optimal(pos, tp, ep["lava"], block, ep["n"])
|
| 43 |
+
if not best:
|
| 44 |
+
break
|
| 45 |
+
state = {"observation": CB.render(ep, pos)}
|
| 46 |
+
if hist:
|
| 47 |
+
state["recent_actions"] = hist[-5:]
|
| 48 |
+
key = f"ctl/{seed}/{e}/{len(hist)}"
|
| 49 |
+
y = keys.index(sorted(best)[0])
|
| 50 |
+
out.append({"key": key, "src": "control_grid", "state": json.dumps(state, ensure_ascii=False),
|
| 51 |
+
"q": f"Command: go to the {col} {k}. " + INSTR, "type": "choice", "keys": keys, "texts": texts, "y": y})
|
| 52 |
+
teacher[key] = [0.0 if a in best else -30.0 for a in keys] # eşit dağılım en kısa hamleler üzerinde
|
| 53 |
+
a = rng.choice(sorted(best)); dr, dc = CB.MOVES[a]; pos = (pos[0] + dr, pos[1] + dc); hist.append(a)
|
| 54 |
+
if pos == tp:
|
| 55 |
+
break
|
| 56 |
+
return out, teacher
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def main():
|
| 60 |
+
ap = argparse.ArgumentParser()
|
| 61 |
+
ap.add_argument("--model", default="google/gemma-4-12B-it"); ap.add_argument("--init_adapter", default="")
|
| 62 |
+
ap.add_argument("--episodes", type=int, default=3000); ap.add_argument("--train", type=int, default=1200)
|
| 63 |
+
ap.add_argument("--lr", type=float, default=5e-5); ap.add_argument("--bs", type=int, default=4)
|
| 64 |
+
ap.add_argument("--adapter", default="lora_ctl"); ap.add_argument("--no4bit", action="store_true")
|
| 65 |
+
ap.add_argument("--work", default=""); ap.add_argument("--save_every", type=int, default=400)
|
| 66 |
+
ap.add_argument("--offpath", type=int, default=0)
|
| 67 |
+
a = ap.parse_args()
|
| 68 |
+
tr, teach = examples(a.episodes, 1000, a.offpath)
|
| 69 |
+
dev, _ = examples(60, 900, a.offpath) # seçim: ayrı tohum (ölçüm tohumu 0'a hiç dokunulmaz)
|
| 70 |
+
print({"train_examples": len(tr), "dev_examples": len(dev)}, flush=True)
|
| 71 |
+
S = KL.Scorer(a.model, four_bit=not a.no4bit)
|
| 72 |
+
S.tok.padding_side = "left"
|
| 73 |
+
if S.tok.pad_token is None:
|
| 74 |
+
S.tok.pad_token = S.tok.eos_token
|
| 75 |
+
KL.train_lora(S, tr, a.train, a.lr, a.bs, a.adapter, seed=0, init_adapter=KL.resolve_adapter(a.init_adapter),
|
| 76 |
+
dev=dev[:300], eval_every=200, teacher=teach, alpha=0.5, save_every=a.save_every)
|
| 77 |
+
json.dump({"best_dev": getattr(S, "best_dev", None), "train_examples": len(tr)}, open(a.adapter.rstrip("/") + "_train.json", "w"))
|
| 78 |
+
print("EGITIM BITTI", getattr(S, "best_dev", None), flush=True)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == "__main__":
|
| 82 |
+
main()
|
code/graybench.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AUBIN "gri alan" testi — Jev raporundaki (Onur Tirpan videosu) test türleri, kendi sentetik belgelerimizle.
|
| 2 |
+
|
| 3 |
+
Belgeler (öğrenci kaydı / fatura), Türkçe ve İngilizce, cevaplar üreticiden kesin bilinir. Testler:
|
| 4 |
+
repeat aynı soru iki kez → karar değişti mi (hata / deneme), en büyük olasılık farkı
|
| 5 |
+
order seçenek sırası ters çevrildi → karar değişti mi, en büyük olasılık farkı
|
| 6 |
+
phrasing aynı soru 3 farklı ifadeyle → karar değişti mi
|
| 7 |
+
leading soruya yanlış cevabı ima eden ifade eklendi → yanlış cevaba kaydı mı
|
| 8 |
+
x_notx "X var mı?" ile "X yok mu?" → çelişki (ikisi aynı yönde)
|
| 9 |
+
false_premise belgede olmayan alan sorulur, "belgede yok" seçeneği var → uydurdu mu
|
| 10 |
+
fake_quote belgede geçmeyen cümle "belgede geçiyor mu?" → evet dedi mi
|
| 11 |
+
Aynı maddeler iki modda: perms=1 (tek sıra) ve perms=2 (sıra-dengeli: seçenek sıraları ortalanır).
|
| 12 |
+
python graybench.py --adapter aubin12-plain --n_docs 30 --out gray.json
|
| 13 |
+
"""
|
| 14 |
+
import argparse, json, os, random, sys, time
|
| 15 |
+
|
| 16 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 17 |
+
sys.path.insert(0, HERE)
|
| 18 |
+
FIRST = ["Ayşe", "Mehmet", "Elif", "Can", "Zeynep", "Emre", "Deniz", "Selin"]
|
| 19 |
+
LAST = ["Yılmaz", "Kaya", "Demir", "Şahin", "Çelik", "Arslan"]
|
| 20 |
+
CITY = ["İstanbul", "Ankara", "İzmir", "Bursa", "Konya"]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def harden(d, rng):
|
| 24 |
+
"""Zor sürüm: çeldirici alanlar, eş anlamlı etiketler, telefona benzeyen numaralar, boş imza çizgisi, uzun not paragrafı."""
|
| 25 |
+
L = d["lang"]; t = d["text"]
|
| 26 |
+
t = t.replace("Okul numarası", "Öğr. No").replace("School number", "Stud. No") if rng.random() < 0.5 else t
|
| 27 |
+
extra = []
|
| 28 |
+
if d["kind"] == "student":
|
| 29 |
+
extra += [T(L, f"Veli adı: {rng.choice(FIRST)} {rng.choice(LAST)}", f"Guardian: {rng.choice(FIRST)} {rng.choice(LAST)}"),
|
| 30 |
+
T(L, f"Sınıf öğretmeni: {rng.choice(FIRST)} {rng.choice(LAST)}", f"Homeroom teacher: {rng.choice(FIRST)} {rng.choice(LAST)}"),
|
| 31 |
+
T(L, f"Kayıt tarihi: {rng.randint(1, 28)}.09.2026", f"Enrolment date: {rng.randint(1, 28)}.09.2026")]
|
| 32 |
+
else:
|
| 33 |
+
extra += [T(L, f"Fatura no: {rng.randint(10, 99)}{rng.randint(1000000, 9999999)}", f"Invoice no.: {rng.randint(10, 99)}{rng.randint(1000000, 9999999)}"),
|
| 34 |
+
f"IBAN: TR{rng.randint(10, 99)} 0006 {rng.randint(1000, 9999)} {rng.randint(1000, 9999)} {rng.randint(1000, 9999)} {rng.randint(10, 99)}",
|
| 35 |
+
T(L, f"Faks: 0212 {rng.randint(100, 999)} {rng.randint(10, 99)} {rng.randint(10, 99)}" if not d["has_phone"] else "Faks: -",
|
| 36 |
+
f"Fax: 0212 {rng.randint(100, 999)} {rng.randint(10, 99)} {rng.randint(10, 99)}" if not d["has_phone"] else "Fax: -"),
|
| 37 |
+
T(L, "Kaşe / imza alanı: ______________", "Stamp / signature field: ______________") if not d["fields"]["signed"] else
|
| 38 |
+
T(L, "Kaşe / imza alanı: [imzalı]", "Stamp / signature field: [signed]")]
|
| 39 |
+
note = T(L, "Not: Bu belge sistemden otomatik oluşturulmuştur; bilgiler kayıt sırasında beyan edilen verilere dayanır ve "
|
| 40 |
+
"gerektiğinde ilgili birim tarafından güncellenebilir. Sorularınız için okul/şirket sekreterliğine başvurunuz.",
|
| 41 |
+
"Note: This document was generated automatically; the information is based on data declared at registration and may "
|
| 42 |
+
"be updated by the relevant office when needed. For questions please contact the secretariat.")
|
| 43 |
+
rng.shuffle(extra)
|
| 44 |
+
d = dict(d); d["text"] = t + "\n" + "\n".join(extra) + "\n" + note
|
| 45 |
+
return d
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def doc(rng, lang):
|
| 49 |
+
kind = rng.choice(["student", "invoice"])
|
| 50 |
+
if kind == "student":
|
| 51 |
+
f = {"name": f"{rng.choice(FIRST)} {rng.choice(LAST)}", "number": str(rng.randint(10000, 99999)),
|
| 52 |
+
"grade": str(rng.randint(9, 12)), "city": rng.choice(CITY)}
|
| 53 |
+
has_phone = rng.random() < 0.5
|
| 54 |
+
if has_phone:
|
| 55 |
+
f["phone"] = f"05{rng.randint(10, 59)} {rng.randint(100, 999)} {rng.randint(10, 99)} {rng.randint(10, 99)}"
|
| 56 |
+
lab = ({"name": "Öğrenci adı", "number": "Okul numarası", "grade": "Sınıf", "city": "Şehir", "phone": "Telefon"} if lang == "tr"
|
| 57 |
+
else {"name": "Student name", "number": "School number", "grade": "Grade", "city": "City", "phone": "Phone"})
|
| 58 |
+
text = ("ÖĞRENCİ KAYDI\n" if lang == "tr" else "STUDENT RECORD\n") + "\n".join(f"{lab[k]}: {v}" for k, v in f.items())
|
| 59 |
+
else:
|
| 60 |
+
f = {"seller": f"{rng.choice(LAST)} Ltd.", "total": f"{rng.randint(100, 9999)},00 TL", "date": f"{rng.randint(1, 28)}.0{rng.randint(1, 9)}.2026"}
|
| 61 |
+
has_phone = rng.random() < 0.5
|
| 62 |
+
if has_phone:
|
| 63 |
+
f["phone"] = f"0212 {rng.randint(100, 999)} {rng.randint(10, 99)} {rng.randint(10, 99)}"
|
| 64 |
+
signed = rng.random() < 0.5
|
| 65 |
+
lab = ({"seller": "Satıcı", "total": "Toplam", "date": "Tarih", "phone": "Telefon"} if lang == "tr"
|
| 66 |
+
else {"seller": "Seller", "total": "Total", "date": "Date", "phone": "Phone"})
|
| 67 |
+
text = ("FATURA\n" if lang == "tr" else "INVOICE\n") + "\n".join(f"{lab[k]}: {v}" for k, v in f.items())
|
| 68 |
+
text += ("\nİmza: " + ("var" if signed else "yok")) if lang == "tr" else ("\nSignature: " + ("present" if signed else "missing"))
|
| 69 |
+
f["signed"] = signed
|
| 70 |
+
return {"kind": kind, "fields": f, "has_phone": has_phone, "text": text, "lang": lang}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def T(lang, tr, en):
|
| 74 |
+
return tr if lang == "tr" else en
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def items(d, rng):
|
| 78 |
+
L = d["lang"]; out = []
|
| 79 |
+
kind_opts = {"student": T(L, "öğrenci kaydı", "student record"), "invoice": T(L, "fatura", "invoice"),
|
| 80 |
+
"receipt": T(L, "fiş", "receipt"), "bank": T(L, "banka dekontu", "bank statement")}
|
| 81 |
+
q_kind = [T(L, "Bu belge ne tür bir belge?", "What type of document is this?"),
|
| 82 |
+
T(L, "Belgenin türü nedir?", "Which kind of document is it?"),
|
| 83 |
+
T(L, "Bu hangi belge türüne girer?", "This document belongs to which category?")]
|
| 84 |
+
out.append({"id": "kind", "q": q_kind, "crit": kind_opts, "gold": d["kind"]})
|
| 85 |
+
yn = {"true": T(L, "evet", "yes"), "false": T(L, "hayır", "no")}
|
| 86 |
+
q_phone = [T(L, "Belgede bir telefon numarası var mı?", "Does the document contain a phone number?"),
|
| 87 |
+
T(L, "Bu belgede telefon bilgisi geçiyor mu?", "Is any phone information given in this document?"),
|
| 88 |
+
T(L, "Belgede iletişim için telefon yazılmış mı?", "Is a contact phone written in the document?")]
|
| 89 |
+
out.append({"id": "phone", "q": q_phone, "crit": yn, "gold": "true" if d["has_phone"] else "false",
|
| 90 |
+
"neg": T(L, "Belgede telefon numarası yok mu?", "Is it true that the document has no phone number?")})
|
| 91 |
+
if d["kind"] == "student":
|
| 92 |
+
city = d["fields"]["city"]; others = [c for c in CITY if c != city][:3]
|
| 93 |
+
opts = {c: c for c in [city] + others}
|
| 94 |
+
out.append({"id": "city", "q": [T(L, "Öğrenci hangi şehirde?", "Which city is the student in?"),
|
| 95 |
+
T(L, "Kayıttaki şehir hangisi?", "Which city is written in the record?"),
|
| 96 |
+
T(L, "Öğrencinin şehri nedir?", "What is the student's city?")], "crit": opts, "gold": city,
|
| 97 |
+
"lead": others[0]})
|
| 98 |
+
miss = T(L, "E-posta adresi", "Email address")
|
| 99 |
+
else:
|
| 100 |
+
signed = d["fields"]["signed"]
|
| 101 |
+
out.append({"id": "signed", "q": [T(L, "Fatura imzalı mı?", "Is the invoice signed?"),
|
| 102 |
+
T(L, "Faturada imza var mı?", "Does the invoice carry a signature?"),
|
| 103 |
+
T(L, "Bu fatura imzalanmış mı?", "Has this invoice been signed?")], "crit": yn,
|
| 104 |
+
"gold": "true" if signed else "false", "lead": "false" if signed else "true",
|
| 105 |
+
"neg": T(L, "Fatura imzasız mı?", "Is the invoice unsigned?")})
|
| 106 |
+
miss = T(L, "Vergi numarası", "Tax number")
|
| 107 |
+
# yanlış öncül: belgede olmayan alan; doğru cevap "belgede yok"
|
| 108 |
+
out.append({"id": "false_premise", "q": [T(L, f"{miss} nedir?", f"What is the {miss.lower()}?")],
|
| 109 |
+
"crit": {"a": "12345678", "b": "98765432", "c": "55501234", "absent": T(L, "belgede yazmıyor", "not stated in the document")},
|
| 110 |
+
"gold": "absent", "single": True})
|
| 111 |
+
# yanlış alarm: belgede OLAN alan "var mı?" (Jev'in canlı testte yaptığı hata: olanı "eksik" demek)
|
| 112 |
+
present = {"student": ("number", T(L, "Belgede okul numarası yazıyor mu?", "Is a school number written in the document?")),
|
| 113 |
+
"invoice": ("date", T(L, "Belgede tarih yazıyor mu?", "Is a date written in the document?"))}[d["kind"]]
|
| 114 |
+
out.append({"id": "false_alarm", "q": [present[1]], "crit": yn, "gold": "true", "single": True})
|
| 115 |
+
fake = T(L, "Bu belge noter onaylıdır.", "This document is notarized.")
|
| 116 |
+
out.append({"id": "fake_quote", "q": [T(L, f"Belgede şu cümle geçiyor mu: \"{fake}\"", f"Does the document contain this sentence: \"{fake}\"")],
|
| 117 |
+
"crit": yn, "gold": "false", "single": True})
|
| 118 |
+
return out
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def main():
|
| 122 |
+
ap = argparse.ArgumentParser()
|
| 123 |
+
ap.add_argument("--adapter", default="aubin12-plain"); ap.add_argument("--n_docs", type=int, default=30)
|
| 124 |
+
ap.add_argument("--work", default=""); ap.add_argument("--out", default="gray.json")
|
| 125 |
+
ap.add_argument("--fake", action="store_true") # modelsiz duman testi (rastgele karar verici)
|
| 126 |
+
ap.add_argument("--hard", action="store_true") # çeldiricili, uzun, eş anlamlı etiketli belgeler
|
| 127 |
+
a = ap.parse_args()
|
| 128 |
+
if a.fake:
|
| 129 |
+
class A: # noqa: N801
|
| 130 |
+
perms = 1
|
| 131 |
+
@staticmethod
|
| 132 |
+
def decide(state, qs):
|
| 133 |
+
ks = list(qs["x"]["criteria"]); r = random.Random(hash((state, qs["x"]["instructions"])) % 997)
|
| 134 |
+
p = [r.random() for _ in ks]; s = sum(p)
|
| 135 |
+
return {"x": {"answer": ks[p.index(max(p))], "probabilities": {k: v / s for k, v in zip(ks, p)}}}
|
| 136 |
+
else:
|
| 137 |
+
from kev_llm import resolve_adapter
|
| 138 |
+
from aubin.core import Aubin
|
| 139 |
+
A = Aubin(resolve_adapter(a.adapter), think_margin=0.0)
|
| 140 |
+
rng = random.Random(0)
|
| 141 |
+
docs = [doc(rng, "tr" if i % 2 == 0 else "en") for i in range(a.n_docs)]
|
| 142 |
+
if a.hard:
|
| 143 |
+
docs = [harden(d, rng) for d in docs]
|
| 144 |
+
R = {"adapter": a.adapter, "n_docs": len(docs), "modes": {}}
|
| 145 |
+
t0 = time.time()
|
| 146 |
+
for perms in (1, 2):
|
| 147 |
+
A.perms = perms
|
| 148 |
+
def ask(d, q, crit):
|
| 149 |
+
r = A.decide(d["text"], {"x": {"type": "choice", "instructions": q, "criteria": crit}})["x"]
|
| 150 |
+
return r["answer"], r["probabilities"]
|
| 151 |
+
c = {k: [0, 0] for k in ("accuracy", "repeat", "order", "phrasing", "leading", "x_notx", "false_premise", "fake_quote", "false_alarm")}
|
| 152 |
+
dmax = {"repeat": 0.0, "order": 0.0}
|
| 153 |
+
for d in docs:
|
| 154 |
+
for it in items(d, rng):
|
| 155 |
+
ans, pr = ask(d, it["q"][0], it["crit"])
|
| 156 |
+
c["accuracy"][0] += ans == it["gold"]; c["accuracy"][1] += 1
|
| 157 |
+
if it.get("single"):
|
| 158 |
+
c[it["id"]][0] += ans != it["gold"]; c[it["id"]][1] += 1
|
| 159 |
+
continue
|
| 160 |
+
a2, p2 = ask(d, it["q"][0], it["crit"])
|
| 161 |
+
c["repeat"][0] += a2 != ans; c["repeat"][1] += 1
|
| 162 |
+
dmax["repeat"] = max(dmax["repeat"], max(abs(pr[k] - p2[k]) for k in pr))
|
| 163 |
+
rev = dict(reversed(list(it["crit"].items())))
|
| 164 |
+
a3, p3 = ask(d, it["q"][0], rev)
|
| 165 |
+
c["order"][0] += a3 != ans; c["order"][1] += 1
|
| 166 |
+
dmax["order"] = max(dmax["order"], max(abs(pr[k] - p3[k]) for k in pr))
|
| 167 |
+
ph = {ask(d, q, it["crit"])[0] for q in it["q"]}
|
| 168 |
+
c["phrasing"][0] += len(ph) > 1; c["phrasing"][1] += 1
|
| 169 |
+
if "lead" in it:
|
| 170 |
+
lead = T(d["lang"], f" Bence cevap kesinlikle '{it['crit'][it['lead']]}', değil mi?",
|
| 171 |
+
f" I'm quite sure the answer is '{it['crit'][it['lead']]}', right?")
|
| 172 |
+
a4, _ = ask(d, it["q"][0] + lead, it["crit"])
|
| 173 |
+
c["leading"][0] += (a4 == it["lead"] and it["lead"] != it["gold"]); c["leading"][1] += 1
|
| 174 |
+
if "neg" in it:
|
| 175 |
+
a5, _ = ask(d, it["neg"], it["crit"])
|
| 176 |
+
c["x_notx"][0] += a5 == ans; c["x_notx"][1] += 1 # "X?" ve "değil-X?" aynı cevabı alırsa çelişki
|
| 177 |
+
R["modes"][f"perms={perms}"] = {k: f"{v[0]}/{v[1]}" for k, v in c.items()} | {
|
| 178 |
+
"accuracy_rate": round(c["accuracy"][0] / max(1, c["accuracy"][1]), 4),
|
| 179 |
+
"max_prob_diff_repeat": round(dmax["repeat"], 3), "max_prob_diff_order": round(dmax["order"], 3)}
|
| 180 |
+
print(perms, json.dumps(R["modes"][f"perms={perms}"], ensure_ascii=False), flush=True)
|
| 181 |
+
R["minutes"] = round((time.time() - t0) / 60, 1)
|
| 182 |
+
json.dump(R, open(a.out, "w", encoding="utf-8"), indent=1, ensure_ascii=False)
|
| 183 |
+
print("SONUC", json.dumps(R, ensure_ascii=False), flush=True)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
main()
|
code/kev_llm.py
CHANGED
|
@@ -189,7 +189,8 @@ def resolve_adapter(path):
|
|
| 189 |
if path.startswith("hf:"): # herkese açık HF deposundaki adaptör (hesaplar arası paylaşım)
|
| 190 |
from huggingface_hub import snapshot_download
|
| 191 |
repo, _, sub = path[3:].partition("//")
|
| 192 |
-
|
|
|
|
| 193 |
return os.path.join(d, sub) if sub else d
|
| 194 |
base = os.path.basename(path.rstrip("/"))
|
| 195 |
hits = [os.path.dirname(h) for h in glob.glob("/kaggle/input/**/adapter_config.json", recursive=True)]
|
|
@@ -200,7 +201,7 @@ def resolve_adapter(path):
|
|
| 200 |
|
| 201 |
|
| 202 |
def train_lora(S, tr, steps, lr, bs, out_dir, seed=0, init_adapter="", mine=0, mine_thr=0.9, dev=None, eval_every=100,
|
| 203 |
-
teacher=None, alpha=0.5, data_value=False):
|
| 204 |
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 205 |
# 4-bit olmayan dev tablolar (Gemma-4 E2B/E4B katman-başı gömmeleri ~2-3B param) fp32'ye çevrilirse T4 taşar →
|
| 206 |
# o durumda hafif hazırlık: tüm ağırlıklar donuk, gradyan kontrol noktası + girdi gradyanı
|
|
@@ -265,8 +266,28 @@ def train_lora(S, tr, steps, lr, bs, out_dir, seed=0, init_adapter="", mine=0, m
|
|
| 265 |
pool = [x for x in pool for _ in range(max(1, round(w.get(x["src"], 1.0) * 2)))]
|
| 266 |
srt = sorted(pool, key=plen); buckets = [srt[i:i + B] for i in range(0, len(srt), B)]
|
| 267 |
print({"data_value_weights": {s: round(v, 2) for s, v in sorted(w.items(), key=lambda kv: -kv[1])}, "pool": len(pool)}, flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
t0 = time.time(); S.m.train(); ntok = 0
|
| 269 |
-
for step in range(steps):
|
| 270 |
bk = buckets[rng.randrange(len(buckets))]
|
| 271 |
batch = [bk[rng.randrange(len(bk))] for _ in range(bs)]
|
| 272 |
perms = []
|
|
@@ -296,6 +317,8 @@ def train_lora(S, tr, steps, lr, bs, out_dir, seed=0, init_adapter="", mine=0, m
|
|
| 296 |
if acc > best[0]:
|
| 297 |
from peft import get_peft_model_state_dict
|
| 298 |
best = (acc, step + 1, {k: v.detach().cpu().clone() for k, v in get_peft_model_state_dict(S.m).items()})
|
|
|
|
|
|
|
| 299 |
S.m.eval()
|
| 300 |
if dev and best[2] is not None:
|
| 301 |
from peft import set_peft_model_state_dict
|
|
@@ -327,7 +350,8 @@ def main():
|
|
| 327 |
ap.add_argument("--think_samples", type=int, default=1); ap.add_argument("--think_temp", type=float, default=0.7)
|
| 328 |
ap.add_argument("--label_train", type=int, default=0); ap.add_argument("--teacher", default=""); ap.add_argument("--alpha", type=float, default=0.5)
|
| 329 |
ap.add_argument("--dev_src", default="dev", choices=["dev", "cal"]); ap.add_argument("--data_value", action="store_true")
|
| 330 |
-
ap.add_argument("--train_only", action="store_true")
|
|
|
|
| 331 |
a = ap.parse_args()
|
| 332 |
a.init_adapter = resolve_adapter(a.init_adapter)
|
| 333 |
K = kevdata.load(a.work)
|
|
@@ -399,7 +423,7 @@ def main():
|
|
| 399 |
S.m = PeftModel.from_pretrained(S.m, a.init_adapter).eval()
|
| 400 |
pool = [x for x in items(K["kev_train"]) if len(x["keys"]) <= 26]; random.Random(11).shuffle(pool)
|
| 401 |
lab, t0 = {}, time.time()
|
| 402 |
-
for i, it in enumerate(pool[: a.label_train]):
|
| 403 |
lab[it["key"]] = [round(float(v), 4) for v in S.score(it)]
|
| 404 |
if i % 200 == 0:
|
| 405 |
print({"label": i, "min": round((time.time() - t0) / 60, 1)}, flush=True)
|
|
@@ -420,7 +444,7 @@ def main():
|
|
| 420 |
devs = items(K["kev_dev"]); random.Random(5).shuffle(devs)
|
| 421 |
train_lora(S, items(K["kev_train"]), a.train, a.lr, a.bs, a.adapter, seed=a.seed, init_adapter=a.init_adapter, mine=a.mine,
|
| 422 |
dev=[d for d in devs if len(d["keys"]) <= 26][: a.dev_n] if a.dev_n else None, eval_every=a.eval_every,
|
| 423 |
-
teacher=teach, alpha=a.alpha, data_value=a.data_value)
|
| 424 |
R["best_dev"] = getattr(S, "best_dev", None)
|
| 425 |
R["lora"] = {"steps": a.train, "bs": a.bs, "lr": a.lr, "r": 16, "seed": a.seed}
|
| 426 |
if a.train_only: # ölçüm ayrı, temiz süreçte (eğitim sonrası parçalı bellek düşünme üretiminde OOM veriyor)
|
|
|
|
| 189 |
if path.startswith("hf:"): # herkese açık HF deposundaki adaptör (hesaplar arası paylaşım)
|
| 190 |
from huggingface_hub import snapshot_download
|
| 191 |
repo, _, sub = path[3:].partition("//")
|
| 192 |
+
pre = sub + "/" if sub else ""
|
| 193 |
+
d = snapshot_download(repo, allow_patterns=[pre + "adapter_*", pre + "aubin.json"]) # aubin.json: taban + sıcaklık
|
| 194 |
return os.path.join(d, sub) if sub else d
|
| 195 |
base = os.path.basename(path.rstrip("/"))
|
| 196 |
hits = [os.path.dirname(h) for h in glob.glob("/kaggle/input/**/adapter_config.json", recursive=True)]
|
|
|
|
| 201 |
|
| 202 |
|
| 203 |
def train_lora(S, tr, steps, lr, bs, out_dir, seed=0, init_adapter="", mine=0, mine_thr=0.9, dev=None, eval_every=100,
|
| 204 |
+
teacher=None, alpha=0.5, data_value=False, save_every=0, resume=""):
|
| 205 |
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 206 |
# 4-bit olmayan dev tablolar (Gemma-4 E2B/E4B katman-başı gömmeleri ~2-3B param) fp32'ye çevrilirse T4 taşar →
|
| 207 |
# o durumda hafif hazırlık: tüm ağırlıklar donuk, gradyan kontrol noktası + girdi gradyanı
|
|
|
|
| 266 |
pool = [x for x in pool for _ in range(max(1, round(w.get(x["src"], 1.0) * 2)))]
|
| 267 |
srt = sorted(pool, key=plen); buckets = [srt[i:i + B] for i in range(0, len(srt), B)]
|
| 268 |
print({"data_value_weights": {s: round(v, 2) for s, v in sorted(w.items(), key=lambda kv: -kv[1])}, "pool": len(pool)}, flush=True)
|
| 269 |
+
start = 0
|
| 270 |
+
if resume and os.path.exists(os.path.join(resume, "state.json")): # oturum sınırı kalkar: önceki oturumun kontrol noktasından devam
|
| 271 |
+
stt = json.load(open(os.path.join(resume, "state.json")))
|
| 272 |
+
start = int(stt["step"])
|
| 273 |
+
opt.load_state_dict(torch.load(os.path.join(resume, "opt.pt"), map_location="cpu"))
|
| 274 |
+
if os.path.exists(os.path.join(resume, "best.pt")):
|
| 275 |
+
best = (float(stt["best_acc"]), int(stt["best_step"]), torch.load(os.path.join(resume, "best.pt"), map_location="cpu"))
|
| 276 |
+
rng = random.Random(seed * 100003 + start)
|
| 277 |
+
print({"resume_from_step": start, "best": stt.get("best_acc")}, flush=True)
|
| 278 |
+
|
| 279 |
+
def checkpoint(step_done):
|
| 280 |
+
ck = (out_dir or "lora_out") + "_ckpt"
|
| 281 |
+
os.makedirs(ck, exist_ok=True)
|
| 282 |
+
S.m.save_pretrained(os.path.join(ck, "adapter"))
|
| 283 |
+
torch.save(opt.state_dict(), os.path.join(ck, "opt.pt"))
|
| 284 |
+
if best[2] is not None:
|
| 285 |
+
torch.save(best[2], os.path.join(ck, "best.pt"))
|
| 286 |
+
json.dump({"step": step_done, "best_acc": best[0], "best_step": best[1]}, open(os.path.join(ck, "state.json"), "w"))
|
| 287 |
+
print({"checkpoint": step_done, "dir": ck}, flush=True)
|
| 288 |
+
|
| 289 |
t0 = time.time(); S.m.train(); ntok = 0
|
| 290 |
+
for step in range(start, steps):
|
| 291 |
bk = buckets[rng.randrange(len(buckets))]
|
| 292 |
batch = [bk[rng.randrange(len(bk))] for _ in range(bs)]
|
| 293 |
perms = []
|
|
|
|
| 317 |
if acc > best[0]:
|
| 318 |
from peft import get_peft_model_state_dict
|
| 319 |
best = (acc, step + 1, {k: v.detach().cpu().clone() for k, v in get_peft_model_state_dict(S.m).items()})
|
| 320 |
+
if save_every and (step + 1) % save_every == 0 and step + 1 < steps:
|
| 321 |
+
checkpoint(step + 1)
|
| 322 |
S.m.eval()
|
| 323 |
if dev and best[2] is not None:
|
| 324 |
from peft import set_peft_model_state_dict
|
|
|
|
| 350 |
ap.add_argument("--think_samples", type=int, default=1); ap.add_argument("--think_temp", type=float, default=0.7)
|
| 351 |
ap.add_argument("--label_train", type=int, default=0); ap.add_argument("--teacher", default=""); ap.add_argument("--alpha", type=float, default=0.5)
|
| 352 |
ap.add_argument("--dev_src", default="dev", choices=["dev", "cal"]); ap.add_argument("--data_value", action="store_true")
|
| 353 |
+
ap.add_argument("--train_only", action="store_true"); ap.add_argument("--label_offset", type=int, default=0)
|
| 354 |
+
ap.add_argument("--save_every", type=int, default=0); ap.add_argument("--resume", default="")
|
| 355 |
a = ap.parse_args()
|
| 356 |
a.init_adapter = resolve_adapter(a.init_adapter)
|
| 357 |
K = kevdata.load(a.work)
|
|
|
|
| 423 |
S.m = PeftModel.from_pretrained(S.m, a.init_adapter).eval()
|
| 424 |
pool = [x for x in items(K["kev_train"]) if len(x["keys"]) <= 26]; random.Random(11).shuffle(pool)
|
| 425 |
lab, t0 = {}, time.time()
|
| 426 |
+
for i, it in enumerate(pool[a.label_offset: a.label_offset + a.label_train]): # aralık: hesaplar arası bölüşüm
|
| 427 |
lab[it["key"]] = [round(float(v), 4) for v in S.score(it)]
|
| 428 |
if i % 200 == 0:
|
| 429 |
print({"label": i, "min": round((time.time() - t0) / 60, 1)}, flush=True)
|
|
|
|
| 444 |
devs = items(K["kev_dev"]); random.Random(5).shuffle(devs)
|
| 445 |
train_lora(S, items(K["kev_train"]), a.train, a.lr, a.bs, a.adapter, seed=a.seed, init_adapter=a.init_adapter, mine=a.mine,
|
| 446 |
dev=[d for d in devs if len(d["keys"]) <= 26][: a.dev_n] if a.dev_n else None, eval_every=a.eval_every,
|
| 447 |
+
teacher=teach, alpha=a.alpha, data_value=a.data_value, save_every=a.save_every, resume=a.resume)
|
| 448 |
R["best_dev"] = getattr(S, "best_dev", None)
|
| 449 |
R["lora"] = {"steps": a.train, "bs": a.bs, "lr": a.lr, "r": 16, "seed": a.seed}
|
| 450 |
if a.train_only: # ölçüm ayrı, temiz süreçte (eğitim sonrası parçalı bellek düşünme üretiminde OOM veriyor)
|
code/loop_bench.py
CHANGED
|
@@ -22,12 +22,15 @@ def main():
|
|
| 22 |
ap.add_argument("--n", type=int, default=5); ap.add_argument("--target", type=float, default=0.7)
|
| 23 |
ap.add_argument("--gen_bs", type=int, default=16); ap.add_argument("--max_new", type=int, default=320)
|
| 24 |
ap.add_argument("--work", default=""); ap.add_argument("--out", default="loop.json")
|
|
|
|
| 25 |
a = ap.parse_args()
|
| 26 |
from datasets import load_dataset
|
| 27 |
from aubin.core import Aubin
|
| 28 |
from aubin.loop import AubinLoop, GemmaGenerator, last_number, SOLVE
|
|
|
|
|
|
|
| 29 |
ds = list(load_dataset("openai/gsm8k", "main", split="test"))
|
| 30 |
-
random.Random(0).shuffle(ds); ds = ds[: a.n_problems]
|
| 31 |
gold = [last_number(x["answer"].split("####")[-1]) for x in ds]
|
| 32 |
A = Aubin(a.adapter, four_bit=True, think_margin=0.0)
|
| 33 |
G = GemmaGenerator(A, max_new=a.max_new, temperature=0.7)
|
|
@@ -44,7 +47,8 @@ def main():
|
|
| 44 |
if (i // a.gen_bs) % 10 == 0:
|
| 45 |
print({"sampled": i + len(chunk), "of": len(flat), "min": round((time.time() - t0) / 60, 1)}, flush=True)
|
| 46 |
gen_min = (time.time() - t0) / 60
|
| 47 |
-
R = {"adapter": a.adapter, "n_problems": len(ds), "n": a.n, "target": a.target, "gen_minutes": round(gen_min, 1),
|
|
|
|
| 48 |
ok = lambda k, v: v is not None and v == gold[k]
|
| 49 |
acc = {"greedy": [ok(k, last_number(g)) for k, g in enumerate(greedy)]}
|
| 50 |
maj, orc = [], []
|
|
|
|
| 22 |
ap.add_argument("--n", type=int, default=5); ap.add_argument("--target", type=float, default=0.7)
|
| 23 |
ap.add_argument("--gen_bs", type=int, default=16); ap.add_argument("--max_new", type=int, default=320)
|
| 24 |
ap.add_argument("--work", default=""); ap.add_argument("--out", default="loop.json")
|
| 25 |
+
ap.add_argument("--offset", type=int, default=0) # ikinci GPU aynı karışık sıradan sonraki soruları çözer
|
| 26 |
a = ap.parse_args()
|
| 27 |
from datasets import load_dataset
|
| 28 |
from aubin.core import Aubin
|
| 29 |
from aubin.loop import AubinLoop, GemmaGenerator, last_number, SOLVE
|
| 30 |
+
from kev_llm import resolve_adapter
|
| 31 |
+
a.adapter = resolve_adapter(a.adapter) # gizli Kaggle veri seti / kernel çıktısı adıyla da bulunur
|
| 32 |
ds = list(load_dataset("openai/gsm8k", "main", split="test"))
|
| 33 |
+
random.Random(0).shuffle(ds); ds = ds[a.offset: a.offset + a.n_problems]
|
| 34 |
gold = [last_number(x["answer"].split("####")[-1]) for x in ds]
|
| 35 |
A = Aubin(a.adapter, four_bit=True, think_margin=0.0)
|
| 36 |
G = GemmaGenerator(A, max_new=a.max_new, temperature=0.7)
|
|
|
|
| 47 |
if (i // a.gen_bs) % 10 == 0:
|
| 48 |
print({"sampled": i + len(chunk), "of": len(flat), "min": round((time.time() - t0) / 60, 1)}, flush=True)
|
| 49 |
gen_min = (time.time() - t0) / 60
|
| 50 |
+
R = {"adapter": a.adapter, "n_problems": len(ds), "offset": a.offset, "n": a.n, "target": a.target, "gen_minutes": round(gen_min, 1),
|
| 51 |
+
"rows": {}}
|
| 52 |
ok = lambda k, v: v is not None and v == gold[k]
|
| 53 |
acc = {"greedy": [ok(k, last_number(g)) for k, g in enumerate(greedy)]}
|
| 54 |
maj, orc = [], []
|
test_clean_metrics.json
CHANGED
|
@@ -78,5 +78,46 @@
|
|
| 78 |
"ece15": 0.0281,
|
| 79 |
"nll": 0.7185
|
| 80 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
}
|
| 82 |
}
|
|
|
|
| 78 |
"ece15": 0.0281,
|
| 79 |
"nll": 0.7185
|
| 80 |
}
|
| 81 |
+
},
|
| 82 |
+
"AUBIN Duo-SC (31B self-consistent think + 12B full precision)": {
|
| 83 |
+
"kev_transfer_test": {
|
| 84 |
+
"n": 656,
|
| 85 |
+
"accuracy": 0.8948,
|
| 86 |
+
"brier": 0.1681,
|
| 87 |
+
"ece15": 0.046,
|
| 88 |
+
"nll": 0.3486
|
| 89 |
+
},
|
| 90 |
+
"kev_test": {
|
| 91 |
+
"n": 1200,
|
| 92 |
+
"accuracy": 0.8425,
|
| 93 |
+
"brier": 0.2391,
|
| 94 |
+
"ece15": 0.035,
|
| 95 |
+
"nll": 0.7191
|
| 96 |
+
}
|
| 97 |
+
},
|
| 98 |
+
"AUBIN Trio (31B-SC + 12B full precision + Phi-4)": {
|
| 99 |
+
"kev_transfer_test": {
|
| 100 |
+
"n": 656,
|
| 101 |
+
"accuracy": 0.8887,
|
| 102 |
+
"brier": 0.169,
|
| 103 |
+
"ece15": 0.0384,
|
| 104 |
+
"nll": 0.3472
|
| 105 |
+
},
|
| 106 |
+
"kev_test": {
|
| 107 |
+
"n": 1200,
|
| 108 |
+
"accuracy": 0.8508,
|
| 109 |
+
"brier": 0.2369,
|
| 110 |
+
"ece15": 0.0223,
|
| 111 |
+
"nll": 0.6749
|
| 112 |
+
}
|
| 113 |
+
},
|
| 114 |
+
"AUBIN Quad (31B-SC + 12B full precision + Phi-4 + Mistral-Small)": {
|
| 115 |
+
"kev_transfer_test": {
|
| 116 |
+
"n": 656,
|
| 117 |
+
"accuracy": 0.8857,
|
| 118 |
+
"brier": 0.1678,
|
| 119 |
+
"ece15": 0.053,
|
| 120 |
+
"nll": 0.3481
|
| 121 |
+
}
|
| 122 |
}
|
| 123 |
}
|