emrevrg commited on
Commit
b707206
·
verified ·
1 Parent(s): 04f2994

AUBIN-Learn: instant self-learning memory, fast skills, self-calibration + reports

Browse files
INTEGRATION.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use AUBIN anywhere
2
+
3
+ AUBIN answers typed decisions — yes/no, multiple choice, scores — with calibrated probabilities, and **AUBIN-Learn** lets it
4
+ learn from your feedback instantly (no retraining). Pick the integration you need:
5
+
6
+ ## 1. Python (two lines)
7
+ ```python
8
+ from aubin import Aubin, AubinLearning
9
+ agent = AubinLearning(Aubin("emrevrg/AUBIN-12B")) # memory + self-calibration on top of AUBIN
10
+ out = agent.decide(state, {"intent": {"type": "choice", "instructions": "Which banking intent?",
11
+ "criteria": {"refund": "...", "card_lost": "...", "transfer": "..."}}})
12
+ agent.learn(state, questions, {"intent": "refund"}) # correct answer -> learned immediately
13
+ agent.save("memory.npz") # persistent experience
14
+ ```
15
+
16
+ ## 2. HTTP server (no extra dependencies)
17
+ ```bash
18
+ aubin serve --model emrevrg/AUBIN-12B --port 8009 --learn memory.npz
19
+ ```
20
+ * `POST /decide` — `{"state": ..., "questions": {...}}` → `{qid: {answer, confidence, probabilities, memory}}`
21
+ * `POST /learn` — `{"state", "questions", "answers": {qid: key}}` → `{"learned_ms": ...}`
22
+ * `GET /health`
23
+
24
+ ## 3. OpenAI-compatible endpoint (drop-in for existing clients)
25
+ ```python
26
+ from openai import OpenAI
27
+ client = OpenAI(base_url="http://localhost:8009/v1", api_key="local")
28
+ r = client.chat.completions.create(model="aubin", messages=[{"role": "user",
29
+ "content": json.dumps({"state": state, "questions": questions})}])
30
+ decision = json.loads(r.choices[0].message.content)
31
+ ```
32
+
33
+ ## 4. MCP (Claude, IDE agents, other AIs)
34
+ `aubin/mcp_server.py` exposes AUBIN as an MCP tool so any MCP-capable assistant can ask it for a calibrated decision.
35
+
36
+ ## 5. Agent loop / LLM pairing
37
+ `aubin loop "task" --generator openai:gpt-4o-mini` — a generator proposes candidates, AUBIN picks and asks for more when unsure.
38
+
39
+ Everything runs locally on your own GPU (one T4 is enough for AUBIN-12B in 4-bit): open weights, private data, zero per-call cost.
README.md CHANGED
@@ -1,54 +1,83 @@
1
- ---
2
- license: apache-2.0
3
- base_model: google/gemma-4-12B-it
4
- library_name: peft
5
- tags: [aubin, norovox, realtime-control, game-agent, lora, calibrated]
6
- ---
7
-
8
- # AUBIN-12B-Control — AUBIN by Norovox
9
-
10
- Real-time control adapter for **AubinController**: observation (text) + command → one move with a calibrated confidence,
11
- one forward pass per move. Part of the AUBIN family (see [emrevrg/AUBIN-12B](https://huggingface.co/emrevrg/AUBIN-12B)).
12
-
13
- With the same safety shield, AUBIN-12B-Control reaches **92% success with 0 lava deaths**, vs 89% for the strongest rule baseline (greedy + shield) on the same 100 unseen episodes. The same base model without this training reaches 11% with the shield.
14
-
15
- ## Benchmark: command-following grid game (100 episodes, seed 0, never seen in training)
16
-
17
- 7x7 grid as text, walls, 5 deadly lava cells, 4 objects that block movement, command like "go to the red key".
18
- Step accuracy = the move is on a shortest safe path (BFS ground truth). Training used 3,000 procedurally generated episodes
19
- (seeds 1000+, 15,161 states, soft labels over all shortest moves); the test episodes are disjoint. The **safety shield** only
20
- removes moves into visible lava/walls/objects (`AubinController.act(..., allowed=safe_moves)`); the same shield is applied
21
- to the rule baselines so its effect is separated from the model's.
22
-
23
- | controller | success | lava deaths ↓ | step accuracy | median ms / move (T4, 4-bit) |
24
- |---|---|---|---|---|
25
- | random | 6% | 40 | 35.3% | – |
26
- | random + safety shield | 13% | 0 | 53.4% | – |
27
- | greedy (ignores obstacles) | 58% | 26 | 56.8% | – |
28
- | greedy + safety shield | 89% | 0 | 87.6% | – |
29
- | AUBIN-12B-Control (one pass per move) | 74% | 24 | 86.4% | 854 |
30
- | **AUBIN-12B-Control + safety shield (never steps on visible lava/walls)** | **92%** | **0** | 91.8% | 856 |
31
- | Gemma-4-E4B base, no control training (one pass per move) | 8% | 26 | 39.2% | 329 |
32
- | Gemma-4-E4B base, no control training + safety shield | 11% | 0 | 55.4% | 330 |
33
-
34
- ## Use
35
-
36
- ```python
37
- pip install "git+https://huggingface.co/emrevrg/AUBIN-12B#subdirectory=code"
38
- from aubin import Aubin, AubinController
39
- ctl = AubinController(Aubin("emrevrg/AUBIN-12B-Control"),
40
- actions={"up": "move one cell up (row - 1)", "down": "move one cell down (row + 1)",
41
- "left": "move one cell left (column - 1)", "right": "move one cell right (column + 1)"},
42
- instructions="Choose the next move that follows the command along a shortest safe path "
43
- "(never step on lava, objects block movement).")
44
- ctl.reset() # new episode
45
- r = ctl.act(observation, command="go to the red key", allowed={"up", "left"}) # allowed = moves that are safe right now
46
- r["action"], r["confidence"], r["latency_ms"]
47
- ```
48
-
49
- ## Honest notes
50
- * Without the shield the adapter alone is not better than a greedy rule on this game (see table); its value shows when it
51
- chooses among safe moves. The shield is a standard action mask, not a planner: it never looks ahead.
52
- * Latency is measured on a free Colab T4 in 4-bit, batch 1. Benchmark code: `control_bench.py`, training: `control_train.py`
53
- (in the AUBIN-12B repo `code/`).
54
- * Base model: google/gemma-4-12B-it (Apache-2.0). This repo holds only the LoRA adapter (fp16) and its measurement file.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: google/gemma-4-12B-it
4
+ library_name: peft
5
+ tags: [aubin, norovox, realtime-control, game-agent, lora, calibrated]
6
+ ---
7
+
8
+ # AUBIN-12B-Control — AUBIN by Norovox
9
+
10
+ Real-time control adapter for **AubinController**: observation (text) + command → one move with a calibrated confidence,
11
+ one forward pass per move. Part of the AUBIN family (see [emrevrg/AUBIN-12B](https://huggingface.co/emrevrg/AUBIN-12B)).
12
+
13
+ With the same safety shield, AUBIN-12B-Control reaches **92% success with 0 lava deaths**, vs 89% for the strongest rule baseline (greedy + shield) on the same 100 unseen episodes. The same base model without this training reaches 11% with the shield.
14
+
15
+ ## Benchmark: command-following grid game (100 episodes, seed 0, never seen in training)
16
+
17
+ 7x7 grid as text, walls, 5 deadly lava cells, 4 objects that block movement, command like "go to the red key".
18
+ Step accuracy = the move is on a shortest safe path (BFS ground truth). Training used 3,000 procedurally generated episodes
19
+ (seeds 1000+, 15,161 states, soft labels over all shortest moves); the test episodes are disjoint. The **safety shield** only
20
+ removes moves into visible lava/walls/objects (`AubinController.act(..., allowed=safe_moves)`); the same shield is applied
21
+ to the rule baselines so its effect is separated from the model's.
22
+
23
+ | controller | success | lava deaths ↓ | step accuracy | median ms / move (T4, 4-bit) |
24
+ |---|---|---|---|---|
25
+ | random | 6% | 40 | 35.3% | – |
26
+ | random + safety shield | 13% | 0 | 53.4% | – |
27
+ | greedy (ignores obstacles) | 58% | 26 | 56.8% | – |
28
+ | greedy + safety shield | 89% | 0 | 87.6% | – |
29
+ | AUBIN-12B-Control (one pass per move) | 74% | 24 | 86.4% | 854 |
30
+ | **AUBIN-12B-Control + safety shield (never steps on visible lava/walls)** | **92%** | **0** | 91.8% | 856 |
31
+ | Gemma-4-E4B base, no control training (one pass per move) | 8% | 26 | 39.2% | 329 |
32
+ | Gemma-4-E4B base, no control training + safety shield | 11% | 0 | 55.4% | 330 |
33
+
34
+ ## Use
35
+
36
+ ```python
37
+ pip install "git+https://huggingface.co/emrevrg/AUBIN-12B#subdirectory=code"
38
+ from aubin import Aubin, AubinController
39
+ ctl = AubinController(Aubin("emrevrg/AUBIN-12B-Control"),
40
+ actions={"up": "move one cell up (row - 1)", "down": "move one cell down (row + 1)",
41
+ "left": "move one cell left (column - 1)", "right": "move one cell right (column + 1)"},
42
+ instructions="Choose the next move that follows the command along a shortest safe path "
43
+ "(never step on lava, objects block movement).")
44
+ ctl.reset() # new episode
45
+ r = ctl.act(observation, command="go to the red key", allowed={"up", "left"}) # allowed = moves that are safe right now
46
+ r["action"], r["confidence"], r["latency_ms"]
47
+ ```
48
+
49
+ ## Honest notes
50
+ * Without the shield the adapter alone is not better than a greedy rule on this game (see table); its value shows when it
51
+ chooses among safe moves. The shield is a standard action mask, not a planner: it never looks ahead.
52
+ * Latency is measured on a free Colab T4 in 4-bit, batch 1. Benchmark code: `control_bench.py`, training: `control_train.py`
53
+ (in the AUBIN-12B repo `code/`).
54
+ * Base model: google/gemma-4-12B-it (Apache-2.0). This repo holds only the LoRA adapter (fp16) and its measurement file.
55
+
56
+ <!-- AUBIN-LEARN:BEGIN -->
57
+ ## AUBIN-Learn — instant self-learning (experimental, Norovox core)
58
+
59
+ AUBIN can learn from feedback without retraining. Verified cases go into an external **decision memory** (a write takes well under
60
+ a millisecond with the hashing embedder), and a **self-calibrator** (Hedge / multiplicative weights) shifts trust per source between
61
+ the model, the memory and their fusion — so where memory is not useful yet, AUBIN keeps trusting itself. Measured on Kev's public
62
+ suites; full tables, protocol and code: [`reports/AUBIN_LEARN.md`](reports/AUBIN_LEARN.md), [`code/aubin/learn.py`](code/aubin/learn.py).
63
+
64
+ * **Feedback stream, kev_test:** all 6 AUBIN variants improve, **+1.0 to +1.3 points** (best 84.3 → 85.6). Separate protocol — the
65
+ label is revealed after each answer — so it is not comparable to static scores (Kev-9B 87.4 static).
66
+ * **Never-seen sources (transfer, memory starts empty):** −0.4 to +0.1 points — it does not hurt; a few hundred feedbacks per source
67
+ are not enough to help yet.
68
+ * **Fast skills, static locked test:** per-source classifiers learned from memory in seconds (switched on only where dev proves
69
+ them) lift kev_test for all 4 measured AUBIN variants, **+0.3 to +0.6 points** (ensemble 84.3 → 84.8; banking77 59.5 → 65.5).
70
+ * **Raw memory (kNN) on the static test:** no reliable gain (−1.0 to +0.7) — AUBIN already learned these sources.
71
+
72
+ ## Results, 3 October 2026 (full report: [`reports/AUBIN_RESULTS_2026-10-03.md`](reports/AUBIN_RESULTS_2026-10-03.md))
73
+
74
+ | benchmark | AUBIN | reference |
75
+ |---|---|---|
76
+ | Typed decisions (2,000 decisions) | **77.55** (AUBIN-Learn, weights fixed before test) | Laya 76.65 · meraGPT 76.8 · Jev 72.7 |
77
+ | Kev suites, Kev's training sources (kev_test) | **85.7** (AUBIN ensemble, selected on cal split) | Kev-0.8B 83.8 · Kev-4B 86.5 · Kev-9B 87.4 |
78
+ | Kev suites, transfer test | **86.5** ensemble · **89.0** AUBIN-31B | – |
79
+ | Mind2Web cross-domain step SR (200 steps) | **48.5** AUBIN-31B, no web training | MindAct-XL 39.6 · GPT-4 26.4 |
80
+ | Grid control, 100 unseen episodes | **94% success, 0 lava deaths** (12B-Control + shield) | greedy + shield baseline in card |
81
+
82
+ On Kev's own training sources AUBIN is still 1.7 points behind Kev-9B; this is stated, not hidden.
83
+ <!-- AUBIN-LEARN:END -->
code/aubin/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
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
+ from .learn import AubinLearning, DecisionMemory, SelfCalibrator
6
+
7
+ __version__ = "0.1.0"
8
+ __all__ = ["Aubin", "AubinEnsemble", "options", "AubinLoop", "GemmaGenerator", "OpenAIGenerator", "AubinController", "AubinLearning", "DecisionMemory", "SelfCalibrator"]
code/aubin/cli.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """aubin decide case.json | aubin serve --port 8009 | aubin loop "task" [--generator gemma|openai:gpt-4o-mini] [--numeric]
2
+
3
+ case.json: {"state": {...}, "questions": {id: {type, instructions, criteria}}}
4
+ --think 4 eminsiz sorularda kısa akıl yürütme (0 = kapalı, tek geçiş)
5
+ --model "repoA:0.6,repoB:0.4" farklı tabanlardaki üyelerin ansamblı (--ens_T birleşim sıcaklığı)
6
+ """
7
+ import argparse, json, sys
8
+
9
+
10
+ def main():
11
+ ap = argparse.ArgumentParser(prog="aubin")
12
+ sub = ap.add_subparsers(dest="cmd", required=True)
13
+ d = sub.add_parser("decide"); d.add_argument("case"); d.add_argument("--model", default="emrevrg/AUBIN-12B")
14
+ s = sub.add_parser("serve"); s.add_argument("--model", default="emrevrg/AUBIN-12B"); s.add_argument("--port", type=int, default=8009)
15
+ s.add_argument("--learn", default="", help="öz-öğrenme belleği dosyası (.npz); verilirse /learn etkin, bellek kalıcı")
16
+ # aubin loop "görev" : üretici aday yazar → AUBIN seçer → güven düşükse yeniden üret (üretici: gemma | openai:<model>)
17
+ lp = sub.add_parser("loop"); lp.add_argument("task"); lp.add_argument("--model", default="emrevrg/AUBIN-12B")
18
+ lp.add_argument("--generator", default="gemma"); lp.add_argument("--base_url", default="https://api.openai.com/v1")
19
+ lp.add_argument("--n", type=int, default=4); lp.add_argument("--rounds", type=int, default=3)
20
+ lp.add_argument("--target", type=float, default=0.8); lp.add_argument("--numeric", action="store_true")
21
+ for x in (d, s, lp):
22
+ x.add_argument("--perms", type=int, default=1); x.add_argument("--think", type=float, default=None)
23
+ x.add_argument("--think_mix", type=float, default=None)
24
+ x.add_argument("--ens_T", type=float, default=0.8)
25
+ a = ap.parse_args()
26
+ from .core import Aubin, AubinEnsemble
27
+ specs = [x.rsplit(":", 1) if ":" in x else (x, "1") for x in a.model.split(",")]
28
+ ms = [(Aubin(r, perms=a.perms, think_margin=a.think, think_mix=a.think_mix), float(w)) for r, w in specs]
29
+ m = ms[0][0] if len(ms) == 1 else AubinEnsemble(ms, a.ens_T)
30
+ if a.cmd == "loop":
31
+ from .loop import AubinLoop, GemmaGenerator, OpenAIGenerator, last_number, final_line
32
+ base = ms[0][0]
33
+ gen = GemmaGenerator(base) if a.generator == "gemma" else OpenAIGenerator(a.generator.split(":", 1)[1], a.base_url)
34
+ loop = AubinLoop(m, gen, extract=last_number if a.numeric else final_line, target=a.target, max_rounds=a.rounds,
35
+ n=a.n, mode="aubin+vote")
36
+ print(json.dumps(loop.solve(a.task), ensure_ascii=False, indent=1))
37
+ elif a.cmd == "decide":
38
+ case = json.load(open(a.case, encoding="utf-8")) if a.case != "-" else json.load(sys.stdin)
39
+ print(json.dumps(m.decide(case["state"], case["questions"]), ensure_ascii=False, indent=1))
40
+ else:
41
+ from .server import serve
42
+ if a.learn: # AUBIN-Learn: bellek + öz-kalibrasyon; dosya varsa yüklenir, çıkışta saklanır
43
+ import atexit, os
44
+ from .learn import AubinLearning
45
+ m = AubinLearning(m)
46
+ if os.path.exists(a.learn):
47
+ m.load(a.learn)
48
+ atexit.register(lambda: m.save(a.learn))
49
+ serve(m, a.port)
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
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 ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN çekirdeği: tipli durum + tipli sorular → kalibre olasılıklar (tek ileri geçiş, metin üretimi yok).
2
+
3
+ Soru biçimi Jev/TypeSafe ve Kev ile uyumludur:
4
+ questions = {"iade": {"type": "choice", "instructions": "...", "criteria": {"a": "...", "b": "..."}},
5
+ "acil": {"type": "noul", "instructions": "..."},
6
+ "puan": {"type": "score", "instructions": "...", "criteria": ["kötü", "orta", "iyi"]}}
7
+ Aubin("emrevrg/AUBIN-12B").decide(state, questions)
8
+ → {"iade": {"answer": "a", "confidence": 0.93, "probabilities": {"a": 0.93, "b": 0.07}}, ...}
9
+ """
10
+ from __future__ import annotations
11
+ import json, os
12
+ import torch
13
+ import torch.nn.functional as F
14
+
15
+ L = [chr(65 + i) for i in range(26)]
16
+
17
+
18
+ def options(q):
19
+ t, c = q["type"], q.get("criteria")
20
+ if t == "noul":
21
+ keys = ["false", "true"]
22
+ if isinstance(c, dict):
23
+ return keys, [f"false — {c.get('false', 'no')}", f"true — {c.get('true', 'yes')}"]
24
+ return keys, ["false — no", "true — yes"]
25
+ if t == "choice":
26
+ return list(c.keys()), [f"{k}: {v}" for k, v in c.items()]
27
+ if isinstance(c, list):
28
+ return [str(i) for i in range(len(c))], [str(v) for v in c]
29
+ return list(c.keys()), [f"{k}: {v}" for k, v in c.items()]
30
+
31
+
32
+ class Aubin:
33
+ """AUBIN karar modeli. base: açık taban (Apache-2.0), adapter: AUBIN LoRA'sı (yerel dizin veya HF repo)."""
34
+
35
+ def __init__(self, adapter="emrevrg/AUBIN-12B", base=None, four_bit=True, device_map=None, temperature=None,
36
+ perms=1, max_state=6000, cache_state=False, think_margin=None, think_tokens=256, think_mix=None,
37
+ think_samples=1, think_temp=0.7):
38
+ # önbellek: Gemma-4 GPU'da birebir değil (fark 0.355) → varsayılan KAPALI
39
+ # think_margin: en iyi iki seçeneğin log-olasılık farkı bunun altındaysa kısa akıl yürütme + yeniden puan
40
+ # ("eminsizse düşün"; Kev dev'de 31B: transfer .852→.864, ~%14 soruda üretim yapılır)
41
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
42
+ meta = self._meta(adapter[0] if isinstance(adapter, (list, tuple)) else adapter)
43
+ base = base or meta.get("base_model", "google/gemma-4-12B-it")
44
+ self.T = float(temperature or meta.get("temperature", 1.0))
45
+ self.perms, self.max_state = perms, max_state
46
+ self.think_margin = float(think_margin if think_margin is not None else meta.get("think_margin", 0.0))
47
+ self.think_tokens = think_tokens
48
+ # think_mix: eminsiz soruda düşünen yolun payı (1.0 = yalnız düşünen yol; Duo tarifi 0.5 = hızlı + düşünen yarı yarıya)
49
+ self.think_mix = float(think_mix if think_mix is not None else meta.get("think_mix", 1.0))
50
+ # think_samples>1: self-consistency — açgözlü akıl yürütme + (n-1) örneklenmiş; cevap olasılıkları ortalanır
51
+ self.think_samples, self.think_temp = int(think_samples), float(think_temp)
52
+ self.cache_state, self._pc = cache_state, None
53
+ self.tok = AutoTokenizer.from_pretrained(base)
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)
74
+ try:
75
+ m = AutoModelForCausalLM.from_pretrained(base, **kw)
76
+ except Exception:
77
+ from transformers import AutoModelForImageTextToText
78
+ m = AutoModelForImageTextToText.from_pretrained(base, **kw)
79
+ self.adapters = []
80
+ ads = adapter if isinstance(adapter, (list, tuple)) else ([adapter] if adapter else [])
81
+ if meta.get("no_adapter"): # sürüm yalnız protokol + kalibrasyon (ağırlık değişikliği yok)
82
+ ads = []
83
+ if ads: # birden çok adaptör = ansambl (log-olasılık ortalaması)
84
+ from peft import PeftModel
85
+ m = PeftModel.from_pretrained(m, ads[0], adapter_name="a0")
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:
121
+ if adapter and os.path.isdir(adapter):
122
+ return json.load(open(os.path.join(adapter, "aubin.json")))
123
+ if adapter:
124
+ from huggingface_hub import hf_hub_download
125
+ return json.load(open(hf_hub_download(adapter, "aubin.json")))
126
+ except Exception:
127
+ pass
128
+ return {}
129
+
130
+ def _prompt(self, state_text, q, texts, order):
131
+ st = state_text if len(state_text) <= self.max_state else state_text[: self.max_state] + " …"
132
+ opts = "\n".join(f"{L[j]}) {texts[i]}" for j, i in enumerate(order))
133
+ u = (f"Decide based ONLY on the state below.\n\nSTATE:\n{st}\n\nQUESTION: {q}\n\nOPTIONS:\n{opts}\n\n"
134
+ f"Reply with the single letter of the correct option.")
135
+ msgs = [{"role": "user", "content": u}]
136
+ try:
137
+ p = self.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False, enable_thinking=False)
138
+ except Exception:
139
+ p = self.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
140
+ return p + "Answer: "
141
+
142
+ @torch.no_grad()
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):
158
+ """Durum önbelleği: aynı duruma sorulan her soruda durum kısmı (önek) BİR kez işlenir, KV-önbelleği
159
+ kopyalanıp yalnız soru+seçenekler (sonek) hesaplanır → çok soruda büyük hız kazancı."""
160
+ import copy
161
+ full = self.tok(prompt, add_special_tokens=False).input_ids
162
+ pre_ids = self.tok(prompt[: prompt.index("\n\nQUESTION:")], add_special_tokens=False).input_ids
163
+ k = 0 # token düzeyinde ortak önek: bölme sınırı birebir aynı tokenlarla
164
+ while k < min(len(full), len(pre_ids)) - 1 and full[k] == pre_ids[k]:
165
+ k += 1
166
+ key = (tuple(full[:k]), getattr(self.m, "active_adapter", None))
167
+ if self._pc is None or self._pc[0] != key:
168
+ out = self.m(input_ids=torch.tensor([full[:k]], device=self.dev), use_cache=True)
169
+ self._pc = (key, k, out.past_key_values)
170
+ n_pre, pkv = self._pc[1], copy.deepcopy(self._pc[2])
171
+ sids = torch.tensor([full[k:]], device=self.dev)
172
+ cp = torch.arange(n_pre, n_pre + sids.shape[1], device=self.dev)
173
+ pos = cp.unsqueeze(0)
174
+ # cache_position açıkça verilir: kayan pencereli katmanların önbelleği kırpılmış tutulur, get_seq_length() önek
175
+ # uzunluğunu değil pencere boyunu döndürebilir → maske/konum kayar (Gemma-4 12B'de görülen 0.355 fark)
176
+ try:
177
+ out = self.m(input_ids=sids, past_key_values=pkv, position_ids=pos, cache_position=cp, use_cache=True, logits_to_keep=1)
178
+ except TypeError:
179
+ out = self.m(input_ids=sids, past_key_values=pkv, position_ids=pos, cache_position=cp, use_cache=True)
180
+ last = out.logits[:, -1].float()
181
+ return torch.stack([last[:, ids].logsumexp(-1) for ids in self.letter_ids], -1)
182
+
183
+ def _think(self, state_text, q, texts):
184
+ """Kısa akıl yürütme üret, 'Answer: ' konumunda harf log-olasılıkları (kev_llm.think_scores ile aynı)."""
185
+ st = state_text if len(state_text) <= self.max_state else state_text[: self.max_state] + " …"
186
+ opts = "\n".join(f"{L[j]}) {t}" for j, t in enumerate(texts))
187
+ u = (f"Decide based ONLY on the state below.\n\nSTATE:\n{st}\n\nQUESTION: {q}\n\nOPTIONS:\n{opts}\n\n"
188
+ f"Think briefly step by step (at most 6 short sentences), weighing the most plausible options. "
189
+ f"Then write the final line exactly as 'Answer: <letter>'.")
190
+ msgs = [{"role": "user", "content": u}]
191
+ try:
192
+ p = self.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False, enable_thinking=False)
193
+ except Exception:
194
+ p = self.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
195
+ enc = self.tok([p], return_tensors="pt", add_special_tokens=False).to(self.dev)
196
+ probs, reasons = None, []
197
+ for s in range(max(1, self.think_samples)):
198
+ kw = dict(do_sample=False) if s == 0 else dict(do_sample=True, temperature=self.think_temp, top_p=0.95)
199
+ with torch.no_grad():
200
+ gen = self.m.generate(**enc, max_new_tokens=self.think_tokens, pad_token_id=self.tok.pad_token_id, **kw)
201
+ t = self.tok.decode(gen[0, enc["input_ids"].shape[1]:], skip_special_tokens=True)
202
+ k = t.find("Answer:")
203
+ reasons.append((t[:k] if k >= 0 else t).strip())
204
+ lg = self._letters([p + (t[:k] if k >= 0 else t).rstrip() + "\nAnswer: "])[0, :len(texts)].cpu()
205
+ pr = torch.softmax(lg.float(), -1)
206
+ probs = pr if probs is None else probs + pr
207
+ self.last_reasoning = reasons[0]
208
+ return torch.log(probs / max(1, self.think_samples) + 1e-12)
209
+
210
+ def _maybe_think(self, lp, state_text, q, texts):
211
+ if not self.think_margin or len(texts) > 26 or len(texts) < 2:
212
+ return lp, False
213
+ v = torch.sort(lp, descending=True).values
214
+ if float(v[0] - v[1]) >= self.think_margin:
215
+ return lp, False
216
+ return self._think(state_text, q, texts), True
217
+
218
+ def _mixed(self, fast, state_text, q, texts):
219
+ """Sıcaklıkla ölçeklenmiş log-olasılık; eminsizse düşünen yol think_mix oranında karıştırılır
220
+ (jev_compare.combine ile birebir aynı hesap)."""
221
+ z = torch.log_softmax(fast / self.T, -1)
222
+ think, did = self._maybe_think(fast, state_text, q, texts)
223
+ if did and self.think_mix > 0:
224
+ z = (1 - self.think_mix) * z + self.think_mix * torch.log_softmax(think / self.T, -1)
225
+ return z
226
+
227
+ def _score(self, state_text, q, texts):
228
+ """Sıcaklık UYGULANMIŞ log-olasılıklar."""
229
+ if len(self.adapters) > 1:
230
+ outs = []
231
+ for name in self.adapters:
232
+ self.m.set_adapter(name)
233
+ outs.append(self._mixed(self._score_one(state_text, q, texts), state_text, q, texts))
234
+ return torch.log_softmax(torch.stack(outs).mean(0), -1)
235
+ return self._mixed(self._score_one(state_text, q, texts), state_text, q, texts)
236
+
237
+ def _score_one(self, state_text, q, texts):
238
+ n = len(texts); idx = list(range(n))
239
+ if n > 26: # 26'lık gruplar + final turu
240
+ full, winners = torch.full((n,), -1e4), []
241
+ for s in range(0, n, 26):
242
+ g = idx[s:s + 26]
243
+ lg = self._letters([self._prompt(state_text, q, texts, g)])[0, :len(g)].cpu()
244
+ full[torch.tensor(g)] = lg; winners.append(g[int(lg.argmax())])
245
+ lg = self._letters([self._prompt(state_text, q, texts, winners)])[0, :len(winners)].cpu()
246
+ full[torch.tensor(winners)] = lg + 50.0
247
+ return torch.log_softmax(full, -1)
248
+ acc = torch.zeros(n)
249
+ shifts = sorted({(k * n) // self.perms for k in range(self.perms)})
250
+ for s in shifts: # seçenek sırası döndürülür: konum yanlılığı ortalanır
251
+ order = idx[s:] + idx[:s]
252
+ lg = torch.log_softmax(self._letters([self._prompt(state_text, q, texts, order)])[0, :n].cpu(), -1)
253
+ back = torch.empty(n); back[torch.tensor(order)] = lg; acc += back
254
+ return acc / len(shifts)
255
+
256
+ def logprobs(self, state, questions):
257
+ """Her soru için sıcaklıkla ölçeklenmiş log-olasılıklar {id: (keys, tensor)} — ansambl bunları birleştirir."""
258
+ st = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False)
259
+ out = {}
260
+ for qid, q in questions.items():
261
+ keys, texts = options(q)
262
+ out[qid] = (keys, torch.log_softmax(self._score(st, q.get("instructions") or qid, texts), -1))
263
+ return out
264
+
265
+ def decide(self, state, questions):
266
+ """state: dict/str; questions: {id: {type, instructions, criteria}} → {id: {answer, confidence, probabilities}}"""
267
+ return _package(self.logprobs(state, questions), 1.0)
268
+
269
+
270
+ def _package(lps, T):
271
+ out = {}
272
+ for qid, (keys, lp) in lps.items():
273
+ p = F.softmax(lp / T, -1)
274
+ j = int(p.argmax())
275
+ out[qid] = {"answer": keys[j], "confidence": round(float(p[j]), 4),
276
+ "probabilities": {k: round(float(v), 4) for k, v in zip(keys, p)}}
277
+ return out
278
+
279
+
280
+ class AubinEnsemble:
281
+ """Farklı tabanlardaki AUBIN üyelerinin ağırlıklı log-olasılık birleşimi (ör. 31B + 12B).
282
+ members: [(Aubin, ağırlık), ...]; temperature: birleşim sonrası sıcaklık (Kev dev'de ölçülen tarif: T=0.8)."""
283
+
284
+ def __init__(self, members, temperature=0.8):
285
+ s = sum(w for _, w in members)
286
+ self.members = [(m, w / s) for m, w in members]
287
+ self.T = temperature
288
+
289
+ def decide(self, state, questions):
290
+ acc = None
291
+ for m, w in self.members:
292
+ lp = m.logprobs(state, questions)
293
+ acc = {k: (v[0], w * v[1]) for k, v in lp.items()} if acc is None else \
294
+ {k: (acc[k][0], acc[k][1] + w * lp[k][1]) for k in acc}
295
+ return _package(acc, self.T)
code/aubin/learn.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN-Learn — Norovox öz-öğrenme çekirdeğinin karar modeline entegrasyonu.
2
+
3
+ Norovox Alpha Mini ilkesi: bilgi ağırlıkta değil, DIŞ BELLEKTE tutulur; model düşünür, bellek hatırlar.
4
+ Burada bu ilke AUBIN'in hızlı karar sürecine taşınır:
5
+
6
+ learn(...) doğrulanmış bir vakayı belleğe yazar — gradyan yok, eğitim yok, ~milisaniye; bir sonraki soruda etkili.
7
+ recall(...) aynı soru tipindeki (kaynak + seçenek kümesi) en benzer çözülmüş vakalardan seçeneklere oy dağılımı.
8
+ fuse(...) modelin log-olasılıkları + bellek oyları (log-doğrusal); ağırlık kaynak-başına, YALNIZ dev'de ayarlanır.
9
+ AubinLearner modeli sarar: emin değilse belleğe bakar; bellekte karşılığı yoksa araştırma kancası (Norovox
10
+ Retrieval: yerel bilgi tabanı → web) kanıt getirir; geri bildirim gelince learn() ile eksiğini kapatır.
11
+
12
+ Gömme (embedding) takılabilir: varsayılan sözcük+karakter n-gram karma vektörü (bağımlılıksız, CPU'da µs-ms),
13
+ istenirse cümle gömme modeli (ör. BAAI/bge-small-en-v1.5) `embed_fn` olarak verilir.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import math
19
+ import re
20
+ import time
21
+ from collections import defaultdict
22
+
23
+ import numpy as np
24
+
25
+ DIM = int(__import__("os").environ.get("AUBIN_HASH_DIM", 2 ** 13))
26
+
27
+
28
+ def hash_embed(texts, dim: int = DIM) -> np.ndarray:
29
+ """Sözcük (1-2 gram) + karakter 4-gram karma (hashing) vektörü, L2-normalize. Model indirmeden çalışır."""
30
+ out = np.zeros((len(texts), dim), dtype=np.float32)
31
+ for r, t in enumerate(texts):
32
+ t = re.sub(r"\s+", " ", str(t).lower())
33
+ ws = re.findall(r"[a-z0-9çğıöşü']+", t)
34
+ feats = ws + [a + "_" + b for a, b in zip(ws, ws[1:])] + [t[i:i + 4] for i in range(0, max(0, len(t) - 3), 2)]
35
+ for f in feats:
36
+ h = int.from_bytes(hashlib.blake2b(f.encode(), digest_size=8).digest(), "little")
37
+ out[r, h % dim] += 1.0 if (h >> 63) & 1 else -1.0
38
+ n = np.linalg.norm(out[r])
39
+ if n:
40
+ out[r] /= n
41
+ return out
42
+
43
+
44
+ def sig(src, keys) -> str:
45
+ """Bellek bölümü. ≤26 seçenek: kaynak + seçenek kümesinin tamamı. Geniş sorularda (banking77: 77–78 seçenek, testte
46
+ seçenek kümesi değişebiliyor) yalnız kaynak — oylar etiket ADIYLA mevcut seçeneklere eşlenir."""
47
+ if len(keys) > 26:
48
+ return f"{src}|wide"
49
+ return f"{src}|{len(keys)}|" + hashlib.md5("\x1f".join(map(str, keys)).encode()).hexdigest()[:10]
50
+
51
+
52
+ class DecisionMemory:
53
+ """Soru tipine göre bölümlenmiş vaka belleği. Ekleme O(1); arama bölüm-içi kosinüs (matris çarpımı)."""
54
+
55
+ def __init__(self, embed_fn=hash_embed):
56
+ self.embed_fn = embed_fn
57
+ self.vecs: dict[str, list] = defaultdict(list) # imza → vektör listesi (yeni eklenenler)
58
+ self.mats: dict[str, np.ndarray] = {} # imza → donmuş matris (toplu arama için)
59
+ self.labels: dict[str, list] = defaultdict(list) # imza → etiket ADI listesi (seçenek kümesinden bağımsız)
60
+ self.n = 0
61
+
62
+ def _freeze(self, s):
63
+ if self.vecs[s]:
64
+ new = np.stack(self.vecs[s])
65
+ self.mats[s] = new if s not in self.mats else np.concatenate([self.mats[s], new])
66
+ self.vecs[s] = []
67
+
68
+ def learn(self, text, src, keys, y, vec=None):
69
+ """Tek vaka öğren (anında etkili). Dönüş: geçen süre (ms)."""
70
+ t0 = time.perf_counter()
71
+ s = sig(src, keys)
72
+ v = vec if vec is not None else self.embed_fn([text])[0]
73
+ self.vecs[s].append(v.astype(np.float32)); self.labels[s].append(str(keys[int(y)])); self.n += 1
74
+ return (time.perf_counter() - t0) * 1e3
75
+
76
+ def learn_many(self, texts, srcs, keyss, ys, batch=2048):
77
+ for i in range(0, len(texts), batch):
78
+ self.learn_vectors(self.embed_fn(texts[i:i + batch]), srcs[i:i + batch], keyss[i:i + batch], ys[i:i + batch])
79
+
80
+ def learn_vectors(self, V, srcs, keyss, ys):
81
+ """Önceden gömülmüş vakaları toplu öğren (gömme bir kez hesaplanır, farklı bellekler için yeniden kullanılır)."""
82
+ for v, sr, ks, y in zip(V, srcs, keyss, ys):
83
+ s = sig(sr, ks); self.vecs[s].append(np.asarray(v, dtype=np.float32)); self.labels[s].append(str(ks[int(y)])); self.n += 1
84
+ for s in list(self.vecs):
85
+ self._freeze(s)
86
+
87
+ def recall(self, text, src, keys, k=16, tau=0.05, vec=None):
88
+ """Seçenekler üzerinde bellek dağılımı (benzerlik-ağırlıklı oy) + en yüksek benzerlik. Bellek boşsa (None, 0)."""
89
+ s = sig(src, keys)
90
+ self._freeze(s)
91
+ M = self.mats.get(s)
92
+ if M is None or not len(M):
93
+ return None, 0.0
94
+ q = vec if vec is not None else self.embed_fn([text])[0]
95
+ sims = M @ q
96
+ kk = min(k, len(sims))
97
+ top = np.argpartition(-sims, kk - 1)[:kk]
98
+ w = np.exp((sims[top] - sims[top].max()) / tau)
99
+ p = vote([self.labels[s][i] for i in top], w, keys)
100
+ return p, (float(sims[top].max()) if p is not None else 0.0)
101
+
102
+
103
+ def vote(labels, weights, keys):
104
+ """Komşu etiket adlarını mevcut seçeneklere eşle (seçenek kümesi değişse de çalışır). Eşleşen yoksa None."""
105
+ pos = {str(k): i for i, k in enumerate(keys)}
106
+ p = np.zeros(len(keys), dtype=np.float64)
107
+ for lab, wi in zip(labels, weights):
108
+ j = pos.get(lab)
109
+ if j is not None:
110
+ p[j] += wi
111
+ return p / p.sum() if p.sum() > 0 else None
112
+
113
+
114
+ def fuse(lp_model, p_mem, w, T=1.0, eps=1e-3):
115
+ """Log-doğrusal birleştirme: log p_model/T + w·log(p_mem + ε). p_mem yoksa model aynen kalır."""
116
+ lp = np.asarray(lp_model, dtype=np.float64) / T
117
+ if p_mem is None or w == 0:
118
+ return lp - np.logaddexp.reduce(lp)
119
+ z = lp + w * np.log(np.asarray(p_mem) + eps)
120
+ return z - np.logaddexp.reduce(z)
121
+
122
+
123
+ class SelfCalibrator:
124
+ """Öz-kalibrasyon (Hedge / çarpımsal ağırlıklar): her kaynak için uzmanlar — model, bellek, birleşik — arasında güveni
125
+ geri bildirimle kendisi ayarlar. Kayıp = log-kayıp; π_e ← π_e·exp(−η·kayıp_e). Pişmanlık sınırı: zamanla en iyi uzmana yaklaşır,
126
+ yani bellek bir kaynakta işe yaramıyorsa ona olan güven kendiliğinden söner (kendi eksiğini kendisi kapatır)."""
127
+
128
+ EXPERTS = ("model", "memory", "fused")
129
+
130
+ def __init__(self, eta=1.0, prior=(0.6, 0.1, 0.3)):
131
+ self.eta, self.prior = eta, np.log(np.asarray(prior, dtype=np.float64))
132
+ self.logw = defaultdict(lambda: self.prior.copy())
133
+
134
+ @staticmethod
135
+ def experts(lp_model, p_mem, w_fuse=1.0):
136
+ pm = np.exp(np.asarray(lp_model, dtype=np.float64) - np.logaddexp.reduce(lp_model))
137
+ pk = pm if p_mem is None else 0.98 * np.asarray(p_mem) + 0.02 / len(pm)
138
+ pf = np.exp(fuse(lp_model, p_mem, w_fuse))
139
+ return np.stack([pm, pk, pf])
140
+
141
+ def predict(self, src, E):
142
+ pi = np.exp(self.logw[src] - np.logaddexp.reduce(self.logw[src]))
143
+ return pi @ E, pi
144
+
145
+ def update(self, src, E, y):
146
+ self.logw[src] = self.logw[src] - self.eta * (-np.log(E[:, y] + 1e-12))
147
+
148
+
149
+ class AubinLearning:
150
+ """Ürün katmanı: herhangi bir AUBIN modelini (Aubin / AubinEnsemble — .logprobs(state, questions) sunan) öz-öğrenen hale getirir.
151
+
152
+ smart = AubinLearning(Aubin("emrevrg/AUBIN-12B"))
153
+ out = smart.decide(state, questions) # bellek + öz-kalibrasyonlu karar
154
+ smart.learn(state, questions, {"q1": "refund"}) # doğru cevap → anında öğrenilir (eğitim yok)
155
+ smart.save("mem.npz"); smart.load("mem.npz") # bellek kalıcı
156
+ Bellek bölümü = soru kimliği + seçenek kümesi (geniş sorularda etiket ADI eşlemesi)."""
157
+
158
+ def __init__(self, model, memory=None, calibrator=None, k=16, tau=0.05, w_fuse=1.0):
159
+ self.model, self.mem = model, (memory or DecisionMemory())
160
+ self.cal = calibrator or SelfCalibrator()
161
+ self.k, self.tau, self.w = k, tau, w_fuse
162
+ self._last = {}
163
+
164
+ @staticmethod
165
+ def _text(state, q):
166
+ import json as _j
167
+ st = state if isinstance(state, str) else _j.dumps(state, ensure_ascii=False, sort_keys=True)
168
+ return f"{st} || {(q or {}).get('instructions', '')}"
169
+
170
+ def decide(self, state, questions):
171
+ lps = self.model.logprobs(state, questions)
172
+ out = {}
173
+ for qid, (keys, lp) in lps.items():
174
+ lp = np.asarray(lp.detach().cpu() if hasattr(lp, "detach") else lp, dtype=np.float64)
175
+ p, smax = self.mem.recall(self._text(state, questions[qid]), qid, keys, self.k, self.tau)
176
+ E = SelfCalibrator.experts(lp, p, self.w)
177
+ mix, pi = self.cal.predict(qid, E)
178
+ self._last[(qid, self._text(state, questions[qid]))] = E
179
+ j = int(np.argmax(mix))
180
+ out[qid] = {"answer": keys[j], "confidence": round(float(mix[j]), 4),
181
+ "probabilities": {str(k): round(float(v), 4) for k, v in zip(keys, mix)},
182
+ "memory": {"similar_case": round(smax, 3), "trust_model_memory_fused": [round(float(x), 3) for x in pi]}}
183
+ return out
184
+
185
+ def learn(self, state, questions, answers):
186
+ """answers: {qid: doğru seçenek anahtarı}. Belleğe yazar + (son decide varsa) güveni günceller. Dönüş: ms."""
187
+ from .core import options
188
+ t0 = time.perf_counter()
189
+ for qid, ans in answers.items():
190
+ keys, _ = options(questions[qid])
191
+ keys = [str(k) for k in keys]
192
+ if str(ans) not in keys:
193
+ continue
194
+ y = keys.index(str(ans)); txt = self._text(state, questions[qid])
195
+ E = self._last.pop((qid, txt), None)
196
+ if E is not None:
197
+ self.cal.update(qid, E, y)
198
+ self.mem.learn(txt, qid, keys, y)
199
+ return round((time.perf_counter() - t0) * 1e3, 3)
200
+
201
+ def save(self, path):
202
+ for s in list(self.mem.vecs):
203
+ self.mem._freeze(s)
204
+ np.savez_compressed(path, **{f"M::{s}": m for s, m in self.mem.mats.items()},
205
+ **{f"L::{s}": np.asarray(self.mem.labels[s]) for s in self.mem.mats})
206
+
207
+ def load(self, path):
208
+ Z = np.load(path, allow_pickle=False)
209
+ for f in Z.files:
210
+ if f.startswith("M::"):
211
+ s = f[3:]; self.mem.mats[s] = Z[f]; self.mem.labels[s] = [str(x) for x in Z["L::" + s]]
212
+ self.mem.n = sum(len(v) for v in self.mem.labels.values())
213
+
214
+
215
+ class AubinLearner:
216
+ """Karar modeli + öz-öğrenme belleği + araştırma kancası.
217
+
218
+ score_fn(item) → seçenek log-olasılıkları (ör. kev_llm.Scorer.score); item: {"state","q","keys","texts","src"}.
219
+ research_fn(query) → kanıt metinleri listesi (ör. norovox_mini.retrieval.Retrieval().fetch).
220
+ """
221
+
222
+ def __init__(self, score_fn, memory=None, weights=None, margin=99.0, research_fn=None, k=16, tau=0.05, calibrator=None):
223
+ self.score_fn, self.mem = score_fn, (memory or DecisionMemory())
224
+ self.weights = weights or {} # kaynak → bellek birleştirme ağırlığı (dev'de ayarlanır); yoksa "*" ya da 0.5
225
+ self.margin, self.research_fn, self.k, self.tau = margin, research_fn, k, tau
226
+ self.cal = calibrator if calibrator is not None else SelfCalibrator()
227
+ self.log, self._last = [], {}
228
+
229
+ @staticmethod
230
+ def text(it):
231
+ return f"{it['state']} || {it['q']}"
232
+
233
+ def decide(self, it):
234
+ t0 = time.perf_counter()
235
+ lp = np.asarray(self.score_fn(it), dtype=np.float64)
236
+ srt = np.sort(lp)[::-1]
237
+ unsure = len(lp) > 1 and (srt[0] - srt[1]) < self.margin
238
+ p, smax, evidence = self.mem.recall(self.text(it), it["src"], it["keys"], self.k, self.tau) + ([],)
239
+ if p is None and unsure and self.research_fn is not None: # bellekte karşılığı yok: dışarıdan kanıt (Norovox Retrieval)
240
+ try:
241
+ evidence = self.research_fn(f"{it['q']} {str(it['state'])[:300]}")[:3]
242
+ except Exception:
243
+ evidence = []
244
+ E = SelfCalibrator.experts(lp, p, self.weights.get(it["src"], self.weights.get("*", 0.5)))
245
+ mix, pi = self.cal.predict(it["src"], E)
246
+ self._last[id(it)] = E
247
+ ms = (time.perf_counter() - t0) * 1e3
248
+ self.log.append({"src": it["src"], "unsure": bool(unsure), "memory_sim": round(smax, 3), "trust": [round(float(x), 3) for x in pi],
249
+ "evidence": len(evidence), "ms": round(ms, 2)})
250
+ return int(np.argmax(mix)), np.log(mix + 1e-12), evidence
251
+
252
+ def feedback(self, it, y):
253
+ """Doğru cevap gelince: (1) belleğe yaz — bilgi eksiği anında kapanır; (2) öz-kalibrasyon — bu kaynakta model mi bellek mi
254
+ daha isabetli, güven kendiliğinden kayar. Dönüş: ms."""
255
+ t0 = time.perf_counter()
256
+ E = self._last.pop(id(it), None)
257
+ if E is not None:
258
+ self.cal.update(it["src"], E, int(y))
259
+ self.mem.learn(self.text(it), it["src"], it["keys"], y)
260
+ return (time.perf_counter() - t0) * 1e3
code/aubin/loop.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN Loop — üretici + karar verici döngüsü (generate → decide → refine).
2
+
3
+ Bir üretici (herhangi bir LLM) aday cevaplar yazar; AUBIN adaylar arasından KALİBRE olasılıkla seçer; güven hedefin
4
+ altındaysa üreticiden, önceki adaylar geri bildirim olarak verilip yeni adaylar istenir.
5
+
6
+ Gemma'da tek ağırlık: GemmaGenerator aynı tabanı AUBIN adaptörü KAPALI kullanır (ek bellek yok), karar AUBIN adaptörüyle.
7
+ Dış üretici: OpenAIGenerator (ChatGPT, vLLM, Ollama… OpenAI-uyumlu uç). Anahtar yalnız ortam değişkeninden okunur.
8
+
9
+ from aubin import Aubin
10
+ from aubin.loop import AubinLoop, GemmaGenerator, last_number
11
+ A = Aubin("emrevrg/AUBIN-12B")
12
+ loop = AubinLoop(A, GemmaGenerator(A), extract=last_number, target=0.8)
13
+ loop.solve("Natalia sold clips to 48 friends in April, and half as many in May. How many in total?")
14
+ → {"answer": "72", "confidence": 0.97, "rounds": 1, "candidates": [...], "trace": [...]}
15
+ """
16
+ from __future__ import annotations
17
+ import contextlib, json, os, re, urllib.request
18
+ import torch
19
+
20
+ SOLVE = ("Solve the task below. Reason briefly, then end with a last line exactly of the form 'Final answer: <answer>'.\n\n"
21
+ "TASK:\n{task}{context}")
22
+
23
+
24
+ def last_number(text):
25
+ """Sayısal cevap: 'Final answer:' satırı, yoksa metindeki son sayı (virgül/para birimi temizlenir)."""
26
+ m = re.search(r"final answer\s*[::]\s*(.+)", text, flags=re.I)
27
+ s = m.group(1) if m else text
28
+ nums = re.findall(r"-?\d[\d,]*(?:\.\d+)?", s)
29
+ if not nums:
30
+ return None
31
+ v = nums[0 if m else -1].replace(",", "").rstrip(".")
32
+ try:
33
+ f = float(v)
34
+ return str(int(f)) if f == int(f) else str(f)
35
+ except ValueError:
36
+ return v
37
+
38
+
39
+ def final_line(text):
40
+ m = re.search(r"final answer\s*[::]\s*(.+)", text, flags=re.I)
41
+ return (m.group(1) if m else text.strip().splitlines()[-1] if text.strip() else "").strip() or None
42
+
43
+
44
+ class GemmaGenerator:
45
+ """Aday üretici: AUBIN'in kendi tabanı, adaptör kapalı (tek ağırlık seti)."""
46
+
47
+ def __init__(self, aubin, max_new=320, temperature=0.8, top_p=0.95):
48
+ self.A, self.max_new, self.temp, self.top_p = aubin, max_new, temperature, top_p
49
+
50
+ def _prompt(self, text):
51
+ msgs = [{"role": "user", "content": text}]
52
+ try:
53
+ return self.A.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False, enable_thinking=False)
54
+ except Exception:
55
+ return self.A.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
56
+
57
+ @torch.no_grad()
58
+ def batch(self, texts, greedy=False):
59
+ """Birden çok istem tek toplu üretimde (döngüde ve ölçümde verim için)."""
60
+ tok, m = self.A.tok, self.A.m
61
+ enc = tok([self._prompt(t) for t in texts], return_tensors="pt", padding=True, add_special_tokens=False).to(self.A.dev)
62
+ ctx = m.disable_adapter() if getattr(self.A, "adapters", None) and hasattr(m, "disable_adapter") else contextlib.nullcontext()
63
+ kw = dict(do_sample=False) if greedy else dict(do_sample=True, temperature=self.temp, top_p=self.top_p)
64
+ with ctx:
65
+ gen = m.generate(**enc, max_new_tokens=self.max_new, pad_token_id=tok.pad_token_id, **kw)
66
+ return tok.batch_decode(gen[:, enc["input_ids"].shape[1]:], skip_special_tokens=True)
67
+
68
+ def __call__(self, prompt, n, greedy_first=False):
69
+ out = self.batch([prompt], greedy=True) if greedy_first else []
70
+ return out + (self.batch([prompt] * (n - len(out))) if n > len(out) else [])
71
+
72
+
73
+ class OpenAIGenerator:
74
+ """OpenAI-uyumlu sohbet ucu. Anahtar koda/istem yazılmaz: api_key_env ortam değişkeninden okunur."""
75
+
76
+ def __init__(self, model="gpt-4o-mini", base_url="https://api.openai.com/v1", api_key_env="OPENAI_API_KEY",
77
+ temperature=0.8, max_tokens=512):
78
+ self.model, self.url, self.env, self.temp, self.max_tokens = model, base_url.rstrip("/"), api_key_env, temperature, max_tokens
79
+
80
+ def __call__(self, prompt, n, greedy_first=False):
81
+ body = {"model": self.model, "messages": [{"role": "user", "content": prompt}], "n": n,
82
+ "temperature": self.temp, "max_tokens": self.max_tokens}
83
+ req = urllib.request.Request(self.url + "/chat/completions", data=json.dumps(body).encode(),
84
+ headers={"Content-Type": "application/json",
85
+ "Authorization": "Bearer " + os.environ.get(self.env, "")})
86
+ with urllib.request.urlopen(req, timeout=120) as r:
87
+ d = json.load(r)
88
+ return [c["message"]["content"] for c in d["choices"]]
89
+
90
+
91
+ class AubinLoop:
92
+ """generate → decide → refine. decider: Aubin / AubinEnsemble (decide(state, questions) arayüzü)."""
93
+
94
+ def __init__(self, decider, generator, extract=final_line, target=0.8, max_rounds=3, n=4, none_option=True,
95
+ mode="aubin", rationale_chars=600):
96
+ self.D, self.G, self.extract = decider, generator, extract
97
+ self.target, self.max_rounds, self.n, self.none = target, max_rounds, n, none_option
98
+ self.mode, self.rc = mode, rationale_chars # mode: "aubin" | "aubin+vote" (AUBIN olasılığı × oy payı)
99
+
100
+ def question(self, task, cands):
101
+ crit = {f"c{i}": f"{c['answer']} — reasoning: {c['text'][-self.rc:].strip()}" for i, c in enumerate(cands)}
102
+ if self.none:
103
+ crit["none"] = "none of the proposed answers is correct"
104
+ return {"type": "choice", "instructions": "Which proposed answer to the task is correct? Check the reasoning.",
105
+ "criteria": crit}
106
+
107
+ def decide(self, task, context, cands):
108
+ res = self.D.decide({"task": task, "context": context or ""}, {"pick": self.question(task, cands)})["pick"]
109
+ probs = dict(res["probabilities"])
110
+ if self.mode == "aubin+vote": # az örnekte oy gürültülü: +1 düzeltmeli oy payıyla çarpılır
111
+ tot = sum(c["votes"] for c in cands) + len(cands)
112
+ for i, c in enumerate(cands):
113
+ probs[f"c{i}"] = probs.get(f"c{i}", 0.0) * (c["votes"] + 1) / tot
114
+ z = sum(probs.values()) or 1.0
115
+ probs = {k: v / z for k, v in probs.items()}
116
+ best = max(probs, key=probs.get)
117
+ return best, probs[best], probs
118
+
119
+ def solve(self, task, context=None, prior=None):
120
+ """prior: önceden üretilmiş aday metinleri (ör. ölçümde toplu üretilenler) — ilk turda üretici çağrılmaz."""
121
+ cands, trace, feedback = [], [], ""
122
+ for r in range(self.max_rounds):
123
+ outs = prior if (r == 0 and prior is not None) else self.G(SOLVE.format(task=task, context=(
124
+ "\n\nCONTEXT:\n" + context if context else "")) + feedback, self.n)
125
+ for o in outs:
126
+ a = self.extract(o)
127
+ if a is None:
128
+ continue
129
+ hit = next((c for c in cands if c["answer"] == a), None)
130
+ if hit:
131
+ hit["votes"] += 1
132
+ else:
133
+ cands.append({"answer": a, "text": o, "votes": 1})
134
+ if not cands:
135
+ continue
136
+ best, conf, probs = self.decide(task, context, cands)
137
+ trace.append({"round": r + 1, "candidates": [(c["answer"], c["votes"]) for c in cands], "pick": best,
138
+ "confidence": round(conf, 4)})
139
+ if best != "none" and conf >= self.target:
140
+ break
141
+ feedback = ("\n\nEarlier proposed answers were judged unreliable: " + ", ".join(c["answer"] for c in cands) +
142
+ ". Solve again carefully from scratch.")
143
+ if not cands:
144
+ return {"answer": None, "confidence": 0.0, "rounds": len(trace), "candidates": [], "trace": trace}
145
+ real = {k: v for k, v in probs.items() if k != "none"}
146
+ k = best if best != "none" else max(real, key=real.get)
147
+ c = cands[int(k[1:])]
148
+ return {"answer": c["answer"], "confidence": round(float(probs[k]), 4), "rounds": len(trace),
149
+ "candidates": [(x["answer"], x["votes"]) for x in cands], "trace": trace,
150
+ "rejected_all": best == "none"}
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/aubin/server.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bağımlılıksız HTTP sunucu — her yere tak-çalıştır entegrasyon.
2
+
3
+ POST /decide {"state": ..., "questions": {...}} → kalibre olasılıklar (+ bellek/güven bilgisi)
4
+ POST /learn {"state": ..., "questions": {...}, "answers": {qid: anahtar}} → anında öğrenme (ms)
5
+ POST /v1/chat/completions OpenAI uyumlu: son kullanıcı mesajı JSON {"state","questions"} → yanıt içeriği JSON karar
6
+ GET /health
7
+ Model AubinLearning ile sarılıysa /learn etkin; değilse /decide düz modelle çalışır.
8
+ """
9
+ import json, time
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ import threading
12
+
13
+
14
+ def serve(model, port=8009):
15
+ lock = threading.Lock()
16
+
17
+ class H(BaseHTTPRequestHandler):
18
+ def _send(self, code, obj):
19
+ data = json.dumps(obj, ensure_ascii=False).encode()
20
+ self.send_response(code); self.send_header("Content-Type", "application/json")
21
+ self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
22
+
23
+ def do_GET(self):
24
+ if self.path.rstrip("/") in ("/health", ""):
25
+ self._send(200, {"ok": True, "model": type(model).__name__, "learning": hasattr(model, "learn")})
26
+ else:
27
+ self.send_error(404)
28
+
29
+ def do_POST(self):
30
+ path = self.path.rstrip("/")
31
+ try:
32
+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
33
+ with lock: # tek GPU: istekler sırayla
34
+ if path == "/decide":
35
+ out = model.decide(body["state"], body["questions"])
36
+ elif path == "/learn":
37
+ if not hasattr(model, "learn"):
38
+ return self._send(400, {"error": "model AubinLearning ile sarılı değil"})
39
+ out = {"learned_ms": model.learn(body["state"], body["questions"], body["answers"])}
40
+ elif path == "/v1/chat/completions":
41
+ msg = [m for m in body.get("messages", []) if m.get("role") == "user"][-1]["content"]
42
+ req = json.loads(msg) if isinstance(msg, str) else msg
43
+ dec = model.decide(req["state"], req["questions"])
44
+ out = {"id": f"aubin-{int(time.time() * 1000)}", "object": "chat.completion", "created": int(time.time()),
45
+ "model": body.get("model", "aubin"),
46
+ "choices": [{"index": 0, "finish_reason": "stop",
47
+ "message": {"role": "assistant", "content": json.dumps(dec, ensure_ascii=False)}}]}
48
+ else:
49
+ return self.send_error(404)
50
+ self._send(200, out)
51
+ except Exception as e:
52
+ self._send(400, {"error": str(e)})
53
+
54
+ def log_message(self, *a):
55
+ pass
56
+
57
+ print(f"AUBIN hazır: http://127.0.0.1:{port} (/decide, /learn, /v1/chat/completions, /health)", flush=True)
58
+ ThreadingHTTPServer(("0.0.0.0", port), H).serve_forever()
code/ensemble.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN ansambl + kalibrasyon (GPU'suz): kev_llm.py çıktılarındaki soru-başı log-olasılıkları birleştirir.
2
+
3
+ python ensemble.py out.json run1.json run2.json [--tag runs] [--weights 1,1]
4
+ Birleştirme: ağırlıklı log-olasılık ortalaması; sıcaklık YALNIZ calibration (decision-v7 cal) üzerinde seçilir.
5
+ """
6
+ import argparse, json, math
7
+ import numpy as np
8
+
9
+
10
+ def softmax(x):
11
+ x = np.asarray(x, dtype=np.float64); x = x - x.max(); e = np.exp(x); return e / e.sum()
12
+
13
+
14
+ def metrics(rows, T):
15
+ by, allr = {}, []
16
+ for src, y, lp in rows:
17
+ p = softmax(np.asarray(lp) / T); oh = np.zeros(len(p)); oh[y] = 1
18
+ r = (int(p.argmax()) == y, float(((p - oh) ** 2).sum()), float(p.max()), -math.log(max(p[y], 1e-12)))
19
+ allr.append(r); by.setdefault(src, []).append(r)
20
+ def m(v):
21
+ ece = 0.0
22
+ for j in range(15):
23
+ bb = [x for x in v if j / 15 < x[2] <= (j + 1) / 15]
24
+ if bb:
25
+ ece += len(bb) / len(v) * abs(np.mean([x[2] for x in bb]) - np.mean([x[0] for x in bb]))
26
+ return {"n": len(v), "accuracy": round(float(np.mean([x[0] for x in v])), 4), "brier": round(float(np.mean([x[1] for x in v])), 4),
27
+ "nll": round(float(np.mean([x[3] for x in v])), 4), "ece15": round(float(ece), 4)}
28
+ return {"all": m(allr), "by_source": {k: m(v) for k, v in sorted(by.items())}}
29
+
30
+
31
+ def main():
32
+ ap = argparse.ArgumentParser()
33
+ ap.add_argument("out"); ap.add_argument("runs", nargs="+"); ap.add_argument("--tag", default="runs")
34
+ ap.add_argument("--weights", default="")
35
+ a = ap.parse_args()
36
+ R = [json.load(open(f)) for f in a.runs]
37
+ w = [float(x) for x in a.weights.split(",")] if a.weights else [1.0] * len(R)
38
+ w = np.array(w) / sum(w)
39
+ cal = [r.get(a.tag + "_cal_items") for r in R]
40
+ out = {"members": [{"file": f, "model": r.get("model"), "lora": r.get("lora")} for f, r in zip(a.runs, R)], "weights": w.tolist()}
41
+ T = 1.0
42
+ if all(cal):
43
+ comb = [(None, c[0]["y"], sum(wi * np.asarray(ci[k]["lp"]) for wi, ci in zip(w, cal))) for k, c in enumerate(zip(*cal))]
44
+ T = min(np.concatenate([np.arange(0.3, 4.0, 0.05), np.arange(4.0, 20.01, 0.25)]), key=lambda t: metrics([(0, y, lp) for _, y, lp in comb], t)["all"]["nll"])
45
+ out["temperature"] = round(float(T), 2)
46
+ suites = set.intersection(*[set(r[a.tag].keys()) if a.tag in r else set(r["runs"].keys()) for r in R])
47
+ for s in sorted(suites):
48
+ its = [(r[a.tag] if a.tag in r else r["runs"])[s]["items"] for r in R]
49
+ assert all(len(x) == len(its[0]) for x in its), "üyelerin madde sayısı farklı"
50
+ rows = []
51
+ for k in range(len(its[0])):
52
+ ys = {x[k]["y"] for x in its}; assert len(ys) == 1, "madde sırası uyuşmuyor"
53
+ rows.append((its[0][k]["src"], its[0][k]["y"], sum(wi * np.asarray(x[k]["lp"]) for wi, x in zip(w, its))))
54
+ out[s] = metrics(rows, T)
55
+ print(s, json.dumps(out[s]["all"]))
56
+ json.dump(out, open(a.out, "w"), indent=1)
57
+
58
+
59
+ if __name__ == "__main__":
60
+ main()
code/kev_augment.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kev eğitim kaynaklarından EK eğitim verisi: aynı HF veri setlerinin eğitim bölümünden, Kev'in HİÇBİR kümesiyle çakışmayan satırlar.
2
+
3
+ Kev decision-v7/train her kaynaktan 1000 satır kullanır (_meta: repo, revision, split, row). Bu betik, her kaynak için
4
+ (1) durum metninin orijinal satırdan nasıl kurulduğunu, (2) orijinal etiket -> soru etiketi eşlemesini,
5
+ (3) soru metnine giren satıra-özgü alanları (MNLI hipotezi, BoolQ sorusu)
6
+ Kev'in kendi satırlarından otomatik öğrenir; sonra yeni satırları rastgele bir Kev şablonuyla aynı biçime çevirir.
7
+ Sızıntı yok: Kev train/dev/cal/test/transfer kümelerindeki tüm durum metinleri (normalize hash) ve kullanılan satır numaraları dışlanır.
8
+
9
+ python kev_augment.py --work /tmp/kev --per_source 4000 --out /content/kev_extra.jsonl
10
+ KEV_EXTRA_TRAIN=/content/kev_extra.jsonl python kev_llm.py ... --train N
11
+ """
12
+ import argparse, collections, copy, hashlib, json, os, random, re, sys
13
+
14
+ HERE = os.path.dirname(os.path.abspath(__file__))
15
+ sys.path.insert(0, HERE)
16
+ import kevdata
17
+
18
+ # hata oranına göre ağırlık (AUBIN Duo'nun dev'de en zayıf olduğu kaynaklar daha çok örnek alır)
19
+ WEIGHT = {"sst5": 2.0, "yelp": 2.0, "amazon": 2.0, "banking77": 1.5, "trec": 1.0, "agnews": 1.0, "mnli": 1.0,
20
+ "imdb": 0.75, "dbpedia14": 0.75, "boolq": 1.0}
21
+
22
+
23
+ def clean(s):
24
+ return re.sub(r"<br\s*/?>", " ", str(s))
25
+
26
+
27
+ def norm(s):
28
+ return re.sub(r"\s+", " ", clean(s)).strip().lower()
29
+
30
+
31
+ def h(s):
32
+ return hashlib.sha256(norm(s).encode()).hexdigest()
33
+
34
+
35
+ def state_text(st):
36
+ return json.dumps(st, ensure_ascii=False, sort_keys=True) if isinstance(st, (dict, list)) else str(st)
37
+
38
+
39
+ def builders(row):
40
+ """Bir veri seti satırından aday durum kurucular: tek alan ve iki alanlı birleşimler."""
41
+ strs = {k: v for k, v in row.items() if isinstance(v, str) and v.strip()}
42
+ out = {f"f:{k}": (lambda r, k=k: r[k]) for k in strs}
43
+ ks = list(strs)
44
+ for a in ks:
45
+ for b in ks:
46
+ if a != b:
47
+ for sep in (" ", "\n", "\n\n", ". ", ": ", " - "):
48
+ out[f"j:{a}|{b}|{sep}"] = (lambda r, a=a, b=b, sep=sep: r[a] + sep + r[b])
49
+ return out
50
+
51
+
52
+ def learn_builder(recs, ds):
53
+ """Durum = alan (temizlenmiş) ya da onun başı (Kev uzun metinleri kısaltmış olabilir). Dönüş: (ad, eşleşme, azami uzunluk)."""
54
+ votes, maxlen = collections.Counter(), 0
55
+ for r in recs[:200]:
56
+ row = ds[int(r["_meta"]["row"])]
57
+ st = r["state"]
58
+ if not isinstance(st, str):
59
+ continue
60
+ maxlen = max(maxlen, len(st))
61
+ for name, f in builders(row).items():
62
+ try:
63
+ full, s = norm(f(row)), norm(st)
64
+ if full == s or (len(s) >= 200 and full.startswith(s[: max(1, len(s) - 3)].rstrip(". "))):
65
+ votes[name] += 1
66
+ except Exception:
67
+ pass
68
+ if not votes:
69
+ return None, 0, 0
70
+ name, n = votes.most_common(1)[0]
71
+ return name, n, maxlen
72
+
73
+
74
+ def make_builder(name, maxlen=0):
75
+ if name.startswith("f:"):
76
+ k = name[2:]
77
+ raw = lambda r: r[k]
78
+ else:
79
+ a, b, sep = name[2:].split("|", 2)
80
+ raw = lambda r: r[a] + sep + r[b]
81
+
82
+ def f(r):
83
+ s = re.sub(r"[ \t]+", " ", clean(raw(r))).strip()
84
+ if maxlen and len(s) > maxlen: # Kev'in en uzun durumu kadar, kelime sınırında kes
85
+ s = s[:maxlen].rsplit(" ", 1)[0]
86
+ return s
87
+ return f
88
+
89
+
90
+ def q_text(q):
91
+ ins = q.get("instructions")
92
+ return ins.get("question", "") if isinstance(ins, dict) else (ins or "")
93
+
94
+
95
+ def set_q_text(q, old, new):
96
+ ins = q.get("instructions")
97
+ if isinstance(ins, dict):
98
+ ins = dict(ins); ins["question"] = ins.get("question", "").replace(old, new); q["instructions"] = ins
99
+ else:
100
+ q["instructions"] = (ins or "").replace(old, new)
101
+
102
+
103
+ def learn_maps(recs, ds):
104
+ """Her soru anahtarı için: (orijinal etiket alanı, eşleme sözlüğü) ve soru metnine giren alan."""
105
+ maps, qfield = {}, {}
106
+ qkeys = collections.Counter(k for r in recs for k in r["questions"])
107
+ for qk, _ in qkeys.items():
108
+ rows = [(r, ds[int(r["_meta"]["row"])]) for r in recs if qk in r["questions"]][:600]
109
+ best = None
110
+ n_lab = len({json.dumps(r["questions"][qk]["label"]) for r, _ in rows})
111
+ cand = [k for k, v in rows[0][1].items() if isinstance(v, (int, bool)) or (isinstance(v, str) and len(v) < 40)]
112
+ for f in cand:
113
+ n_val = len({json.dumps(row.get(f)) for _, row in rows})
114
+ if n_val > max(30, 3 * n_lab) or n_val > 0.5 * len(rows): # kimlik/metin gibi her satırda farklı alanlar etiket olamaz
115
+ continue
116
+ m, ok, bad = {}, 0, 0
117
+ for r, row in rows:
118
+ o, lab = row.get(f), r["questions"][qk]["label"]
119
+ key = json.dumps(o)
120
+ if key in m and m[key] != lab:
121
+ bad += 1
122
+ else:
123
+ m[key] = lab; ok += 1
124
+ score = ok - 5 * bad
125
+ if bad <= 0.01 * len(rows) and (best is None or score > best[0]):
126
+ best = (score, f, m)
127
+ if best:
128
+ maps[qk] = (best[1], best[2])
129
+ # satıra özgü soru metni (ör. MNLI hipotezi, BoolQ sorusu)
130
+ for f, v in rows[0][1].items():
131
+ if isinstance(v, str) and len(v) > 8 and all(
132
+ norm(row.get(f, "")) and norm(row.get(f, "")) in norm(q_text(r["questions"][qk])) for r, row in rows[:50]):
133
+ qfield[qk] = f
134
+ break
135
+ return maps, qfield
136
+
137
+
138
+ def main():
139
+ ap = argparse.ArgumentParser()
140
+ ap.add_argument("--work", default="/tmp/kev"); ap.add_argument("--per_source", type=int, default=4000)
141
+ ap.add_argument("--out", default="kev_extra.jsonl"); ap.add_argument("--seed", type=int, default=0)
142
+ a = ap.parse_args()
143
+ from datasets import load_dataset
144
+ paths = kevdata.fetch(a.work)
145
+ raw = {k: [json.loads(l) for l in open(p, encoding="utf-8")] for k, p in paths.items()}
146
+ excl = {h(state_text(r["state"])) for rs in raw.values() for r in rs}
147
+ used = collections.defaultdict(set)
148
+ for rs in raw.values():
149
+ for r in rs:
150
+ m = r.get("_meta", {})
151
+ if m.get("repo") and m.get("row") is not None:
152
+ used[(m["repo"], m.get("split"))].add(int(m["row"]))
153
+ by_src = collections.defaultdict(list)
154
+ for r in raw["kev_train"]:
155
+ m = r["_meta"]
156
+ if m.get("repo") and m.get("split") == "train" and m.get("row") is not None and isinstance(r["state"], str):
157
+ by_src[m["source"]].append(r)
158
+ rng = random.Random(a.seed); out, report = [], {}
159
+ for src, recs in sorted(by_src.items()):
160
+ m0 = recs[0]["_meta"]
161
+ try:
162
+ ds = load_dataset(m0["repo"], split="train", revision=m0.get("revision"))
163
+ except Exception as e:
164
+ report[src] = f"veri seti yüklenemedi: {e}"[:160]; continue
165
+ bname, bn, maxlen = learn_builder(recs, ds)
166
+ if not bname or bn < 0.85 * min(200, len(recs)):
167
+ report[src] = f"durum kurucu bulunamadı ({bname}, {bn})"; continue
168
+ build = make_builder(bname, maxlen)
169
+ maps, qfield = learn_maps(recs, ds)
170
+ # doğrulama: eşleme Kev'in TÜM satırlarında doğru etiketi veriyor mu (≥ %98 değilse o soru kullanılmaz)
171
+ verify = {}
172
+ for qk, (f, mp) in list(maps.items()):
173
+ rs = [r for r in recs if qk in r["questions"]]
174
+ hit = sum(mp.get(json.dumps(ds[int(r["_meta"]["row"])].get(f))) == r["questions"][qk]["label"] for r in rs)
175
+ verify[qk] = round(hit / max(1, len(rs)), 4)
176
+ if verify[qk] < 0.98:
177
+ maps.pop(qk)
178
+ if not maps:
179
+ report[src] = {"etiket eşlemesi doğrulanmadı": verify}; continue
180
+ n_want = int(a.per_source * WEIGHT.get(src, 1.0))
181
+ idx = [i for i in range(len(ds)) if i not in used[(m0["repo"], "train")]]
182
+ rng.shuffle(idx); made = 0
183
+ for i in idx:
184
+ if made >= n_want:
185
+ break
186
+ row = ds[i]
187
+ try:
188
+ st = build(row)
189
+ except Exception:
190
+ continue
191
+ if not isinstance(st, str) or len(st) < 3 or h(st) in excl:
192
+ continue
193
+ tpl = rng.choice(recs)
194
+ qs = {}
195
+ for qk, q in tpl["questions"].items():
196
+ if qk not in maps:
197
+ continue
198
+ f, mp = maps[qk]
199
+ key = json.dumps(row.get(f))
200
+ if key not in mp:
201
+ continue
202
+ q2 = copy.deepcopy(q); q2["label"] = mp[key]
203
+ if qk in qfield:
204
+ old = tpl_row_val = None
205
+ trow = ds[int(tpl["_meta"]["row"])]
206
+ old = trow.get(qfield[qk]); new = row.get(qfield[qk])
207
+ if not old or not new or norm(old) not in norm(q_text(q2)):
208
+ continue
209
+ set_q_text(q2, old, new)
210
+ qs[qk] = q2
211
+ if not qs:
212
+ continue
213
+ excl.add(h(st))
214
+ out.append({"state": st, "questions": qs,
215
+ "_meta": {"source": src, "repo": m0["repo"], "split": "train", "row": i, "id": f"aug/{src}/{i}",
216
+ "variant": "aug", "template": tpl["_meta"].get("id")}})
217
+ made += 1
218
+ report[src] = {"made": made, "builder": bname, "maxlen": maxlen, "verify": verify, "questions": {k: v[0] for k, v in maps.items()},
219
+ "qfield": qfield, "pool": len(idx)}
220
+ print(src, json.dumps(report[src], ensure_ascii=False)[:300], flush=True)
221
+ with open(a.out, "w", encoding="utf-8") as f:
222
+ for r in out:
223
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
224
+ json.dump(report, open(a.out + ".report.json", "w"), indent=1, ensure_ascii=False)
225
+ print("YAZILDI", a.out, len(out), flush=True)
226
+
227
+
228
+ if __name__ == "__main__":
229
+ main()
code/kev_llm.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN by Norovox — açık-tabanlı karar modeli, Kev'in AÇIK paketleriyle AYNI protokolde ölçülür.
2
+
3
+ Tipli soru → tek ileri geçiş → seçenek olasılıkları (metin üretimi yok). Seçenekler harflerle listelenir, cevap
4
+ konumundaki harf logitleri okunur (>26 seçenekte 26'lık gruplar + final turu). Sıcaklık decision-v7 calibration'da.
5
+ Eğitim (--train): LoRA, kayıp = harf logitleri üzerinde çapraz-entropi (Kev'in pointer-head'inin LM-başlı karşılığı).
6
+ Kev'in transfer kaynakları (mmlu, sciq, qnli, paws, emotion, tweet_offensive...) EĞİTİMDE ASLA kullanılmaz.
7
+
8
+ python kev_llm.py --model google/gemma-4-12B-it --suites kev_transfer_test,kev_test --out r.json [--train N --adapter out/]
9
+ """
10
+ import argparse, json, math, os, random, sys, time
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn.functional as F
14
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
15
+ import kevdata
16
+
17
+ L = [chr(65 + i) for i in range(26)]
18
+
19
+
20
+ def options(q):
21
+ t, c = q["type"], q.get("criteria")
22
+ if t == "noul":
23
+ keys = ["false", "true"]
24
+ if isinstance(c, dict):
25
+ return keys, [f"false — {c.get('false', 'no')}", f"true — {c.get('true', 'yes')}"]
26
+ return keys, ["false — no", "true — yes"]
27
+ if t == "choice":
28
+ keys = list(c.keys())
29
+ return keys, [f"{k}: {v}" for k, v in c.items()]
30
+ if isinstance(c, list):
31
+ return [str(i) for i in range(len(c))], [str(v) for v in c]
32
+ keys = list(c.keys())
33
+ return keys, [f"{k}: {v}" for k, v in c.items()]
34
+
35
+
36
+ def items(cases):
37
+ out = []
38
+ for c in cases:
39
+ st = json.dumps(c["state"], ensure_ascii=False)
40
+ for qid, q in c["questions"].items():
41
+ keys, texts = options(q)
42
+ lab = str(c["gold"][qid]["label"])
43
+ if lab not in keys:
44
+ continue
45
+ out.append({"key": f"{c['id']}/{qid}", "src": c["source"], "state": st, "q": q.get("instructions") or qid, "type": q["type"],
46
+ "keys": keys, "texts": texts, "y": keys.index(lab)})
47
+ return out
48
+
49
+
50
+ class Scorer:
51
+ def __init__(self, model_id, four_bit=True, max_state=6000, device_map=""):
52
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
53
+ self.tok = AutoTokenizer.from_pretrained(model_id)
54
+ self.dev = "cuda:0" if torch.cuda.is_available() else "cpu"
55
+ kw = dict(device_map=device_map or self.dev, dtype=torch.float16 if self.dev != "cpu" else torch.float32)
56
+ if device_map == "auto" and torch.cuda.device_count() > 1: # 31B 4-bit iki T4'e bölünür
57
+ kw["max_memory"] = {i: "13GiB" for i in range(torch.cuda.device_count())}
58
+ if four_bit:
59
+ kw["quantization_config"] = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
60
+ bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True)
61
+ try:
62
+ self.m = AutoModelForCausalLM.from_pretrained(model_id, **kw)
63
+ except Exception as e:
64
+ print("[AutoModelForCausalLM olmadı]", str(e)[:200], flush=True)
65
+ from transformers import AutoModelForImageTextToText
66
+ self.m = AutoModelForImageTextToText.from_pretrained(model_id, **kw)
67
+ self.m.eval()
68
+ self.max_state = max_state
69
+ self.letter_ids = []
70
+ for a in L:
71
+ ids = {self.tok.encode(a, add_special_tokens=False)[0], self.tok.encode(" " + a, add_special_tokens=False)[-1]}
72
+ self.letter_ids.append(sorted(ids))
73
+
74
+ def prompt(self, it, idx):
75
+ st = it["state"]
76
+ if len(st) > self.max_state:
77
+ st = st[: self.max_state] + " …"
78
+ opts = "\n".join(f"{L[j]}) {it['texts'][i]}" for j, i in enumerate(idx))
79
+ u = (f"Decide based ONLY on the state below.\n\nSTATE:\n{st}\n\nQUESTION: {it['q']}\n\nOPTIONS:\n{opts}\n\n"
80
+ f"Reply with the single letter of the correct option.")
81
+ msgs = [{"role": "user", "content": u}]
82
+ try:
83
+ p = self.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False, enable_thinking=False)
84
+ except Exception:
85
+ p = self.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
86
+ return p + "Answer: "
87
+
88
+ def think_prompt(self, it):
89
+ """Eminsiz sorular için: kısa akıl yürütme, sonra 'Answer: <harf>'."""
90
+ st = it["state"] if len(it["state"]) <= self.max_state else it["state"][: self.max_state] + " …"
91
+ opts = "\n".join(f"{L[j]}) {t}" for j, t in enumerate(it["texts"]))
92
+ u = (f"Decide based ONLY on the state below.\n\nSTATE:\n{st}\n\nQUESTION: {it['q']}\n\nOPTIONS:\n{opts}\n\n"
93
+ f"Think briefly step by step (at most 6 short sentences), weighing the most plausible options. "
94
+ f"Then write the final line exactly as 'Answer: <letter>'.")
95
+ msgs = [{"role": "user", "content": u}]
96
+ try:
97
+ return self.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False, enable_thinking=False)
98
+ except Exception:
99
+ return self.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
100
+
101
+ @torch.no_grad()
102
+ def think_scores(self, its, max_new=256, bs=8, samples=1, temp=0.7):
103
+ """Toplu akıl yürütme üretimi → 'Answer: ' konumunda harf logitleri. Dönüş: soru-başı log-olasılık listesi.
104
+ samples>1: self-consistency — açgözlü yol + (samples-1) örneklenmiş akıl yürütme; cevap olasılıkları ortalanır."""
105
+ out = []
106
+ for i in range(0, len(its), bs):
107
+ batch = its[i:i + bs]
108
+ ps = [self.think_prompt(it) for it in batch]
109
+ enc = self.tok(ps, return_tensors="pt", padding=True, add_special_tokens=False).to(self.dev)
110
+ runs = [self.m.generate(**enc, max_new_tokens=max_new, do_sample=False, pad_token_id=self.tok.pad_token_id)]
111
+ for _ in range(samples - 1):
112
+ runs.append(self.m.generate(**enc, max_new_tokens=max_new, do_sample=True, temperature=temp, top_p=0.95,
113
+ pad_token_id=self.tok.pad_token_id))
114
+ probs = [None] * len(batch)
115
+ for gen in runs:
116
+ texts = self.tok.batch_decode(gen[:, enc["input_ids"].shape[1]:], skip_special_tokens=True)
117
+ conts = []
118
+ for p, t in zip(ps, texts):
119
+ k = t.find("Answer:")
120
+ reason = (t[:k] if k >= 0 else t).rstrip()
121
+ conts.append(p + reason + "\nAnswer: ")
122
+ lg = self.letter_logits(conts)
123
+ for b, it in enumerate(batch):
124
+ pr = torch.softmax(lg[b, :len(it["keys"])].float().cpu(), -1)
125
+ probs[b] = pr if probs[b] is None else probs[b] + pr
126
+ for b in range(len(batch)):
127
+ out.append(torch.log(probs[b] / len(runs) + 1e-12))
128
+ return out
129
+
130
+ def letter_logits(self, prompts, grad=False):
131
+ enc = self.tok(prompts, return_tensors="pt", padding=True, add_special_tokens=False).to(self.dev)
132
+ ctx = torch.enable_grad() if grad else torch.no_grad()
133
+ with ctx:
134
+ try: # yalnız son konumun logiti (262k sözlükte tüm konumlar = GB'larca bellek)
135
+ out = self.m(**enc, logits_to_keep=1)
136
+ except TypeError:
137
+ out = self.m(**enc)
138
+ last = out.logits[:, -1].float()
139
+ return torch.stack([last[:, ids].logsumexp(-1) for ids in self.letter_ids], -1) # [B, 26]
140
+
141
+ def score(self, it, perms=1):
142
+ n = len(it["keys"])
143
+ idx = list(range(n))
144
+ if n <= 26:
145
+ # konum yanlılığına karşı: P döngüsel kaydırmada sorulur, seçenek-başı log-olasılıkların ortalaması
146
+ acc = torch.zeros(n)
147
+ shifts = sorted({(k * n) // perms for k in range(perms)})
148
+ for s in shifts:
149
+ order = idx[s:] + idx[:s]
150
+ lg = torch.log_softmax(self.letter_logits([self.prompt(it, order)])[0, :n].cpu(), -1)
151
+ back = torch.empty(n); back[torch.tensor(order)] = lg
152
+ acc += back
153
+ return acc / len(shifts)
154
+ # >26 seçenek: 26'lık gruplar, her grubun en iyisi finalde yarışır; olasılık final dağılımından
155
+ winners, full = [], torch.full((n,), -1e4)
156
+ for s in range(0, n, 26):
157
+ g = idx[s:s + 26]
158
+ lg = self.letter_logits([self.prompt(it, g)])[0, :len(g)].cpu()
159
+ full[torch.tensor(g)] = lg
160
+ winners.append(g[int(lg.argmax())])
161
+ lg = self.letter_logits([self.prompt(it, winners)])[0, :len(winners)].cpu()
162
+ full[torch.tensor(winners)] = lg + 50.0
163
+ return full
164
+
165
+
166
+ def metrics(rows, T=1.0):
167
+ by, allr = {}, []
168
+ for it, lg in rows:
169
+ p = F.softmax(lg / T, -1).numpy()
170
+ ok = int(p.argmax()) == it["y"]; oh = np.zeros(len(p)); oh[it["y"]] = 1
171
+ r = (ok, float(((p - oh) ** 2).sum()), float(p.max()), float(-math.log(max(p[it["y"]], 1e-12))))
172
+ allr.append(r); by.setdefault(it["src"], []).append(r)
173
+ def m(v):
174
+ ece = 0.0
175
+ for j in range(15):
176
+ bb = [x for x in v if j / 15 < x[2] <= (j + 1) / 15]
177
+ if bb:
178
+ ece += len(bb) / len(v) * abs(np.mean([x[2] for x in bb]) - np.mean([x[0] for x in bb]))
179
+ return {"n": len(v), "accuracy": round(float(np.mean([x[0] for x in v])), 4), "brier": round(float(np.mean([x[1] for x in v])), 4),
180
+ "nll": round(float(np.mean([x[3] for x in v])), 4), "ece15": round(float(ece), 4)}
181
+ return {"all": m(allr), "by_source": {k: m(v) for k, v in sorted(by.items())}}
182
+
183
+
184
+ def resolve_adapter(path):
185
+ """Adaptör dizinini bul: verilen yol yoksa /kaggle/input altında aynı adlı (adapter_config.json içeren) dizini ara."""
186
+ import glob
187
+ if not path or os.path.exists(os.path.join(path, "adapter_config.json")):
188
+ return 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
+ 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)]
197
+ named = [h for h in hits if os.path.basename(h) == base]
198
+ found = (named or hits or [path])[0]
199
+ print("[adaptör yolu]", path, "->", found, "| adaylar:", hits[:6], flush=True)
200
+ return found
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="", wide=False):
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ı
208
+ big = sum(p.numel() for p in S.m.parameters() if p.dtype in (torch.float16, torch.bfloat16, torch.float32))
209
+ if big > 1.5e9 or os.environ.get("AUBIN_LIGHT_PREP") == "1": # 31B: gömme tablosu 1,41e9 → fp32'ye çevrilirse 5,25 GB OOM
210
+ for p in S.m.parameters():
211
+ p.requires_grad_(False)
212
+ if p.dtype == torch.float16 and p.numel() < 5e7: # norm vb. küçük parçalar fp32 (kararlılık), dev tablolar fp16 kalır
213
+ p.data = p.data.float()
214
+ S.m.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
215
+ S.m.enable_input_require_grads()
216
+ print({"light_kbit_prep": True, "unquantized_params": big}, flush=True)
217
+ else:
218
+ S.m = prepare_model_for_kbit_training(S.m, use_gradient_checkpointing=True)
219
+ cfg = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM",
220
+ # yalnız dil katmanları (görsel/ses kulesindeki özel Linear türleri hariç)
221
+ # Phi-3/4 ailesi birleşik katmanlar kullanır (qkv_proj, gate_up_proj)
222
+ target_modules=r"^(?!.*(vision|audio|siglip|embed_vision|embed_audio)).*\.(q_proj|k_proj|v_proj|qkv_proj|o_proj|gate_proj|up_proj|gate_up_proj|down_proj)$")
223
+ if init_adapter: # önceki turun adaptöründen devam
224
+ from peft import PeftModel
225
+ S.m = PeftModel.from_pretrained(S.m, init_adapter, is_trainable=True)
226
+ else:
227
+ S.m = get_peft_model(S.m, cfg)
228
+ S.m.print_trainable_parameters()
229
+ opt = torch.optim.AdamW([p for p in S.m.parameters() if p.requires_grad], lr=lr, weight_decay=0.0)
230
+ rng = random.Random(seed); pool = [x for x in tr if len(x["keys"]) <= 26 or wide] # wide: >26 seçenekli sorular da (banking77)
231
+ if teacher: # damıtmada yalnız öğretmenin etiketlediği sorular (yumuşak etiket her örnekte)
232
+ pool = [x for x in pool if x["key"] in teacher or x["key"].startswith("kev_extra/")] # ek veri: sert etiketle
233
+ print({"distill_pool": len(pool)}, flush=True)
234
+ if mine: # zor-örnek madenciliği: model neyi bilmiyorsa onu çalış
235
+ S.m.eval(); cand = rng.sample(pool, min(mine, len(pool))); hard, easy = [], []
236
+ t1 = time.time()
237
+ for i, it in enumerate(cand):
238
+ pc = float(F.softmax(S.score(it), -1)[it["y"]])
239
+ (hard if pc < mine_thr else easy).append(it)
240
+ if i % 500 == 0:
241
+ print({"mine": i, "hard": len(hard), "min": round((time.time() - t1) / 60, 1)}, flush=True)
242
+ rng.shuffle(easy)
243
+ pool = hard + easy[: max(1, len(hard) // 4)] # zorların yanında %20 kolay: unutmayı önler
244
+ print({"mined": len(cand), "hard": len(hard), "pool": len(pool)}, flush=True)
245
+ # uzunluğa göre kovalar: batch içindeki dolgu (boşa hesap) en aza iner
246
+ plen = lambda it: len(it["state"]) + sum(len(t) for t in it["texts"]) + len(it["q"])
247
+ srt = sorted(pool, key=plen); B = max(bs * 8, 32)
248
+ buckets = [srt[i:i + B] for i in range(0, len(srt), B)]
249
+ best = (-1.0, 0, None)
250
+ if dev: # başlangıç (eğitimsiz) dev doğruluğu: taban çizgisi
251
+ S.m.eval()
252
+ init_state = None
253
+ if init_adapter: # devam eğitimi: iyileşme olmazsa BAŞLANGIÇ adaptörü geri yüklenir (sıfırlanmaz)
254
+ from peft import get_peft_model_state_dict
255
+ init_state = {k: v.detach().cpu().clone() for k, v in get_peft_model_state_dict(S.m).items()}
256
+ hits0 = [int(S.score(it).argmax()) == it["y"] for it in dev]
257
+ best = (float(np.mean(hits0)), 0, init_state)
258
+ print({"dev_step": 0, "dev_acc": round(best[0], 4)}, flush=True)
259
+ if data_value: # veri değeri: hesap, modelin seçim bölümünde zayıf olduğu kaynaklara kayar
260
+ err = {}
261
+ for it, h in zip(dev, hits0):
262
+ err.setdefault(it["src"], []).append(1 - h)
263
+ w = {s: (float(np.mean(v)) + 0.03) for s, v in err.items()}
264
+ mw = float(np.mean(list(w.values())))
265
+ w = {s: min(4.0, max(0.25, v / mw)) for s, v in w.items()}
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 = []
294
+ for it in batch: # seçenek sırası karıştırılır: konum yanlılığı öğrenilmez
295
+ n = len(it["keys"])
296
+ if n <= 26:
297
+ idx = list(range(n))
298
+ else: # geniş soru: doğru + rastgele çeldiriciler (≤26) — testteki 26'lık grup
299
+ k = 26 if rng.random() < 0.75 else rng.randint(2, 6) # turu (%75) ve az seçenekli final turu (%25) birebir çalışılır
300
+ idx = rng.sample([j for j in range(n) if j != it["y"]], k - 1) + [it["y"]]
301
+ rng.shuffle(idx); perms.append(idx)
302
+ lg = S.letter_logits([S.prompt(it, idx) for it, idx in zip(batch, perms)], grad=True)
303
+ loss = 0.0
304
+ for b, (it, idx) in enumerate(zip(batch, perms)):
305
+ ce = F.cross_entropy(lg[b, :len(idx)].unsqueeze(0), torch.tensor([idx.index(it["y"])], device=lg.device))
306
+ if teacher and it["key"] in teacher and len(teacher[it["key"]]) == len(it["keys"]) and len(idx) == len(it["keys"]): # damıtma: öğretmenin (AUBIN-31B) dağılımı, öğrencinin sırasına çevrilir
307
+ tq = torch.softmax(torch.tensor(teacher[it["key"]], dtype=torch.float32), -1)[torch.tensor(idx)].to(lg.device)
308
+ kd = -(tq * F.log_softmax(lg[b, :len(idx)], -1)).sum()
309
+ ce = (1 - alpha) * ce + alpha * kd
310
+ loss = loss + ce
311
+ loss = loss / bs
312
+ for g in opt.param_groups:
313
+ g["lr"] = lr * min(1.0, (step + 1) / 30) * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * step / steps)))
314
+ opt.zero_grad(set_to_none=True); loss.backward()
315
+ torch.nn.utils.clip_grad_norm_([p for p in S.m.parameters() if p.requires_grad], 1.0); opt.step()
316
+ if step % 20 == 0:
317
+ print({"step": step, "loss": round(float(loss), 4), "min": round((time.time() - t0) / 60, 1)}, flush=True)
318
+ if dev and ((step + 1) % eval_every == 0 or step == steps - 1): # çöküşe karşı: en iyi dev adaptörü tutulur
319
+ S.m.eval()
320
+ acc = float(np.mean([int(S.score(it).argmax()) == it["y"] for it in dev]))
321
+ S.m.train()
322
+ print({"dev_step": step + 1, "dev_acc": round(acc, 4), "best": round(best[0], 4)}, flush=True)
323
+ if acc > best[0]:
324
+ from peft import get_peft_model_state_dict
325
+ best = (acc, step + 1, {k: v.detach().cpu().clone() for k, v in get_peft_model_state_dict(S.m).items()})
326
+ if save_every and (step + 1) % save_every == 0 and step + 1 < steps:
327
+ checkpoint(step + 1)
328
+ S.m.eval()
329
+ if dev and best[2] is not None:
330
+ from peft import set_peft_model_state_dict
331
+ set_peft_model_state_dict(S.m, best[2]); print({"best_dev_step": best[1], "best_dev_acc": round(best[0], 4)}, flush=True)
332
+ elif dev: # eğitim tabanı hiç geçemedi: adaptör etkisiz (lora_B = 0) → ham taban
333
+ with torch.no_grad():
334
+ for n_, p_ in S.m.named_parameters():
335
+ if "lora_B" in n_:
336
+ p_.zero_()
337
+ print({"best_dev_step": 0, "note": "eğitim tabanı geçemedi; adaptör sıfırlandı"}, flush=True)
338
+ S.best_dev = best[:2] if dev else None
339
+ if out_dir:
340
+ S.m.save_pretrained(out_dir)
341
+
342
+
343
+ def main():
344
+ ap = argparse.ArgumentParser()
345
+ ap.add_argument("--model", default="google/gemma-4-12B-it"); ap.add_argument("--work", default="/tmp/kev")
346
+ ap.add_argument("--suites", default="kev_transfer_test,kev_test"); ap.add_argument("--out", default="aubin_kev.json")
347
+ ap.add_argument("--limit", type=int, default=0); ap.add_argument("--no4bit", action="store_true")
348
+ ap.add_argument("--train", type=int, default=0); ap.add_argument("--lr", type=float, default=1e-4)
349
+ ap.add_argument("--bs", type=int, default=4); ap.add_argument("--adapter", default="")
350
+ ap.add_argument("--cal", type=int, default=300); ap.add_argument("--perms", type=int, default=1); ap.add_argument("--seed", type=int, default=0)
351
+ ap.add_argument("--eval_before", action="store_true"); ap.add_argument("--device_map", default="")
352
+ ap.add_argument("--init_adapter", default=""); ap.add_argument("--mine", type=int, default=0)
353
+ ap.add_argument("--dev_n", type=int, default=0); ap.add_argument("--eval_every", type=int, default=100)
354
+ ap.add_argument("--think_margin", type=float, default=0.0); ap.add_argument("--think_tokens", type=int, default=256)
355
+ ap.add_argument("--think_bs", type=int, default=8)
356
+ ap.add_argument("--think_samples", type=int, default=1); ap.add_argument("--think_temp", type=float, default=0.7)
357
+ ap.add_argument("--label_train", type=int, default=0); ap.add_argument("--teacher", default=""); ap.add_argument("--alpha", type=float, default=0.5)
358
+ ap.add_argument("--dev_src", default="dev", choices=["dev", "cal"]); ap.add_argument("--data_value", action="store_true")
359
+ ap.add_argument("--train_only", action="store_true"); ap.add_argument("--label_offset", type=int, default=0)
360
+ ap.add_argument("--save_every", type=int, default=0); ap.add_argument("--resume", default="")
361
+ ap.add_argument("--wide", action="store_true") # >26 seçenekli soruları (banking77, 77 sınıf) da eğit ve seç
362
+ ap.add_argument("--no_extra", action="store_true") # karşılaştırma: KEV_EXTRA_TRAIN ek verisi bu süreçte kullanılmaz
363
+ a = ap.parse_args()
364
+ if a.no_extra:
365
+ os.environ.pop("KEV_EXTRA_TRAIN", None)
366
+ a.init_adapter = resolve_adapter(a.init_adapter)
367
+ K = kevdata.load(a.work)
368
+ assert not ({c["source"] for c in K["kev_train"]} & kevdata.HOLDOUT)
369
+ S = Scorer(a.model, four_bit=not a.no4bit, device_map=a.device_map)
370
+ S.tok.padding_side = "left"
371
+ if S.tok.pad_token is None:
372
+ S.tok.pad_token = S.tok.eos_token
373
+ R = {"model": a.model, "protocol": "Kev açık paketleri; harf-logit tek geçiş; sıcaklık decision-v7 calibration", "runs": {}}
374
+ R["perms"] = a.perms
375
+
376
+ def think(rows):
377
+ """Eminsiz (en iyi iki log-olasılık farkı < marj) sorular: akıl yürütmeli ikinci geçiş ile değiştirilir."""
378
+ if not a.think_margin:
379
+ return rows, 0
380
+ def marg(lg):
381
+ v = torch.sort(torch.log_softmax(lg.float(), -1), descending=True).values
382
+ return float(v[0] - v[1]) if len(v) > 1 else 99.0
383
+ sel = [i for i, (it, lg) in enumerate(rows) if len(it["keys"]) <= 26 and marg(lg) < a.think_margin]
384
+ if not sel:
385
+ return rows, 0
386
+ new = S.think_scores([rows[i][0] for i in sel], a.think_tokens, a.think_bs, a.think_samples, a.think_temp)
387
+ rows = list(rows)
388
+ for i, lg in zip(sel, new):
389
+ rows[i] = (rows[i][0], lg)
390
+ return rows, len(sel)
391
+
392
+ def eval_all(tag):
393
+ rng = random.Random(0)
394
+ cal = items(K["kev_cal"]); rng.shuffle(cal); cal = cal[: a.cal]
395
+ cal_rows = [(it, S.score(it, a.perms)) for it in cal]
396
+ cal_rows, nth = think(cal_rows); print(f"[{tag}] kalibrasyonda düşünülen soru:", nth, flush=True)
397
+ T = min(np.concatenate([np.arange(0.3, 4.0, 0.05), np.arange(4.0, 20.01, 0.25)]), key=lambda t: metrics(cal_rows, t)["all"]["nll"])
398
+ R[tag + "_temperature"] = round(float(T), 2)
399
+ R[tag + "_cal_items"] = [{"y": it["y"], "lp": [round(float(x), 4) for x in torch.log_softmax(lg.float(), -1)]} for it, lg in cal_rows]
400
+ print(f"[{tag} kalibrasyon] T =", R[tag + "_temperature"], flush=True)
401
+ R.setdefault(tag, {})
402
+ for s in a.suites.split(","):
403
+ its = items(K[s])
404
+ if a.limit:
405
+ rng.shuffle(its); its = its[: a.limit]
406
+ t0 = time.time(); rows = []
407
+ for i, it in enumerate(its):
408
+ rows.append((it, S.score(it, a.perms)))
409
+ if i % 100 == 0:
410
+ print(tag, s, i, len(its), round(time.time() - t0), "s", flush=True)
411
+ fast = rows
412
+ t1 = time.time(); rows, nth = think(rows)
413
+ r = metrics(rows, T); r["raw_T1"] = metrics(rows, 1.0)["all"]
414
+ if nth:
415
+ r["fast_only"] = metrics(fast, T)["all"]; r["thought"] = nth; r["think_seconds"] = round(time.time() - t1, 1)
416
+ r["fast_items"] = [[round(float(x), 4) for x in torch.log_softmax(lg.float(), -1)] for _, lg in fast]
417
+ # soru-başı ham log-olasılıklar (ansambl / sonradan kalibrasyon GPU'suz yapılabilsin)
418
+ r["items"] = [{"src": it["src"], "y": it["y"], "lp": [round(float(x), 4) for x in torch.log_softmax(lg.float(), -1)]}
419
+ for it, lg in rows]
420
+ r["seconds"] = round(time.time() - t0, 1)
421
+ R[tag][s] = r
422
+ print(tag, s, json.dumps(r["all"]), flush=True)
423
+ json.dump(R, open(a.out, "w"), indent=1)
424
+
425
+ if a.teacher and not os.path.exists(a.teacher): # Kaggle kernel kaynağı yolu hesaba göre değişir
426
+ import glob
427
+ a.teacher = (glob.glob("/kaggle/input/**/" + os.path.basename(a.teacher), recursive=True) or [a.teacher])[0]
428
+ print("[öğretmen yolu]", a.teacher, flush=True)
429
+ teach = json.load(open(a.teacher)) if a.teacher else None
430
+ if a.label_train: # öğretmen modu: eğitim sorularının log-olasılıkları → dosya
431
+ if a.init_adapter:
432
+ from peft import PeftModel
433
+ S.m = PeftModel.from_pretrained(S.m, a.init_adapter).eval()
434
+ pool = [x for x in items(K["kev_train"]) if len(x["keys"]) <= 26]; random.Random(11).shuffle(pool)
435
+ lab, t0 = {}, time.time()
436
+ for i, it in enumerate(pool[a.label_offset: a.label_offset + a.label_train]): # aralık: hesaplar arası bölüşüm
437
+ lab[it["key"]] = [round(float(v), 4) for v in S.score(it)]
438
+ if i % 200 == 0:
439
+ print({"label": i, "min": round((time.time() - t0) / 60, 1)}, flush=True)
440
+ json.dump(lab, open(a.out, "w"))
441
+ json.dump(lab, open(a.out, "w")); print("ETIKETLEME BITTI", len(lab), flush=True)
442
+ return
443
+ if a.init_adapter and not a.train: # yalnız değerlendirme: eğitilmiş adaptörle ölç
444
+ from peft import PeftModel
445
+ S.m = PeftModel.from_pretrained(S.m, a.init_adapter).eval()
446
+ R["adapter"] = a.init_adapter
447
+ if a.eval_before:
448
+ eval_all("zeroshot")
449
+ if a.train:
450
+ if a.dev_src == "cal": # seçim kalibrasyon bölümünde: Jev'le kıyaslanan dev kümesine hiç dokunulmaz
451
+ devs = items(K["kev_cal"]); random.Random(0).shuffle(devs)
452
+ devs = devs[a.cal:] if len(devs) - a.cal >= a.dev_n else devs[::-1]
453
+ else:
454
+ devs = items(K["kev_dev"]); random.Random(5).shuffle(devs)
455
+ 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,
456
+ dev=[d for d in devs if len(d["keys"]) <= 26 or a.wide][: a.dev_n] if a.dev_n else None, eval_every=a.eval_every,
457
+ teacher=teach, alpha=a.alpha, data_value=a.data_value, save_every=a.save_every, resume=a.resume, wide=a.wide)
458
+ R["best_dev"] = getattr(S, "best_dev", None)
459
+ R["lora"] = {"steps": a.train, "bs": a.bs, "lr": a.lr, "r": 16, "seed": a.seed}
460
+ if a.train_only: # ölçüm ayrı, temiz süreçte (eğitim sonrası parçalı bellek düşünme üretiminde OOM veriyor)
461
+ json.dump(R, open(a.out, "w"), indent=1); print("EGITIM BITTI", R["best_dev"], flush=True)
462
+ return
463
+ eval_all("runs")
464
+ R["temperature"] = R.get("runs_temperature")
465
+ json.dump(R, open(a.out, "w"), indent=1)
466
+ print("BITTI", flush=True)
467
+
468
+
469
+ if __name__ == "__main__":
470
+ main()
code/kevdata.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kev (jaredpalmer/kev) açık değerlendirme paketlerini NIVEN vaka biçimine çevirir — AYNI maddelerde kıyas için.
2
+
3
+ Kev kaydı: {"state": {...}, "questions": {qid: {type, instructions, criteria, label, src}}, "_meta": {...}}
4
+ NIVEN vakası: {"id", "source", "state", "questions": {qid: {type, instructions, criteria}}, "gold": {qid: {"label"}}}
5
+
6
+ Paketler (HF dataset jaredpalmer/kev-suites, Apache-2.0):
7
+ v7/decision-v7 train / development / calibration / test (Kev'in eğitildiği kaynaklar)
8
+ v4/transfer-v4 test (764) (Kev'in HİÇ eğitilmediği kaynaklar: mmlu, sciq, qnli,
9
+ paws, emotion, tweet_offensive, contrastive, composition)
10
+ Bu kaynaklar NIVEN eğitiminde de KULLANILMAZ (transfer-v4 yalnız değerlendirme).
11
+ """
12
+ import json, os
13
+
14
+ REPO = "jaredpalmer/kev-suites"
15
+ FILES = {
16
+ "kev_train": "v7/decision-v7/train.jsonl",
17
+ "kev_dev": "v7/decision-v7/development.jsonl",
18
+ "kev_cal": "v7/decision-v7/calibration.jsonl",
19
+ "kev_test": "v7/decision-v7/test.jsonl",
20
+ "kev_transfer_test": "v4/transfer-v4/test.jsonl",
21
+ "kev_transfer_dev": "v4/transfer-v4/development.jsonl", # Jev'in ölçüldüğü bölüm (Kev README: Jev yalnız development)
22
+ }
23
+ HOLDOUT = {"mmlu", "emotion", "tweet_offensive", "qnli", "paws", "sciq"}
24
+
25
+
26
+ def fetch(out_dir):
27
+ from huggingface_hub import hf_hub_download
28
+ os.makedirs(out_dir, exist_ok=True)
29
+ return {k: hf_hub_download(REPO, p, repo_type="dataset", local_dir=out_dir) for k, p in FILES.items()}
30
+
31
+
32
+ def _label(v):
33
+ return str(v).lower() if isinstance(v, bool) else str(v)
34
+
35
+
36
+ def convert(path, tag):
37
+ cases = []
38
+ for i, line in enumerate(open(path, encoding="utf-8")):
39
+ r = json.loads(line)
40
+ qs, gold, src = {}, {}, None
41
+ for qid, q in r["questions"].items():
42
+ src = q.get("src") or r.get("_meta", {}).get("source") or tag
43
+ qs[qid] = {k: q[k] for k in ("type", "instructions", "criteria") if k in q}
44
+ gold[qid] = {"label": _label(q["label"])}
45
+ meta = r.get("_meta", {})
46
+ cases.append({"id": f"{tag}/{meta.get('id', i)}/{i}", "source": src, "workflow": tag,
47
+ "state": r["state"], "questions": qs, "gold": gold})
48
+ return cases
49
+
50
+
51
+ def load(out_dir):
52
+ p = fetch(out_dir)
53
+ K = {k: convert(v, k) for k, v in p.items()}
54
+ extra = os.environ.get("KEV_EXTRA_TRAIN", "") # ek eğitim verisi (kev_augment.py; Kev'in hiçbir kümesiyle çakışmaz)
55
+ if extra and os.path.exists(extra):
56
+ K["kev_train"] += convert(extra, "kev_extra")
57
+ print({"kev_extra_train": len(K["kev_train"])}, flush=True)
58
+ return K
code/learn_eval.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN-Learn ölçümü (CPU yeter): öz-öğrenme belleği + kayıtlı model tahminleri → kilitli Kev testleri.
2
+
3
+ Protokol (dürüst):
4
+ * Bellek = Kev decision-v7 TRAIN (+ kev_augment ek verisi). Test/dev/cal/transfer kümeleri belleğe ASLA girmez.
5
+ * Model log-olasılıkları önceden ölçülmüş koşulardan (aynı madde sırası; y eşleşmesi doğrulanır).
6
+ * Birleştirme ağırlığı (kaynak-başına, log-kayıpla), komşu sayısı ve sıcaklık YALNIZ dev'de (kev_dev; yoksa cal-300)
7
+ seçilir; kev_test / kev_transfer_test bir kez raporlanır.
8
+ * Ek: öğrenme eğrisi (bellek %0→%100), gecikme (learn/recall ms), çevrimiçi geri bildirim deneyi (ayrı protokol).
9
+
10
+ python learn_eval.py --work /tmp/kev --pack model_lp.json.gz --embed bge,hash --out learn_report.json
11
+ """
12
+ import argparse, gzip, json, math, os, random, sys, time
13
+ import numpy as np
14
+
15
+ HERE = os.path.dirname(os.path.abspath(__file__))
16
+ sys.path.insert(0, HERE)
17
+ import kevdata
18
+ from kev_llm import items
19
+ from aubin.learn import DecisionMemory, hash_embed, fuse, sig, vote
20
+
21
+ SUITES = ("kev_dev", "kev_test", "kev_transfer_dev", "kev_transfer_test")
22
+ WGRID = [0.0, 0.1, 0.2, 0.35, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0]
23
+
24
+
25
+ def bge_embed_factory(name="BAAI/bge-small-en-v1.5"):
26
+ try:
27
+ from sentence_transformers import SentenceTransformer
28
+ except ImportError:
29
+ import subprocess
30
+ subprocess.run([sys.executable, "-m", "pip", "-q", "install", "sentence-transformers"], check=False)
31
+ from sentence_transformers import SentenceTransformer
32
+ m = SentenceTransformer(name, device="cpu"); m.max_seq_length = int(os.environ.get("AUBIN_EMB_LEN", 128))
33
+ return lambda texts: m.encode(list(texts), batch_size=64, normalize_embeddings=True, convert_to_numpy=True).astype(np.float32)
34
+
35
+
36
+ def text(it):
37
+ return f"{it['state']} || {it['q']}"
38
+
39
+
40
+ def acc(rows):
41
+ return float(np.mean([int(np.argmax(lp)) == y for lp, y in rows])) if rows else float("nan")
42
+
43
+
44
+ def nll(rows):
45
+ return float(np.mean([-lp[y] for lp, y in rows])) if rows else float("nan")
46
+
47
+
48
+ def neighbours(mem, its, V, K=64):
49
+ out = []
50
+ for it, v in zip(its, V):
51
+ s = sig(it["src"], it["keys"]); mem._freeze(s)
52
+ M = mem.mats.get(s)
53
+ if M is None or not len(M):
54
+ out.append(None); continue
55
+ sims = M @ v; kk = min(K, len(sims)); top = np.argpartition(-sims, kk - 1)[:kk]
56
+ top = top[np.argsort(-sims[top])]
57
+ out.append((sims[top].astype(np.float32), np.asarray([mem.labels[s][i] for i in top])))
58
+ return out
59
+
60
+
61
+ def pmem(nb, keys, k, tau):
62
+ if nb is None:
63
+ return None
64
+ sims, labs = nb[0][:k], nb[1][:k]
65
+ return vote(list(labs), np.exp((sims - sims.max()) / tau), keys)
66
+
67
+
68
+ def combine(lps, ys, nbs, srcs, kss, k, tau, wsrc, T):
69
+ return [(fuse(lp, pmem(nb, ks, k, tau), wsrc.get(s, wsrc.get("*", 0.0)), T), y) for lp, y, nb, s, ks in zip(lps, ys, nbs, srcs, kss)]
70
+
71
+
72
+ def tune(dev, T):
73
+ """Global (k, τ, w) dev log-kaybıyla; sonra kaynak-başına w (≥30 madde) yine log-kayıpla (doğruluktan daha az gürültülü)."""
74
+ lps, ys, nbs, srcs, ns = dev
75
+ best = None
76
+ for k in (8, 16, 32, 64):
77
+ for tau in (0.02, 0.05, 0.1, 0.2):
78
+ for w in WGRID:
79
+ v = nll(combine(lps, ys, nbs, srcs, ns, k, tau, {"*": w}, T))
80
+ if best is None or v < best[0] - 1e-9:
81
+ best = (v, k, tau, w)
82
+ _, k, tau, wg = best
83
+ wsrc = {"*": wg}
84
+ for s in sorted(set(srcs)):
85
+ idx = [i for i, x in enumerate(srcs) if x == s]
86
+ if len(idx) < 30:
87
+ continue
88
+ sub = [lps[i] for i in idx], [ys[i] for i in idx], [nbs[i] for i in idx], [srcs[i] for i in idx], [ns[i] for i in idx]
89
+ wsrc[s] = min(WGRID, key=lambda w: (nll(combine(*sub, k, tau, {"*": w}, T)), abs(w - wg)))
90
+ full = combine(lps, ys, nbs, srcs, ns, k, tau, wsrc, T)
91
+ return {"k": k, "tau": tau, "w": wsrc, "dev_nll_global": round(best[0], 4), "dev_acc_fused": round(acc(full), 4)}
92
+
93
+
94
+ def by_source(rows, srcs):
95
+ d = {}
96
+ for (lp, y), s in zip(rows, srcs):
97
+ d.setdefault(s, []).append(int(np.argmax(lp)) == y)
98
+ return {s: [round(float(np.mean(v)), 4), len(v)] for s, v in sorted(d.items())}
99
+
100
+
101
+ def main():
102
+ ap = argparse.ArgumentParser()
103
+ ap.add_argument("--work", default="/tmp/kev"); ap.add_argument("--pack", required=True)
104
+ ap.add_argument("--embed", default="bge,hash"); ap.add_argument("--out", default="learn_report.json")
105
+ a = ap.parse_args()
106
+ K = kevdata.load(a.work)
107
+ tr = items(K["kev_train"])
108
+ ev = {s: items(K[s]) for s in SUITES}
109
+ cal = items(K["kev_cal"]); random.Random(0).shuffle(cal); ev["cal300"] = cal[:300]
110
+ pack = json.load(gzip.open(a.pack, "rt", encoding="utf-8"))
111
+ is_extra = np.array([x["key"].startswith("kev_extra/") for x in tr])
112
+ R = {"protocol": __doc__.split("Protokol (dürüst):")[1].split("python learn_eval")[0].strip(),
113
+ "memory": {"kev_train_items": int((~is_extra).sum()), "extra_items": int(is_extra.sum())},
114
+ "reference": {"Kev-9B kev_test": 0.874, "Kev-27B kev_test": 0.870, "Kev-27B kev_transfer_test": 0.896}, "embeds": {}}
115
+ for emb in a.embed.split(","):
116
+ t0 = time.time()
117
+ fn = hash_embed if emb == "hash" else bge_embed_factory({"bge": "BAAI/bge-small-en-v1.5", "bge-base": "BAAI/bge-base-en-v1.5", "e5-base": "intfloat/e5-base-v2"}[emb])
118
+ VP = np.concatenate([fn([text(x) for x in tr[i:i + 4096]]) for i in range(0, len(tr), 4096)])
119
+ VE = {s: fn([text(x) for x in ev[s]]) for s in ev}
120
+ print(emb, "gömme bitti", VP.shape, round(time.time() - t0), "s", flush=True)
121
+ if emb != "hash": # sonraki koşular için gömmeleri sakla (float16)
122
+ np.savez_compressed(os.path.join(os.path.dirname(os.path.abspath(a.out)), f"emb_{emb}.npz"), VP=VP.astype(np.float16),
123
+ **{"VE_" + s: VE[s].astype(np.float16) for s in VE})
124
+ out = {}
125
+ for mem_name, mask in (("kev+extra", np.ones(len(tr), bool)), ("kev_only", ~is_extra)):
126
+ if mem_name == "kev+extra" and not is_extra.any():
127
+ continue
128
+ idx = np.where(mask)[0]
129
+ mem = DecisionMemory(fn)
130
+ mem.learn_vectors(VP[idx], [tr[i]["src"] for i in idx], [tr[i]["keys"] for i in idx], [tr[i]["y"] for i in idx])
131
+ NB = {s: neighbours(mem, ev[s], VE[s]) for s in ev}
132
+ res = {"embed_seconds": round(time.time() - t0, 1), "memory_items": int(len(idx)), "runs": {}}
133
+ it0 = ev["kev_test"][0]
134
+ ms_l = [mem.learn(text(it0), "latency_probe", it0["keys"], it0["y"]) for _ in range(20)]
135
+ t1 = time.perf_counter(); [mem.recall(text(x), x["src"], x["keys"]) for x in ev["kev_test"][:100]]
136
+ res["latency_ms"] = {"learn_median": round(float(np.median(ms_l)), 3), "recall_mean_incl_embed": round((time.perf_counter() - t1) * 1e3 / 100, 3)}
137
+ for rn, rp in pack.items():
138
+ T = rp.get("T", 1.0); have = [s for s in ev if s in rp["suites"]]
139
+ def prep(s, nbs=None):
140
+ its = ev[s]; L = rp["suites"][s]
141
+ assert len(L["y"]) == len(its) and all(int(y) == it["y"] for y, it in zip(L["y"], its)), f"{rn}/{s} sıra uyuşmuyor"
142
+ return [np.asarray(x) for x in L["lp"]], L["y"], (nbs or NB[s]), [it["src"] for it in its], [it["keys"] for it in its]
143
+ devname = "kev_dev" if "kev_dev" in have else ("cal300" if "cal300" in have else None)
144
+ if devname is None:
145
+ continue
146
+ prm = tune(prep(devname), T)
147
+ rr = {"dev_used": devname, "params": prm}
148
+ for s in ("kev_test", "kev_transfer_test", "kev_dev", "kev_transfer_dev"):
149
+ if s not in have:
150
+ continue
151
+ P = prep(s)
152
+ base = combine(*P, prm["k"], prm["tau"], {"*": 0.0}, T)
153
+ fu = combine(*P, prm["k"], prm["tau"], prm["w"], T)
154
+ memonly = [((np.log(pm + 1e-9) if pm is not None else lp), y) for lp, y, pm in
155
+ zip(P[0], P[1], [pmem(nb, ks, prm["k"], prm["tau"]) for nb, ks in zip(P[2], P[4])])]
156
+ rr[s] = {"model": round(acc(base), 4), "memory_only": round(acc(memonly), 4), "fused": round(acc(fu), 4),
157
+ "model_nll": round(nll(base), 4), "fused_nll": round(nll(fu), 4), "n": len(base),
158
+ "by_source_model": by_source(base, P[3]), "by_source_fused": by_source(fu, P[3])}
159
+ if "kev_test" in have and mem_name == "kev+extra": # öğrenme eğrisi: bellek büyüdükçe test doğruluğu
160
+ curve = {}
161
+ rng = np.random.default_rng(1); u = rng.random(len(idx))
162
+ for f in (0.0, 0.05, 0.2, 0.5, 1.0):
163
+ sel = idx[u < f]; sub = DecisionMemory(fn)
164
+ if len(sel):
165
+ sub.learn_vectors(VP[sel], [tr[i]["src"] for i in sel], [tr[i]["keys"] for i in sel], [tr[i]["y"] for i in sel])
166
+ P = prep("kev_test", neighbours(sub, ev["kev_test"], VE["kev_test"]))
167
+ curve[str(f)] = {"memory_items": int(len(sel)), "kev_test_fused": round(acc(combine(*P, prm["k"], prm["tau"], prm["w"], T)), 4)}
168
+ rr["learning_curve"] = curve
169
+ if "kev_test" in have: # çevrimiçi geri bildirim: test akışında her cevaptan sonra doğru etiket belleğe
170
+ on = DecisionMemory(fn)
171
+ on.learn_vectors(VP[idx], [tr[i]["src"] for i in idx], [tr[i]["keys"] for i in idx], [tr[i]["y"] for i in idx])
172
+ hits = []
173
+ for j, it in enumerate(ev["kev_test"]):
174
+ nb = neighbours(on, [it], VE["kev_test"][j:j + 1])[0]
175
+ lp = fuse(np.asarray(rp["suites"]["kev_test"]["lp"][j]), pmem(nb, it["keys"], prm["k"], prm["tau"]),
176
+ prm["w"].get(it["src"], prm["w"]["*"]), T)
177
+ hits.append(int(np.argmax(lp)) == it["y"])
178
+ on.learn_vectors(VE["kev_test"][j:j + 1], [it["src"]], [it["keys"]], [it["y"]])
179
+ rr["online_feedback_kev_test"] = {"note": "ayrı protokol: her cevaptan sonra doğru etiket belleğe yazılır (statik test değil)",
180
+ "accuracy": round(float(np.mean(hits)), 4),
181
+ "second_half": round(float(np.mean(hits[len(hits) // 2:])), 4)}
182
+ res["runs"][rn] = rr
183
+ print(emb, mem_name, rn, "TEST fused", {s: rr[s]["fused"] for s in ("kev_test", "kev_transfer_test") if s in rr},
184
+ "model", {s: rr[s]["model"] for s in ("kev_test", "kev_transfer_test") if s in rr}, flush=True)
185
+ out[mem_name] = res
186
+ R["embeds"][emb] = out
187
+ json.dump(R, open(a.out, "w"), indent=1)
188
+ print("BITTI", a.out, flush=True)
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()
code/learn_online.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN-Learn çevrimiçi deney: soru akışında her cevaptan sonra doğru etiket gelir (geri bildirim), sistem anında öğrenir.
2
+
3
+ İki akış:
4
+ * kev_transfer_test — Kev'in de AUBIN'in de HİÇ eğitilmediği kaynaklar (mmlu, emotion, tweet_offensive, qnli, paws, sciq);
5
+ bellek BOŞ başlar, yalnız geri bildirimle dolar → "bilmediğini anında öğrenme" ölçümü.
6
+ * kev_test — bellek Kev train (+ek veri) ile başlar.
7
+ Yöntemler: model (sabit), AUBIN-Learn = bellek + öz-kalibrasyon (Hedge: model/bellek/birleşik uzmanlarına güven kaynak-başına
8
+ geri bildirimle kendiliğinden ayarlanır). Aynı maddelerde, aynı sırada; ikinci yarı ayrıca raporlanır (öğrenme etkisi).
9
+ Not: Bu, statik kilitli test skoru DEĞİLDİR (akışta etiket görülür); statik skorlar learn_eval.py raporundadır.
10
+
11
+ python learn_online.py --emb emb_bge.npz --pack model_lp.json.gz --out learn_online.json
12
+ """
13
+ import argparse, glob, gzip, json, os, sys
14
+ import numpy as np
15
+
16
+ HERE = os.path.dirname(os.path.abspath(__file__))
17
+ sys.path.insert(0, HERE)
18
+ import kevdata
19
+ from kev_llm import items
20
+ from aubin.learn import DecisionMemory, SelfCalibrator
21
+
22
+
23
+ def run_stream(its, V, lps, T, mem, cal, k=16, tau=0.05, wf=1.0):
24
+ hm, hl, src, hk = [], [], [], {}
25
+ for j, it in enumerate(its):
26
+ lp = np.asarray(lps[j], dtype=np.float64) / T
27
+ p, _ = mem.recall(None, it["src"], it["keys"], k, tau, vec=V[j])
28
+ if p is not None:
29
+ hk.setdefault(it["src"], []).append(int(np.argmax(p)) == it["y"])
30
+ E = SelfCalibrator.experts(lp, p, wf)
31
+ mix, _ = cal.predict(it["src"], E)
32
+ hm.append(int(np.argmax(lp)) == it["y"]); hl.append(int(np.argmax(mix)) == it["y"]); src.append(it["src"])
33
+ cal.update(it["src"], E, it["y"])
34
+ mem.learn(None, it["src"], it["keys"], it["y"], vec=V[j])
35
+ half = len(its) // 2
36
+ by = {}
37
+ for s, a, b in zip(src, hm, hl):
38
+ by.setdefault(s, [[], []]); by[s][0].append(a); by[s][1].append(b)
39
+ r = lambda x: round(float(np.mean(x)), 4)
40
+ return {"n": len(its), "model": r(hm), "aubin_learn": r(hl), "model_2nd_half": r(hm[half:]), "aubin_learn_2nd_half": r(hl[half:]),
41
+ "by_source": {s: {"n": len(v[0]), "model": r(v[0]), "aubin_learn": r(v[1]),
42
+ "memory_only_when_available": (r(hk[s]) if hk.get(s) else None), "memory_available": len(hk.get(s, [])),
43
+ "model_2nd_half": r(v[0][len(v[0]) // 2:]), "aubin_learn_2nd_half": r(v[1][len(v[1]) // 2:])} for s, v in sorted(by.items())}}
44
+
45
+
46
+ def main():
47
+ ap = argparse.ArgumentParser()
48
+ ap.add_argument("--work", default="/tmp/kev"); ap.add_argument("--emb", default="")
49
+ ap.add_argument("--pack", required=True); ap.add_argument("--out", default="learn_online.json")
50
+ a = ap.parse_args()
51
+ emb = a.emb or (glob.glob("/kaggle/input/**/emb_bge.npz", recursive=True) or [""])[0]
52
+ Z = np.load(emb)
53
+ K = kevdata.load(a.work); tr = items(K["kev_train"])
54
+ VP = Z["VP"].astype(np.float32)
55
+ assert len(VP) == len(tr), f"gömme/bellek boyu uyuşmuyor {len(VP)} != {len(tr)} (KEV_EXTRA_TRAIN aynı mı?)"
56
+ pack = json.load(gzip.open(a.pack, "rt", encoding="utf-8"))
57
+ R = {"protocol": __doc__.split("Not:")[0].strip(), "note": "Statik kilitli test skoru değildir; statik skorlar learn_eval raporunda.",
58
+ "runs": {}}
59
+ def stream(rp, s, warm, eta, prior):
60
+ its = items(K[s]); V = Z["VE_" + s].astype(np.float32); L = rp["suites"][s]
61
+ assert all(int(y) == it["y"] for y, it in zip(L["y"], its))
62
+ mem = DecisionMemory()
63
+ if warm:
64
+ mem.learn_vectors(VP, [x["src"] for x in tr], [x["keys"] for x in tr], [x["y"] for x in tr])
65
+ return run_stream(its, V, L["lp"], rp.get("T", 1.0), mem, SelfCalibrator(eta, prior))
66
+
67
+ GRID = [(eta, pr) for eta in (0.3, 1.0, 3.0) for pr in ((0.6, 0.1, 0.3), (0.8, 0.05, 0.15), (0.34, 0.33, 0.33))]
68
+ for rn, rp in pack.items():
69
+ out = {}
70
+ # öz-kalibrasyon hiperparametreleri (η, başlangıç güveni) YALNIZ dev akışlarında seçilir; test akışlarına bir kez uygulanır
71
+ devs = [(s, w) for s, w in (("kev_transfer_dev", False), ("kev_dev", True)) if s in rp["suites"] and "VE_" + s in Z.files]
72
+ best = (1.0, (0.6, 0.1, 0.3))
73
+ if devs:
74
+ best = max(GRID, key=lambda g: np.mean([stream(rp, s, w, *g)["aubin_learn"] for s, w in devs]))
75
+ out["selected_on_dev"] = {"eta": best[0], "prior_model_memory_fused": best[1], "dev_streams": [s for s, _ in devs]}
76
+ for s, warm in (("kev_transfer_test", False), ("kev_test", True)):
77
+ if s not in rp["suites"]:
78
+ continue
79
+ out[s] = stream(rp, s, warm, *best)
80
+ print(rn, s, best, {k: out[s][k] for k in ("model", "aubin_learn", "model_2nd_half", "aubin_learn_2nd_half")}, flush=True)
81
+ R["runs"][rn] = out
82
+ json.dump(R, open(a.out, "w"), indent=1)
83
+ print("BITTI", a.out, flush=True)
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
code/learn_pack.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kayıtlı koşuların soru-başı log-olasılıklarını AUBIN-Learn ölçümü için tek sıkıştırılmış pakete toplar (+ dev'de eşit
2
+ ağırlıklı ansambl). Çıktı: {ad: {"T": sıcaklık, "suites": {küme: {"lp": [...], "y": [...]}}}}
3
+
4
+ python learn_pack.py out.json.gz runs/r12l/a12_b.json runs/f31l2/a31lora2.json ...
5
+ """
6
+ import gzip, json, os, sys
7
+ import numpy as np
8
+
9
+
10
+ def lsm(x):
11
+ x = np.asarray(x, dtype=np.float64); return x - np.logaddexp.reduce(x)
12
+
13
+
14
+ def main():
15
+ out, files = sys.argv[1], sys.argv[2:]
16
+ P = {}
17
+ for f in files:
18
+ j = json.load(open(f, encoding="utf-8")); r = j["runs"]
19
+ name = os.path.splitext(os.path.basename(f))[0]
20
+ S = {s: {"lp": [[round(float(v), 3) for v in it["lp"]] for it in r[s]["items"]], "y": [it["y"] for it in r[s]["items"]]}
21
+ for s in r if isinstance(r[s], dict) and "items" in r[s]}
22
+ if j.get("runs_cal_items"):
23
+ S["cal300"] = {"lp": [[round(float(v), 3) for v in it["lp"]] for it in j["runs_cal_items"]], "y": [it["y"] for it in j["runs_cal_items"]]}
24
+ P[name] = {"T": float(j.get("runs_temperature", 1.0)), "model": j.get("model"), "suites": S}
25
+ mem = [n for n in P if "kev_dev" in P[n]["suites"] and "kev_test" in P[n]["suites"]]
26
+ if len(mem) >= 2: # eşit ağırlıklı ansambl (sıcaklık-ölçekli, normalize)
27
+ S = {}
28
+ for s in set.intersection(*[set(P[n]["suites"]) for n in mem]):
29
+ lps = [[lsm(np.asarray(x) / P[n]["T"]) for x in P[n]["suites"][s]["lp"]] for n in mem]
30
+ S[s] = {"lp": [[round(float(v), 3) for v in np.mean([l[i] for l in lps], 0)] for i in range(len(lps[0]))],
31
+ "y": P[mem[0]]["suites"][s]["y"]}
32
+ P["ens_" + "+".join(mem)] = {"T": 1.0, "model": "ensemble", "suites": S}
33
+ sel = os.environ.get("AUBIN_SEL", "") # select_members.py çıktısı: dev'de seçilmiş ağırlıklı ansambl
34
+ if sel:
35
+ Sj = json.load(open(sel, encoding="utf-8"))
36
+ ms = [(os.path.splitext(os.path.basename(m["file"]))[0], m["weight"]) for m in Sj["members"]]
37
+ S = {}
38
+ for s in set.intersection(*[set(P[n]["suites"]) for n, _ in ms]):
39
+ lps = [([lsm(np.asarray(x) / P[n]["T"]) for x in P[n]["suites"][s]["lp"]], w) for n, w in ms]
40
+ S[s] = {"lp": [[round(float(v), 3) for v in sum(w * l[i] for l, w in lps)] for i in range(len(lps[0][0]))],
41
+ "y": P[ms[0][0]]["suites"][s]["y"]}
42
+ P["sel_" + "+".join(n for n, _ in ms)] = {"T": float(Sj.get("temperature", 1.0)), "model": "ensemble(dev-selected)", "suites": S}
43
+ json.dump(P, gzip.open(out, "wt", encoding="utf-8"))
44
+ print(out, os.path.getsize(out), {n: sorted(P[n]["suites"]) for n in P})
45
+
46
+
47
+ if __name__ == "__main__":
48
+ main()
code/learn_skill.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN-Learn hızlı beceri (Norovox SkillLibrary'nin karar modeli karşılığı): bellekteki vakalardan kaynak-başına saniyeler içinde
2
+ öğrenilen doğrusal sınıflandırıcı (gömme → etiket ADI). Model + beceri log-doğrusal birleşir; ağırlık ve düzenlileştirme
3
+ (C) YALNIZ kev_dev'de seçilir, kev_test / kev_transfer_test bir kez raporlanır. Bellek = Kev train + ek veri (test asla girmez).
4
+
5
+ python learn_skill.py --pack model_lp.json.gz --emb emb_bge.npz --out learn_skill.json
6
+ """
7
+ import argparse, glob, gzip, json, os, sys, time
8
+ import numpy as np
9
+
10
+ HERE = os.path.dirname(os.path.abspath(__file__))
11
+ sys.path.insert(0, HERE)
12
+ import kevdata
13
+ from kev_llm import items
14
+ from aubin.learn import fuse
15
+
16
+ WGRID = [0.0, 0.1, 0.2, 0.35, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0]
17
+
18
+
19
+ def lsm(x):
20
+ x = np.asarray(x, dtype=np.float64); return x - np.logaddexp.reduce(x)
21
+
22
+
23
+ class SoftmaxProbe:
24
+ """Bağımlılıksız çok sınıflı lojistik regresyon (numpy, L2 = 1/C, Adam, tam yığın). sklearn arayüzünün alt kümesi."""
25
+
26
+ def __init__(self, C=1.0, max_iter=300, lr=0.05):
27
+ self.C, self.max_iter, self.lr = C, max_iter, lr
28
+
29
+ def fit(self, X, y):
30
+ self.classes_ = np.array(sorted(set(y)))
31
+ idx = {c: i for i, c in enumerate(self.classes_)}
32
+ Y = np.zeros((len(y), len(self.classes_)), dtype=np.float32); Y[np.arange(len(y)), [idx[c] for c in y]] = 1
33
+ X = np.asarray(X, dtype=np.float32); n, d = X.shape
34
+ W = np.zeros((d, len(self.classes_)), dtype=np.float32); b = np.zeros(len(self.classes_), dtype=np.float32)
35
+ mW, vW, mb, vb = np.zeros_like(W), np.zeros_like(W), np.zeros_like(b), np.zeros_like(b)
36
+ lam = 1.0 / (self.C * n)
37
+ for t in range(1, self.max_iter + 1):
38
+ Z = X @ W + b; Z -= Z.max(1, keepdims=True); P = np.exp(Z); P /= P.sum(1, keepdims=True)
39
+ G = (P - Y) / n
40
+ gW, gb = X.T @ G + lam * W, G.sum(0)
41
+ for g, m, v, p in ((gW, mW, vW, W), (gb, mb, vb, b)):
42
+ m *= 0.9; m += 0.1 * g; v *= 0.999; v += 0.001 * g * g
43
+ p -= self.lr * (m / (1 - 0.9 ** t)) / (np.sqrt(v / (1 - 0.999 ** t)) + 1e-8)
44
+ self.W, self.b = W, b
45
+ return self
46
+
47
+ def predict_proba(self, X):
48
+ Z = np.asarray(X, dtype=np.float32) @ self.W + self.b; Z -= Z.max(1, keepdims=True); P = np.exp(Z)
49
+ return P / P.sum(1, keepdims=True)
50
+
51
+
52
+ def fit_skills(tr, VP, C):
53
+ """Kaynak-başına çok sınıflı lojistik regresyon (etiket adları). Dönüş: {kaynak: (model, sınıflar, süre_ms)}."""
54
+ LogisticRegression = SoftmaxProbe
55
+ by = {}
56
+ for i, x in enumerate(tr):
57
+ by.setdefault(x["src"], []).append(i)
58
+ out = {}
59
+ for s, idx in by.items():
60
+ y = [str(tr[i]["keys"][tr[i]["y"]]) for i in idx]
61
+ if len(set(y)) < 2 or len(idx) < 50:
62
+ continue
63
+ t0 = time.perf_counter()
64
+ m = LogisticRegression(C=C)
65
+ m.fit(VP[idx], y)
66
+ out[s] = (m, list(m.classes_), (time.perf_counter() - t0) * 1e3)
67
+ return out
68
+
69
+
70
+ def skill_probs(skills, its, V):
71
+ P = []
72
+ for it, v in zip(its, V):
73
+ sk = skills.get(it["src"])
74
+ if sk is None:
75
+ P.append(None); continue
76
+ m, cls, _ = sk
77
+ pr = m.predict_proba(v[None])[0]
78
+ pos = {c: j for j, c in enumerate(cls)}
79
+ p = np.array([pr[pos[str(k)]] if str(k) in pos else 0.0 for k in it["keys"]], dtype=np.float64)
80
+ P.append(p / p.sum() if p.sum() > 0 else None)
81
+ return P
82
+
83
+
84
+ def main():
85
+ ap = argparse.ArgumentParser()
86
+ ap.add_argument("--work", default="/tmp/kev"); ap.add_argument("--emb", default="")
87
+ ap.add_argument("--pack", required=True); ap.add_argument("--out", default="learn_skill.json")
88
+ a = ap.parse_args()
89
+ emb = a.emb or (glob.glob("/kaggle/input/**/" + os.environ.get("AUBIN_EMB_FILE", "emb_bge.npz"), recursive=True) or [""])[0]
90
+ Z = np.load(emb)
91
+ K = kevdata.load(a.work); tr = items(K["kev_train"])
92
+ VP = Z["VP"].astype(np.float32)
93
+ assert len(VP) == len(tr), f"gömme/bellek boyu uyuşmuyor {len(VP)} != {len(tr)}"
94
+ pack = json.load(gzip.open(a.pack, "rt", encoding="utf-8"))
95
+ ev = {s: items(K[s]) for s in ("kev_dev", "kev_test", "kev_transfer_test")}
96
+ import random as _r
97
+ _c = items(K["kev_cal"]); _r.Random(0).shuffle(_c); ev["cal300"] = _c[:300] # kev_dev'i eksik üyeler için ayar kümesi
98
+ VE = {s: Z["VE_" + s].astype(np.float32) for s in ev}
99
+ R = {"protocol": __doc__.split(" python")[0].strip(), "memory_items": len(tr), "C": {}, "runs": {}}
100
+ SK = {}
101
+ for C in (0.3, 1.0, 3.0, 10.0):
102
+ t0 = time.time(); sk = fit_skills(tr, VP, C)
103
+ SK[C] = {s: skill_probs(sk, ev[s], VE[s]) for s in ev}
104
+ R["C"][str(C)] = {"fit_seconds_total": round(time.time() - t0, 1),
105
+ "fit_ms_per_source": {s: round(v[2], 1) for s, v in sk.items()},
106
+ "skill_only_dev_acc": round(float(np.mean([int(np.argmax(p)) == it["y"] for p, it in zip(SK[C]["kev_dev"], ev["kev_dev"]) if p is not None])), 4)}
107
+ print("C", C, R["C"][str(C)]["skill_only_dev_acc"], R["C"][str(C)]["fit_seconds_total"], "s", flush=True)
108
+ for rn, rp in pack.items():
109
+ D = "kev_dev" if "kev_dev" in rp["suites"] else ("cal300" if "cal300" in rp["suites"] else None)
110
+ if D is None:
111
+ continue
112
+ T = rp.get("T", 1.0)
113
+ L = {s: [np.asarray(x) for x in rp["suites"][s]["lp"]] for s in ev if s in rp["suites"]}
114
+ def rows(s, C, wsrc):
115
+ return [(fuse(lp, p, wsrc.get(it["src"], wsrc.get("*", 0.0)), T), it["y"], it["src"])
116
+ for lp, p, it in zip(L[s], SK[C][s], ev[s])]
117
+ nll = lambda rr: float(np.mean([-r[0][r[1]] for r in rr]))
118
+ acc = lambda rr: float(np.mean([int(np.argmax(r[0])) == r[1] for r in rr]))
119
+ bestC, bestw = min(((C, w) for C in SK for w in WGRID), key=lambda cw: nll(rows(D, cw[0], {"*": cw[1]})))
120
+ gated = os.environ.get("AUBIN_SKILL_GATE", "1") == "1"
121
+ wsrc = {"*": 0.0 if gated else bestw} # temkinli: kanıtlanmayan kaynakta beceri KAPALI
122
+ for s in sorted({it["src"] for it in ev[D]}):
123
+ idx = [i for i, it in enumerate(ev[D]) if it["src"] == s]
124
+ if len(idx) < 30:
125
+ continue
126
+ def sub(w):
127
+ rr = rows(D, bestC, {"*": w})
128
+ return float(np.mean([-rr[i][0][rr[i][1]] for i in idx])), sum(int(np.argmax(rr[i][0])) == rr[i][1] for i in idx)
129
+ w_nll = min(WGRID, key=lambda w: (sub(w)[0], abs(w - bestw)))
130
+ if gated: # kapı: dev'de doğruluk ≥ +2 soru VE log-kayıp düşmeli; yoksa 0
131
+ (n0, a0), (n1, a1) = sub(0.0), sub(w_nll)
132
+ wsrc[s] = w_nll if (a1 >= a0 + 2 and n1 < n0) else 0.0
133
+ else:
134
+ wsrc[s] = w_nll
135
+ out = {"selected_on_dev": {"C": bestC, "w": wsrc, "gated": gated, "dev_split": D}}
136
+ for s in ("kev_dev", "kev_test", "kev_transfer_test"):
137
+ if s not in L:
138
+ continue
139
+ base, fu = rows(s, bestC, {"*": 0.0}), rows(s, bestC, wsrc)
140
+ bys = {}
141
+ for (b, f) in zip(base, fu):
142
+ bys.setdefault(b[2], [[], []]); bys[b[2]][0].append(int(np.argmax(b[0])) == b[1]); bys[b[2]][1].append(int(np.argmax(f[0])) == f[1])
143
+ sk_only = [int(np.argmax(p)) == it["y"] for p, it in zip(SK[bestC][s], ev[s]) if p is not None]
144
+ out[s] = {"model": round(acc(base), 4), "fused": round(acc(fu), 4), "model_nll": round(nll(base), 4), "fused_nll": round(nll(fu), 4),
145
+ "skill_only_when_available": round(float(np.mean(sk_only)), 4) if sk_only else None, "n": len(base),
146
+ "by_source": {k: [len(v[0]), round(float(np.mean(v[0])), 4), round(float(np.mean(v[1])), 4)] for k, v in sorted(bys.items())}}
147
+ R["runs"][rn] = out
148
+ print(rn, {s: (out[s]["model"], out[s]["fused"]) for s in ("kev_test", "kev_transfer_test") if s in out}, flush=True)
149
+ json.dump(R, open(a.out, "w"), indent=1)
150
+ print("BITTI", a.out, flush=True)
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
code/make_learn_report.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """learn_report.json → AUBIN_LEARN.md (HF'ye giden rapor). Dürüst: seçim dev'de, test bir kez; Kev referansları yanında.
2
+
3
+ python make_learn_report.py runs/learn/learn_report.json release/AUBIN_LEARN.md
4
+ """
5
+ import json, sys
6
+
7
+
8
+ def pct(x):
9
+ return "—" if x is None else f"{100 * x:.1f}"
10
+
11
+
12
+ def glance(online_path, R):
13
+ """Sonuçlar bir bakışta — dürüst: işe yarayan ve yaramayan birlikte."""
14
+ out = ["## Results at a glance", ""]
15
+ if online_path:
16
+ O = json.load(open(online_path, encoding="utf-8"))["runs"]
17
+ gains = [(rn, rr["kev_test"]["model"], rr["kev_test"]["aubin_learn"]) for rn, rr in O.items() if "kev_test" in rr]
18
+ tg = [(rn, rr["kev_transfer_test"]["model"], rr["kev_transfer_test"]["aubin_learn"]) for rn, rr in O.items() if "kev_transfer_test" in rr]
19
+ best = max(gains, key=lambda g: g[2])
20
+ out += [f"* **Learning from feedback works:** on the kev_test stream every one of {len(gains)} AUBIN variants improved "
21
+ f"(+{100 * min(b - a for _, a, b in gains):.1f} to +{100 * max(b - a for _, a, b in gains):.1f} points); best "
22
+ f"`{best[0]}` {pct(best[1])} → **{pct(best[2])}**. Online protocol (labels revealed after each answer) — not a static test score.",
23
+ f"* **Never-seen sources (transfer, memory starts empty):** change "
24
+ f"{100 * min(b - a for _, a, b in tg):+.1f} to {100 * max(b - a for _, a, b in tg):+.1f} points — the self-calibrator keeps "
25
+ "trust on the model when memory is not yet useful, so it does not hurt; a few hundred feedbacks per source are not enough to help."]
26
+ st = []
27
+ for emb, mems in R.get("embeds", {}).items():
28
+ for mname, res in mems.items():
29
+ for rn, rr in res["runs"].items():
30
+ if "kev_test" in rr:
31
+ st.append(rr["kev_test"]["fused"] - rr["kev_test"]["model"])
32
+ if st:
33
+ out.append(f"* **Static locked test (no feedback):** fusing a frozen memory into an already-fine-tuned AUBIN changes kev_test by "
34
+ f"{100 * min(st):+.1f} to {100 * max(st):+.1f} points — no reliable gain; AUBIN already learned these sources.")
35
+ out += ["* Latency: writing a case to memory takes well under a millisecond with the hashing embedder (tens of ms with a "
36
+ "sentence embedder); recall is a matrix product over the partition.", ""]
37
+ return out
38
+
39
+
40
+ def main():
41
+ R = json.load(open(sys.argv[1], encoding="utf-8")); out = sys.argv[2]
42
+ ref = R.get("reference", {})
43
+ L = ["# AUBIN-Learn — instant self-learning memory for AUBIN (Norovox core)", "",
44
+ "AUBIN-Learn plugs the Norovox self-learning core into AUBIN's fast decision loop. Knowledge is not baked into "
45
+ "weights: verified cases live in an external **decision memory**. When AUBIN is unsure, it recalls the most similar "
46
+ "solved cases of the same question type and fuses their vote with its own probabilities; when it is told the right "
47
+ "answer, `learn()` writes it to memory and the very next decision uses it — no gradient step, no retraining.", "",
48
+ "```python", "from aubin.learn import DecisionMemory, AubinLearner",
49
+ "mem = DecisionMemory() # or DecisionMemory(embed_fn=<sentence embedder>)",
50
+ "agent = AubinLearner(score_fn=scorer.score, memory=mem, weights=dev_tuned_weights, margin=4.0,",
51
+ " research_fn=Retrieval().fetch) # Norovox Retrieval: local KB -> web, when memory has nothing",
52
+ "choice, logprobs, evidence = agent.decide(item)", "agent.feedback(item, correct_index) # learned instantly", "```", "",
53
+ *glance(sys.argv[3] if len(sys.argv) > 3 else "", R),
54
+ "## Protocol", "",
55
+ "* Memory = Kev decision-v7 **train** (+ kev_augment extra rows). Test / development / calibration / transfer items never enter memory.",
56
+ "* Model log-probabilities come from previously measured AUBIN runs (same item order; labels verified to match).",
57
+ "* Fusion weight (per source, by log-loss), neighbour count and temperature are selected on development data only "
58
+ "(kev_dev; cal-300 when a run has no dev); kev_test and kev_transfer_test are reported once.",
59
+ "* Also measured: a learning curve (memory 0% → 100%), latency, and an online-feedback stream (separate protocol).", "",
60
+ f"Memory: {R['memory']['kev_train_items']} Kev decision-v7 train items + {R['memory']['extra_items']} leak-free extra items "
61
+ "(kev_augment.py: same HF source datasets, rows not used anywhere in Kev's suites).", ""]
62
+ for emb, mems in R.get("embeds", {}).items():
63
+ for mname, res in mems.items():
64
+ L += [f"## Embedding `{emb}`, memory `{mname}` ({res.get('memory_items', '?')} items)", "",
65
+ f"Latency: learn {res['latency_ms']['learn_median']} ms (median, incl. embedding) · recall "
66
+ f"{res['latency_ms']['recall_mean_incl_embed']} ms/query (incl. embedding).", "",
67
+ "| model predictions | tuned on | kev_test model | kev_test + memory | memory alone | kev_transfer_test model | + memory |",
68
+ "|---|---|---|---|---|---|---|"]
69
+ for rn, rr in res["runs"].items():
70
+ t, x = rr.get("kev_test", {}), rr.get("kev_transfer_test", {})
71
+ L.append(f"| {rn} | {rr['dev_used']} | {pct(t.get('model'))} | {pct(t.get('fused'))} | {pct(t.get('memory_only'))} | "
72
+ f"{pct(x.get('model'))} | {pct(x.get('fused'))} |")
73
+ best = max(res["runs"].items(), key=lambda kv: kv[1].get("kev_test", {}).get("fused", 0))
74
+ rn, rr = best
75
+ L += ["", f"Reference on kev_test (Kev's own training sources): Kev-9B {pct(ref.get('Kev-9B kev_test'))}, "
76
+ f"Kev-27B {pct(ref.get('Kev-27B kev_test'))}. Best row above: `{rn}` {pct(rr['kev_test']['fused'])}.", ""]
77
+ if "kev_test" in rr:
78
+ L += ["Per source (kev_test), model → model + memory:", "", "| source | n | model | + memory |", "|---|---|---|---|"]
79
+ for s, (a, n) in rr["kev_test"]["by_source_model"].items():
80
+ L.append(f"| {s} | {n} | {pct(a)} | {pct(rr['kev_test']['by_source_fused'][s][0])} |")
81
+ L.append("")
82
+ if "learning_curve" in rr:
83
+ L += ["Learning curve — the same model, memory grown from 0% to 100% (no retraining):", "",
84
+ "| memory fraction | items | kev_test |", "|---|---|---|"]
85
+ for f, c in rr["learning_curve"].items():
86
+ L.append(f"| {f} | {c['memory_items']} | {pct(c['kev_test_fused'])} |")
87
+ L.append("")
88
+ if "online_feedback_kev_test" in rr:
89
+ o = rr["online_feedback_kev_test"]
90
+ L += [f"Online feedback (separate protocol, not a static test score): answering kev_test as a stream and writing "
91
+ f"each correct label to memory after answering gives {pct(o['accuracy'])} overall, "
92
+ f"{pct(o['second_half'])} on the second half.", ""]
93
+ if len(sys.argv) > 4 and sys.argv[4]: # hızlı beceri (bellekten saniyede öğrenilen doğrusal sınıflandırıcı)
94
+ S = json.load(open(sys.argv[4], encoding="utf-8"))
95
+ L += ["## Fast skills (learned from memory in seconds)", "",
96
+ "The Norovox skill-library idea applied to decisions: for every source, a small softmax classifier is fitted on the "
97
+ "memory's embeddings (labels by name) in seconds on a CPU, and fused with AUBIN's probabilities. Regularisation and "
98
+ "per-source fusion weights were selected on kev_dev only; test is reported once. A skill is switched on for a source "
99
+ "only if, on kev_dev, it raises accuracy by at least 2 questions **and** lowers log-loss; everywhere else it stays off. "
100
+ "(An ungated variant that picked weights by log-loss alone gave no gain — `reports/learn_skill_ungated.json`.)", "",
101
+ "| predictions | kev_test model | kev_test + skills | kev_transfer_test model | + skills |", "|---|---|---|---|---|"]
102
+ for rn, rr in S["runs"].items():
103
+ t, x = rr.get("kev_test", {}), rr.get("kev_transfer_test", {})
104
+ L.append(f"| {rn} | {pct(t.get('model'))} | {pct(t.get('fused'))} | {pct(x.get('model'))} | {pct(x.get('fused'))} |")
105
+ best = max(S["runs"].items(), key=lambda kv: kv[1].get("kev_test", {}).get("fused", 0))
106
+ L += ["", f"Per source for `{best[0]}` (kev_test): n · model · + skills", ""]
107
+ for s, (n, m, f) in best[1]["kev_test"]["by_source"].items():
108
+ L.append(f"* {s}: {n} · {pct(m)} · {pct(f)}")
109
+ L.append("")
110
+ if len(sys.argv) > 3 and sys.argv[3]: # çevrimiçi (geri bildirimli) akış deneyi
111
+ O = json.load(open(sys.argv[3], encoding="utf-8"))
112
+ L += ["## Online self-learning (feedback stream)", "",
113
+ "Questions arrive one by one; after each answer the correct label is revealed. AUBIN-Learn writes it to memory "
114
+ "(instant) and its **self-calibrator** (Hedge / multiplicative weights over three experts — model, memory, fused) "
115
+ "shifts trust per source towards whichever has been more accurate. On kev_transfer_test the memory starts **empty**: "
116
+ "these sources were never seen in training by AUBIN or Kev. Hyper-parameters (η, initial trust) were selected on the "
117
+ "development streams only. This is a separate protocol, not a static locked-test score.", "",
118
+ "| predictions | stream | model | AUBIN-Learn | model, 2nd half | AUBIN-Learn, 2nd half |", "|---|---|---|---|---|---|"]
119
+ for rn, rr in O["runs"].items():
120
+ for s in ("kev_transfer_test", "kev_test"):
121
+ if s in rr:
122
+ x = rr[s]
123
+ L.append(f"| {rn} | {s} | {pct(x['model'])} | {pct(x['aubin_learn'])} | {pct(x['model_2nd_half'])} | {pct(x['aubin_learn_2nd_half'])} |")
124
+ L.append("")
125
+ L += ["## Honest notes", "",
126
+ "* Fusion weights, neighbour count and temperature were chosen on development data only; test numbers are reported once.",
127
+ "* Memory never contains test, development, calibration or transfer items.",
128
+ "* Sources unseen by the memory (all of transfer-v4) fall back to the model unchanged — memory cannot hurt them.",
129
+ "* Any comparison with Kev uses the same public Kev suites; Kev models are not part of AUBIN-Learn."]
130
+ open(out, "w", encoding="utf-8").write("\n".join(L) + "\n")
131
+ print(out)
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
code/mind2web_eval.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN bilgisayar kullanımı (web ajanı) ölçümü — Mind2Web (Deng et al., 2023), MindAct çoktan-seçmeli protokolü.
2
+
3
+ Her adım: görev + önceki eylemler + resmi sıralayıcının (scores_all_data.pkl) ilk-K adayı → AUBIN tipli kararlar:
4
+ 1) element: hangi öğe? (K seçenek; >26 ise 26'lık gruplar + final turu)
5
+ 2) op: CLICK / TYPE / SELECT
6
+ 3) value: TYPE/SELECT ise kısa üretim
7
+ Ölçüler (Mind2Web ile aynı): Element Accuracy, Operation F1 (op+değer token F1), Step Success Rate.
8
+ Pozitif öğe ilk-K'da değilse adım başarısız sayılır (MindAct ile aynı).
9
+
10
+ python mind2web_eval.py --model google/gemma-4-12B-it --adapter <lora> --split test_task --steps 200 --out m2w.json
11
+ """
12
+ import argparse, json, os, pickle, random, re, sys, time
13
+ import torch
14
+
15
+ HERE = os.path.dirname(os.path.abspath(__file__))
16
+ sys.path.insert(0, HERE)
17
+
18
+ OPS = ["CLICK", "TYPE", "SELECT"]
19
+ KEEP = ("aria_label", "aria-label", "placeholder", "title", "name", "type", "value", "alt", "role", "id", "input_value", "label")
20
+
21
+
22
+ def load_split(split, limit_files=0):
23
+ from huggingface_hub import HfApi, hf_hub_download
24
+ import pyarrow.parquet as pq
25
+ fs = sorted(f for f in HfApi().list_repo_files("osunlp/Multimodal-Mind2Web", repo_type="dataset")
26
+ if f.startswith(f"data/{split}-") and f.endswith(".parquet"))
27
+ rows = []
28
+ for f in fs[: limit_files or None]:
29
+ p = hf_hub_download("osunlp/Multimodal-Mind2Web", f, repo_type="dataset")
30
+ t = pq.read_table(p, columns=["action_uid", "cleaned_html", "operation", "pos_candidates", "neg_candidates",
31
+ "annotation_id", "confirmed_task", "action_reprs", "target_action_index", "website"])
32
+ rows += t.to_pylist()
33
+ return rows
34
+
35
+
36
+ def load_scores():
37
+ from huggingface_hub import hf_hub_download
38
+ p = hf_hub_download("osunlp/Mind2Web", "scores_all_data.pkl", repo_type="dataset")
39
+ with open(p, "rb") as f:
40
+ return pickle.load(f)
41
+
42
+
43
+ def describe(cand, html_index):
44
+ """Aday öğenin MindAct benzeri kısa metni: <etiket öznitelikler> görünen metin </etiket> + üst öğe bağlamı."""
45
+ c = json.loads(cand) if isinstance(cand, str) else cand
46
+ attrs = json.loads(c["attributes"]) if isinstance(c.get("attributes"), str) else (c.get("attributes") or {})
47
+ nid = str(attrs.get("backend_node_id"))
48
+ bits = " ".join(f'{k}="{str(attrs[k])[:40]}"' for k in KEEP if attrs.get(k))
49
+ own, parent = html_index.get(nid, ("", ""))
50
+ s = f"<{c.get('tag', '?')} {bits}> {own[:90]} </{c.get('tag', '?')}>".replace(" ", " ")
51
+ if parent and parent != own:
52
+ s += f" (inside: {parent[:70]})"
53
+ return nid, s[:260]
54
+
55
+
56
+ def html_text_index(cleaned_html):
57
+ from lxml import html as lh
58
+ idx = {}
59
+ try:
60
+ root = lh.fromstring(cleaned_html)
61
+ except Exception:
62
+ return idx
63
+ for el in root.iter():
64
+ nid = el.get("backend_node_id") if hasattr(el, "get") else None
65
+ if nid:
66
+ try:
67
+ own = re.sub(r"\s+", " ", el.text_content()).strip()
68
+ par = el.getparent()
69
+ ptxt = re.sub(r"\s+", " ", par.text_content()).strip() if par is not None else ""
70
+ idx[nid] = (own[:160], ptxt[:160])
71
+ except Exception:
72
+ pass
73
+ return idx
74
+
75
+
76
+ def tournament(S, st, cands, group=5):
77
+ """MindAct çoktan-seçmeli: 5'li gruplar + 'None of the above'; seçilenler bir sonraki tura; tek aday kalana dek."""
78
+ alive, rounds = list(cands), 0
79
+ while len(alive) > 1:
80
+ nxt = []
81
+ for i in range(0, len(alive), group):
82
+ g = alive[i:i + group]
83
+ it = {"state": st, "q": "Which page element should be acted on next to accomplish the task? Choose 'None of the above' if none fits.",
84
+ "keys": [c[0] for c in g] + ["none"], "texts": [c[1] for c in g] + ["None of the above"], "y": 0}
85
+ with torch.no_grad():
86
+ lp = S.score(it)
87
+ j = int(lp.argmax())
88
+ if j < len(g):
89
+ nxt.append((g[j], float(torch.softmax(lp, -1)[j])))
90
+ rounds += 1
91
+ if not nxt:
92
+ return None, 0.0, rounds
93
+ alive = [x[0] for x in nxt]
94
+ if len(alive) == 1:
95
+ return alive[0], nxt[0][1], rounds
96
+ return (alive[0], 1.0, rounds) if alive else (None, 0.0, rounds)
97
+
98
+
99
+ def train_items(rows, scores, topk, rng, per_action=2):
100
+ """Mind2Web EĞİTİM bölümünden MindAct tarzı çoktan-seçmeli örnekler (kev_llm item biçimi):
101
+ grup = 5 aday (+ 'None of the above'); pozitif içeren grupta cevap pozitif, içermeyende 'None'."""
102
+ out = []
103
+ for r in rows:
104
+ key = f"{r['annotation_id']}_{r['action_uid']}"
105
+ sc = scores.get(key) if isinstance(scores, dict) else None
106
+ idx = html_text_index(r["cleaned_html"])
107
+ pos = [describe(c, idx) for c in r["pos_candidates"]]
108
+ neg = [describe(c, idx) for c in r["neg_candidates"]]
109
+ if not pos or not neg:
110
+ continue
111
+ if sc:
112
+ neg.sort(key=lambda x: -float(sc.get(x[0], -1e9)))
113
+ neg = neg[:topk]
114
+ hist = r["action_reprs"][: int(r["target_action_index"])]
115
+ st = json.dumps({"task": r["confirmed_task"], "website": r["website"], "previous_actions": hist[-6:] or ["(none)"]}, ensure_ascii=False)
116
+ q = "Which page element should be acted on next to accomplish the task? Choose 'None of the above' if none fits."
117
+ for k in range(per_action):
118
+ g = rng.sample(neg, min(4 if k == 0 else 5, len(neg)))
119
+ if k == 0:
120
+ g = g + [rng.choice(pos)]
121
+ rng.shuffle(g)
122
+ keys = [c[0] for c in g] + ["none"]; texts = [c[1] for c in g] + ["None of the above"]
123
+ y = next((i for i, c in enumerate(g) if c in pos), len(g))
124
+ out.append({"key": f"{key}/{k}", "src": "mind2web_train", "state": st, "q": q, "type": "choice",
125
+ "keys": keys, "texts": texts, "y": y})
126
+ opr = json.loads(r["operation"]) if isinstance(r["operation"], str) else r["operation"]
127
+ out.append({"key": f"{key}/op", "src": "mind2web_train", "state": st + f"\nChosen element: {pos[0][1]}",
128
+ "q": "Which operation should be performed on the chosen element?", "type": "choice",
129
+ "keys": OPS, "texts": ["CLICK: click it", "TYPE: type text into it", "SELECT: choose an option from it"],
130
+ "y": OPS.index(opr["op"]) if opr["op"] in OPS else 0})
131
+ return out
132
+
133
+
134
+ def f1(pred, gold):
135
+ p, g = pred.lower().split(), gold.lower().split()
136
+ if not p and not g:
137
+ return 1.0
138
+ common = sum(min(p.count(w), g.count(w)) for w in set(p))
139
+ if common == 0:
140
+ return 0.0
141
+ pr, rc = common / len(p), common / len(g)
142
+ return 2 * pr * rc / (pr + rc)
143
+
144
+
145
+ def main():
146
+ ap = argparse.ArgumentParser()
147
+ ap.add_argument("--model", default="google/gemma-4-12B-it"); ap.add_argument("--adapter", default="")
148
+ ap.add_argument("--split", default="test_task"); ap.add_argument("--steps", type=int, default=200)
149
+ ap.add_argument("--topk", type=int, default=50); ap.add_argument("--files", type=int, default=0)
150
+ ap.add_argument("--no4bit", action="store_true"); ap.add_argument("--device_map", default="")
151
+ ap.add_argument("--work", default=""); ap.add_argument("--out", default="m2w.json"); ap.add_argument("--seed", type=int, default=0)
152
+ ap.add_argument("--train_steps", type=int, default=0); ap.add_argument("--train_files", type=int, default=10)
153
+ ap.add_argument("--lr", type=float, default=3e-5); ap.add_argument("--bs", type=int, default=4)
154
+ ap.add_argument("--save_adapter", default="lora_m2w")
155
+ ap.add_argument("--select", default="tournament", choices=["tournament", "flat"]) # flat: tek K-yollu seçim (26'lık gruplar + final)
156
+ a = ap.parse_args()
157
+ t0 = time.time()
158
+ rows = load_split(a.split, a.files)
159
+ S_ = load_scores()
160
+ scores = S_.get("scores", S_) if isinstance(S_, dict) else S_
161
+ print({"rows": len(rows), "score_keys_sample": list(scores)[:2] if isinstance(scores, dict) else type(scores).__name__,
162
+ "load_s": round(time.time() - t0, 1)}, flush=True)
163
+ rng = random.Random(a.seed)
164
+ order = list(range(len(rows))); rng.shuffle(order)
165
+ from kev_llm import Scorer, resolve_adapter
166
+ S = Scorer(a.model, four_bit=not a.no4bit, device_map=a.device_map)
167
+ train_info = None
168
+ if a.train_steps: # Mind2Web EĞİTİM bölümüyle ince ayar (MindAct gibi), sonra aynı test ölçümü
169
+ from kev_llm import train_lora
170
+ tr_rows = load_split("train", a.train_files)
171
+ tr = train_items(tr_rows, scores, a.topk, random.Random(a.seed + 1))
172
+ random.Random(a.seed + 2).shuffle(tr)
173
+ dev, tr = tr[:150], tr[150:]
174
+ print({"train_actions": len(tr_rows), "train_items": len(tr), "dev_items": len(dev)}, flush=True)
175
+ tr_rows = None
176
+ t1 = time.time()
177
+ train_lora(S, tr, a.train_steps, a.lr, a.bs, a.save_adapter, seed=a.seed, init_adapter=resolve_adapter(a.adapter) if a.adapter else "",
178
+ dev=dev, eval_every=max(100, a.train_steps // 6))
179
+ S.m.eval()
180
+ train_info = {"steps": a.train_steps, "items": len(tr), "lr": a.lr, "bs": a.bs, "minutes": round((time.time() - t1) / 60, 1),
181
+ "best_dev": getattr(S, "best_dev", None), "adapter_dir": a.save_adapter}
182
+ print(train_info, flush=True)
183
+ elif a.adapter:
184
+ from peft import PeftModel
185
+ S.m = PeftModel.from_pretrained(S.m, resolve_adapter(a.adapter)).eval()
186
+ R = {"train": train_info, "split": a.split, "select": a.select, "protocol": (f"MindAct multi-choice (groups of 5 + None, iterative), top-{a.topk} by official ranker" if a.select == "tournament" else f"single {a.topk}-way choice (26-way groups + final), top-{a.topk} by official ranker"), "steps": [], "model": a.model,
187
+ "adapter": a.adapter}
188
+ n_done = 0
189
+ for i in order:
190
+ if n_done >= a.steps:
191
+ break
192
+ r = rows[i]
193
+ key = f"{r['annotation_id']}_{r['action_uid']}"
194
+ sc = scores.get(key) if isinstance(scores, dict) else None
195
+ idx = html_text_index(r["cleaned_html"])
196
+ pos = [describe(c, idx) for c in r["pos_candidates"]]
197
+ neg = [describe(c, idx) for c in r["neg_candidates"]]
198
+ allc = pos + neg
199
+ if not pos:
200
+ continue
201
+ if sc:
202
+ allc.sort(key=lambda x: -float(sc.get(x[0], -1e9)))
203
+ else:
204
+ rng.shuffle(allc)
205
+ cands = allc[: a.topk]
206
+ pos_ids = {p[0] for p in pos}
207
+ hist = r["action_reprs"][: int(r["target_action_index"])]
208
+ state = {"task": r["confirmed_task"], "website": r["website"], "previous_actions": hist[-6:] or ["(none)"]}
209
+ st = json.dumps(state, ensure_ascii=False)
210
+ if a.select == "flat":
211
+ item = {"state": st, "q": "Which page element should be acted on next to accomplish the task?",
212
+ "keys": [c[0] for c in cands], "texts": [c[1] for c in cands], "y": 0}
213
+ with torch.no_grad():
214
+ lpf = S.score(item)
215
+ jf = int(lpf.argmax()); win, p_pick = cands[jf], float(torch.softmax(lpf, -1)[jf])
216
+ else:
217
+ win, p_pick, _r = tournament(S, st, cands)
218
+ if win is None: # model "hiçbiri" dedi: adım başarısız, yine de ilk adayla devam
219
+ win = cands[0]
220
+ pick_id = win[0]
221
+ pick = [c[0] for c in cands].index(pick_id)
222
+ op_item = {"state": st + f"\nChosen element: {cands[pick][1]}", "q": "Which operation should be performed on the chosen element?",
223
+ "keys": OPS, "texts": ["CLICK: click it", "TYPE: type text into it", "SELECT: choose an option from it"], "y": 0}
224
+ with torch.no_grad():
225
+ op = OPS[int(S.score(op_item).argmax())]
226
+ val = ""
227
+ if op in ("TYPE", "SELECT"):
228
+ msgs = [{"role": "user", "content": f"Task: {r['confirmed_task']}\nPrevious actions: {hist[-6:]}\nElement: {cands[pick][1]}\n"
229
+ f"Operation: {op}. Reply with ONLY the exact text to {'type' if op == 'TYPE' else 'select'}."}]
230
+ p = S.tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
231
+ enc = S.tok([p], return_tensors="pt", add_special_tokens=False).to(S.dev)
232
+ with torch.no_grad():
233
+ g = S.m.generate(**enc, max_new_tokens=24, do_sample=False, pad_token_id=S.tok.pad_token_id)
234
+ val = S.tok.decode(g[0, enc["input_ids"].shape[1]:], skip_special_tokens=True).strip().split("\n")[0].strip().strip('"')
235
+ opr = json.loads(r["operation"]) if isinstance(r["operation"], str) else r["operation"]
236
+ gold_op = opr["op"]; gold_val = opr.get("value", "") or ""
237
+ ele_ok = pick_id in pos_ids
238
+ op_f1 = f1(f"{op} {val}".strip(), f"{gold_op} {gold_val}".strip())
239
+ R["steps"].append({"key": key, "pos_in_topk": bool(pos_ids & {c[0] for c in cands}), "ele": ele_ok, "op": op, "val": val,
240
+ "gold_op": gold_op, "gold_val": gold_val, "op_f1": round(op_f1, 4),
241
+ "step_sr": bool(ele_ok and op == gold_op and (gold_op == "CLICK" or f1(val, gold_val) == 1.0)),
242
+ "p_pick": round(p_pick, 4)})
243
+ n_done += 1
244
+ if n_done % 20 == 0:
245
+ s = R["steps"]
246
+ print({"n": n_done, "ele_acc": round(sum(x["ele"] for x in s) / len(s), 4), "op_f1": round(sum(x["op_f1"] for x in s) / len(s), 4),
247
+ "step_sr": round(sum(x["step_sr"] for x in s) / len(s), 4), "min": round((time.time() - t0) / 60, 1)}, flush=True)
248
+ json.dump(R, open(a.out, "w"), indent=1)
249
+ s = R["steps"]
250
+ R["summary"] = {"n": len(s), "element_accuracy": round(sum(x["ele"] for x in s) / len(s), 4),
251
+ "operation_f1": round(sum(x["op_f1"] for x in s) / len(s), 4),
252
+ "step_success_rate": round(sum(x["step_sr"] for x in s) / len(s), 4),
253
+ "pos_in_topk_rate": round(sum(x["pos_in_topk"] for x in s) / len(s), 4), "minutes": round((time.time() - t0) / 60, 1)}
254
+ json.dump(R, open(a.out, "w"), indent=1)
255
+ print("SONUC", json.dumps(R["summary"]), flush=True)
256
+
257
+
258
+ if __name__ == "__main__":
259
+ main()
code/select_members.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN ansambl üye seçimi — DÜRÜST protokol: seçim yalnız dev bölümlerinde (kev_dev + kev_transfer_dev), test yalnız raporlanır.
2
+
3
+ Açgözlü ileri seçim (tekrarlı üye = ağırlık artışı): her adımda dev log-kaybını (NLL, sıcaklık cal'da) en çok düşüren üye eklenir;
4
+ iyileşme yoksa durur. Sonra seçilen ağırlıklarla kev_test / kev_transfer_test (ve dev) raporlanır.
5
+
6
+ python select_members.py out.json e12a.json e12b.json e31.json ... [--max 8] [--metric nll|acc]
7
+ """
8
+ import argparse, json
9
+ import numpy as np
10
+ from ensemble import metrics
11
+
12
+ DEV = ("kev_dev", "kev_transfer_dev")
13
+ TEST = ("kev_test", "kev_transfer_test")
14
+
15
+
16
+ def runs(r):
17
+ d = dict(r["runs"] if "runs" in r else r)
18
+ if r.get("runs_cal_items") and "cal300" not in d: # kalibrasyon bölümü de seçim kümesi olabilir (--dev cal300)
19
+ d["cal300"] = {"items": [{"src": "cal", "y": it["y"], "lp": it["lp"]} for it in r["runs_cal_items"]],
20
+ "all": {"accuracy": float(np.mean([int(np.argmax(it["lp"])) == it["y"] for it in r["runs_cal_items"]]))}}
21
+ return d
22
+
23
+
24
+ def _n(lp, r):
25
+ """Üyeyi kendi kalibrasyon sıcaklığıyla normalize et (farklı tabanların ham logit ölçekleri farklı)."""
26
+ x = np.asarray(lp, dtype=np.float64) / float(r.get("runs_temperature", 1.0))
27
+ return x - np.logaddexp.reduce(x)
28
+
29
+
30
+ def combo(R, w, s):
31
+ its = [runs(r)[s]["items"] for r in R]
32
+ rows = []
33
+ for k in range(len(its[0])):
34
+ lp = sum(wi * _n(x[k]["lp"], r) for wi, x, r in zip(w, its, R) if wi)
35
+ rows.append((its[0][k]["src"], its[0][k]["y"], lp))
36
+ return rows
37
+
38
+
39
+ def temp(R, w):
40
+ cal = [r.get("runs_cal_items") for r in R]
41
+ if not all(cal[i] for i in range(len(R)) if w[i]):
42
+ return 1.0
43
+ sel = [(wi, ci, r) for wi, ci, r in zip(w, cal, R) if wi]
44
+ comb = [(0, sel[0][1][k]["y"], sum(wi * _n(ci[k]["lp"], r) for wi, ci, r in sel)) for k in range(len(sel[0][1]))]
45
+ grid = np.concatenate([np.arange(0.3, 4.0, 0.05), np.arange(4.0, 20.01, 0.25)])
46
+ return float(min(grid, key=lambda t: metrics(comb, t)["all"]["nll"]))
47
+
48
+
49
+ def score(R, cnt, metric):
50
+ w = np.array(cnt, dtype=float); w = w / w.sum()
51
+ T = temp(R, w)
52
+ rows = [x for s in DEV for x in combo(R, w, s)]
53
+ m = metrics(rows, T)["all"]
54
+ return (-m["nll"] if metric == "nll" else m["accuracy"]), w, T
55
+
56
+
57
+ def main():
58
+ ap = argparse.ArgumentParser()
59
+ ap.add_argument("out"); ap.add_argument("files", nargs="+")
60
+ ap.add_argument("--max", type=int, default=8); ap.add_argument("--metric", default="nll", choices=["nll", "acc"])
61
+ ap.add_argument("--dev", default="kev_dev,kev_transfer_dev")
62
+ a = ap.parse_args()
63
+ global DEV
64
+ DEV = tuple(a.dev.split(","))
65
+ R = [json.load(open(f)) for f in a.files]
66
+ for f, r in zip(a.files, R):
67
+ miss = [s for s in DEV + ("kev_test",) if s not in runs(r)]
68
+ assert not miss, f"{f}: eksik küme {miss}"
69
+ cnt = [0] * len(R); best = None; path = []
70
+ for _ in range(a.max):
71
+ cands = []
72
+ for i in range(len(R)):
73
+ c = list(cnt); c[i] += 1
74
+ cands.append((score(R, c, a.metric)[0], i))
75
+ sc, i = max(cands)
76
+ if best is not None and sc <= best + 1e-6:
77
+ break
78
+ best = sc; cnt[i] += 1; path.append((a.files[i], round(sc, 5)))
79
+ print("ekle", a.files[i], "dev", a.metric, round(sc, 5), flush=True)
80
+ _, w, T = score(R, cnt, a.metric)
81
+ out = {"protocol": f"üye seçimi + ağırlık yalnız dev ({'+'.join(DEV)}); sıcaklık cal; test yalnız rapor",
82
+ "members": [{"file": f, "weight": round(float(x), 4), "model": r.get("model"), "lora": r.get("lora")}
83
+ for f, r, x in zip(a.files, R, w) if x],
84
+ "temperature": round(T, 2), "selection_path": path}
85
+ for s in DEV + TEST:
86
+ if not all(s in runs(r) for r, x in zip(R, w) if x):
87
+ continue
88
+ out[s] = metrics(combo(R, w, s), T)
89
+ print(s, json.dumps(out[s]["all"]), flush=True)
90
+ for f, r in zip(a.files, R): # tek üyeler (karşılaştırma için)
91
+ out.setdefault("single", {})[f] = {s: runs(r)[s]["all"]["accuracy"] for s in DEV + TEST if s in runs(r)}
92
+ json.dump(out, open(a.out, "w"), indent=1)
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
code/td_eval.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN'i Laya/Jev/meraGPT'nin kümesinde (LocalLLaMA/typed-decisions, Apache-2.0) ölç + AUBIN-Learn için soru-başı log-olasılıkları sakla.
2
+
3
+ Kurallar: etiket = gold[q]["label"] (öğretmen dağılımının argmax'ı; tablo 'Accuracy' ile aynı tanım). 'factors' (vakayı üreten gizli
4
+ etkenler) ASLA girdi olarak kullanılmaz. train bölümü yalnız bellek/beceri ve birleştirme ayarı (çapraz doğrulama) için; test bir kez.
5
+
6
+ python td_eval.py --init_adapter hf:emrevrg/AUBIN-12B --out /kaggle/working/td_aubin12.json [--limit N]
7
+ """
8
+ import argparse, json, os, sys, time
9
+ import numpy as np
10
+ import torch
11
+
12
+ HERE = os.path.dirname(os.path.abspath(__file__))
13
+ sys.path.insert(0, HERE)
14
+ from kev_llm import Scorer, items, resolve_adapter
15
+
16
+
17
+ def load_td(split):
18
+ """typed-decisions satırları → kev_llm vaka biçimi."""
19
+ try:
20
+ from datasets import load_dataset
21
+ rows = load_dataset("LocalLLaMA/typed-decisions", "all", split=split)
22
+ except Exception:
23
+ import glob, pyarrow.parquet as pq
24
+ p = glob.glob(os.path.expanduser(f"~/.cache/huggingface/hub/datasets--LocalLLaMA--typed-decisions/snapshots/*/all/{split}-*.parquet"))[0]
25
+ rows = pq.read_table(p).to_pylist()
26
+ cases = []
27
+ for r in rows:
28
+ st = r["state"]; qs = r["questions"]; gd = r["gold"]
29
+ st = json.loads(st) if isinstance(st, str) else st
30
+ qs = json.loads(qs) if isinstance(qs, str) else qs
31
+ gd = json.loads(gd) if isinstance(gd, str) else gd
32
+ cases.append({"id": f"td_{split}/{r['id']}", "source": r["workflow"], "state": st,
33
+ "questions": {q: {k: v[k] for k in ("type", "instructions", "criteria") if k in v} for q, v in qs.items()},
34
+ "gold": {q: {"label": str(gd[q]["label"]).lower() if isinstance(gd[q]["label"], bool) else str(gd[q]["label"])} for q in qs}})
35
+ return cases
36
+
37
+
38
+ def main():
39
+ ap = argparse.ArgumentParser()
40
+ ap.add_argument("--model", default="google/gemma-4-12B-it"); ap.add_argument("--init_adapter", default="")
41
+ ap.add_argument("--no4bit", action="store_true"); ap.add_argument("--device_map", default="")
42
+ ap.add_argument("--work", default=""); ap.add_argument("--limit", type=int, default=0)
43
+ ap.add_argument("--out", default="td_eval.json")
44
+ a = ap.parse_args()
45
+ S = Scorer(a.model, four_bit=not a.no4bit, device_map=a.device_map)
46
+ S.tok.padding_side = "left"
47
+ if S.tok.pad_token is None:
48
+ S.tok.pad_token = S.tok.eos_token
49
+ ad = resolve_adapter(a.init_adapter)
50
+ if ad:
51
+ from peft import PeftModel
52
+ S.m = PeftModel.from_pretrained(S.m, ad).eval()
53
+ R = {"model": a.model, "adapter": a.init_adapter, "benchmark": "LocalLLaMA/typed-decisions (all)",
54
+ "reference": {"meraGPT sd-1": 0.768, "Laya (our run)": 0.7665, "TypeSafe Jev 1.13.0": 0.727, "teacher self-agreement": 0.735}}
55
+ for split in ("test", "train"): # test önce: süre biterse asıl sayı elde olsun
56
+ its = items(load_td(split))
57
+ if a.limit:
58
+ its = its[: a.limit]
59
+ t0 = time.time(); rows = []
60
+ for i, it in enumerate(its):
61
+ with torch.no_grad():
62
+ lg = S.score(it)
63
+ rows.append({"key": it["key"], "src": it["src"], "y": it["y"], "lp": [round(float(x), 4) for x in torch.log_softmax(lg.float(), -1)]})
64
+ if i % 200 == 0:
65
+ print(split, i, len(its), round(time.time() - t0), "s", flush=True)
66
+ acc = float(np.mean([int(np.argmax(r["lp"])) == r["y"] for r in rows]))
67
+ R[split] = {"n": len(rows), "accuracy_T1": round(acc, 4), "seconds": round(time.time() - t0, 1), "items": rows}
68
+ print(split, "ACC", round(acc, 4), flush=True)
69
+ json.dump(R, open(a.out, "w"))
70
+ print("BITTI", a.out, flush=True)
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()
code/td_fuse.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AUBIN-Learn @ typed-decisions (Laya / Jev / meraGPT kümesi): AUBIN LLM + hızlı beceriler (NIVEN-Ağaç, bge-softmax) birleşimi.
2
+
3
+ Uzmanlar (hepsinin train tahmini ÖRNEK-DIŞI):
4
+ * AUBIN (td_eval.py): soru-başı log-olasılık; AUBIN bu kümede hiç eğitilmedi.
5
+ * NIVEN-Ağaç (hukum3/gbdt.py, yalnız durum JSON'u; 'factors' girdisi YOK): train 5-katlı OOF, test tam-train.
6
+ * bge-beceri (td_skill.py): soru-başı gömme → softmax, aynı 5 kat.
7
+ Birleştirme: soru-anahtarı başına log-doğrusal ağırlıklar + AUBIN sıcaklığı YALNIZ train'de (log-kayıp) seçilir; test bir kez.
8
+
9
+ python td_fuse.py --gbdt gbdt_preds.json [--aubin td_aubin12.json] [--skill td_skill.json] --out td_fused.json
10
+ """
11
+ import argparse, glob, itertools, json, os, sys
12
+ import numpy as np
13
+
14
+ HERE = os.path.dirname(os.path.abspath(__file__))
15
+ sys.path.insert(0, HERE)
16
+ from td_eval import load_td
17
+ from kev_llm import items
18
+
19
+ REF = {"meraGPT Decider 1 (leaderboard #1)": 0.768, "Laya (same test, our run)": 0.7665, "TypeSafe Jev 1.13.0": 0.727,
20
+ "NIVEN (ours, 26 Sep)": 0.773, "teacher self-agreement": 0.735}
21
+ GRID = [0.0, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0]
22
+
23
+
24
+ def lsm(x):
25
+ x = np.asarray(x, dtype=np.float64); return x - np.logaddexp.reduce(x)
26
+
27
+
28
+ def raw_rows(split):
29
+ try:
30
+ from datasets import load_dataset
31
+ rows = load_dataset("LocalLLaMA/typed-decisions", "all", split=split)
32
+ except Exception:
33
+ import pyarrow.parquet as pq
34
+ rows = pq.read_table(glob.glob(os.path.expanduser(f"~/.cache/huggingface/hub/datasets--LocalLLaMA--typed-decisions/snapshots/*/all/{split}-*.parquet"))[0]).to_pylist()
35
+ return [{"id": r["id"], "workflow": r["workflow"], "gold_full": json.loads(r["gold"]) if isinstance(r["gold"], str) else r["gold"]} for r in rows]
36
+
37
+
38
+ def main():
39
+ ap = argparse.ArgumentParser()
40
+ ap.add_argument("--gbdt", required=True); ap.add_argument("--aubin", default=""); ap.add_argument("--skill", default="")
41
+ ap.add_argument("--out", required=True)
42
+ a = ap.parse_args()
43
+ G = json.load(open(a.gbdt)); A = json.load(open(a.aubin)) if a.aubin else None; S = json.load(open(a.skill)) if a.skill else None
44
+ opts = {}
45
+ for r in raw_rows("train"): # hukum.build_schema ile aynı seçenek sırası
46
+ for q, g in r["gold_full"].items():
47
+ opts.setdefault(f"{r['workflow']}/{q}", list(g["probabilities"].keys()))
48
+ names = ["NIVEN-Ağaç"] + (["AUBIN"] if A else []) + (["bge-beceri"] if S else [])
49
+ data = {}
50
+ for split, gk in (("train", "oof"), ("test", "test")):
51
+ its = items(load_td(split))
52
+ la = {r["key"]: r for r in A[split]["items"]} if A else {}
53
+ rows = []
54
+ for it in its:
55
+ cid = it["key"].split("/", 1)[1].rsplit("/", 1)[0]; q = it["key"].rsplit("/", 1)[1]; qk = f"{it['src']}/{q}"
56
+ g = G[gk].get(cid, {}).get(qk)
57
+ if g is None or (A and it["key"] not in la):
58
+ continue
59
+ pos = {o: j for j, o in enumerate(opts[qk])}
60
+ pg = np.array([g[pos[k]] if k in pos else 0.0 for k in it["keys"]])
61
+ E = {"NIVEN-Ağaç": np.log(pg / pg.sum() + 1e-6)}
62
+ if A:
63
+ E["AUBIN"] = np.asarray(la[it["key"]]["lp"])
64
+ if S:
65
+ d = S[gk].get(cid, {}).get(qk, {})
66
+ ps = np.array([d.get(str(k), 0.0) for k in it["keys"]]); ps = ps / ps.sum() if ps.sum() > 0 else np.full(len(ps), 1 / len(ps))
67
+ E["bge-beceri"] = np.log(ps + 1e-6)
68
+ rows.append({"qk": qk, "y": it["y"], "E": E})
69
+ data[split] = rows
70
+ tr, te = data["train"], data["test"]
71
+ acc = lambda rr, f: float(np.mean([int(np.argmax(f(r))) == r["y"] for r in rr]))
72
+ nll = lambda rr, f: float(np.mean([-lsm(f(r))[r["y"]] for r in rr]))
73
+ T = 1.0
74
+ if A:
75
+ T = min([0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0], key=lambda t: nll(tr, lambda r: r["E"]["AUBIN"] / t))
76
+ sc = lambda r, n: r["E"][n] / (T if n == "AUBIN" else 1.0)
77
+ W = {}
78
+ for qk in sorted({r["qk"] for r in tr}):
79
+ sub = [r for r in tr if r["qk"] == qk]
80
+ W[qk] = min((w for w in itertools.product(GRID, repeat=len(names)) if sum(w) > 0),
81
+ key=lambda w: nll(sub, lambda r: sum(wi * sc(r, n) for wi, n in zip(w, names))))
82
+ fused = lambda r: sum(wi * sc(r, n) for wi, n in zip(W[r["qk"]], names))
83
+ label = "AUBIN-Learn (" + " + ".join(names) + ")"
84
+ R = {"benchmark": "LocalLLaMA/typed-decisions test (400 cases x 5 = 2000 decisions); label = gold argmax",
85
+ "protocol": __doc__.split(" python")[0].strip(), "reference": REF, "experts": names, "aubin_temperature": T,
86
+ "n": {"train": len(tr), "test": len(te)},
87
+ "test": {**{n: round(acc(te, lambda r, n=n: r["E"][n]), 4) for n in names}, label: round(acc(te, fused), 4)},
88
+ "train_oof": {**{n: round(acc(tr, lambda r, n=n: r["E"][n]), 4) for n in names}, "fused": round(acc(tr, fused), 4)},
89
+ "test_nll_fused": round(nll(te, fused), 4),
90
+ "weights_per_question": {k: dict(zip(names, v)) for k, v in W.items()}}
91
+ os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
92
+ json.dump(R, open(a.out, "w"), indent=1, ensure_ascii=False)
93
+ print(json.dumps(R["test"], ensure_ascii=False), "| train", json.dumps(R["train_oof"], ensure_ascii=False))
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main()
code/td_skill.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """typed-decisions için AUBIN-Learn hızlı becerisi: soru-anahtarı başına bge gömmesi → softmax sınıflandırıcı (saniyeler, CPU).
2
+ train için NIVEN ile AYNI 5 kat (random.Random(7) karıştırma, i::5) → örnek-dışı (OOF) tahmin; test için tüm train'le eğitilir.
3
+ Girdi yalnız durum + soru metni ('factors' YOK). Çıktı td_fuse.py'nin üçüncü uzmanı.
4
+
5
+ python td_skill.py --out /kaggle/working/td_skill.json
6
+ """
7
+ import argparse, json, os, random, sys
8
+ import numpy as np
9
+
10
+ HERE = os.path.dirname(os.path.abspath(__file__))
11
+ sys.path.insert(0, HERE)
12
+ from td_eval import load_td
13
+ from kev_llm import items
14
+ from learn_skill import SoftmaxProbe
15
+ from learn_eval import bge_embed_factory
16
+
17
+
18
+ def text(it):
19
+ return f"{it['state']} || {it['q']}"
20
+
21
+
22
+ def main():
23
+ ap = argparse.ArgumentParser()
24
+ ap.add_argument("--out", default="td_skill.json"); ap.add_argument("--work", default="")
25
+ ap.add_argument("--C", type=float, default=1.0)
26
+ a = ap.parse_args()
27
+ tr, te = items(load_td("train")), items(load_td("test"))
28
+ emb = bge_embed_factory()
29
+ Vtr, Vte = emb([text(x) for x in tr]), emb([text(x) for x in te])
30
+ cid = lambda it: it["key"].split("/", 1)[1].rsplit("/", 1)[0]
31
+ qk = lambda it: f"{it['src']}/{it['key'].rsplit('/', 1)[1]}"
32
+ order = list(dict.fromkeys(cid(x) for x in tr)) # veri seti sırası (NIVEN: range(len(tr)) karıştırılır)
33
+ perm = list(range(len(order))); random.Random(7).shuffle(perm)
34
+ fold = {order[perm[k]]: k % 5 for k in range(len(order))} # NIVEN: folds[f] = ids[f::5]
35
+ out = {"oof": {}, "test": {}, "C": a.C}
36
+ for q in sorted({qk(x) for x in tr}):
37
+ I = [i for i, x in enumerate(tr) if qk(x) == q]; J = [j for j, x in enumerate(te) if qk(x) == q]
38
+ lab = lambda it: str(it["keys"][it["y"]])
39
+ for f in range(5):
40
+ trn = [i for i in I if fold[cid(tr[i])] != f]; val = [i for i in I if fold[cid(tr[i])] == f]
41
+ m = SoftmaxProbe(C=a.C).fit(Vtr[trn], [lab(tr[i]) for i in trn])
42
+ P = m.predict_proba(Vtr[val])
43
+ for i, p in zip(val, P):
44
+ out["oof"].setdefault(cid(tr[i]), {})[q] = {str(c): float(v) for c, v in zip(m.classes_, p)}
45
+ m = SoftmaxProbe(C=a.C).fit(Vtr[I], [lab(tr[i]) for i in I])
46
+ for j, p in zip(J, m.predict_proba(Vte[J])):
47
+ out["test"].setdefault(cid(te[j]), {})[q] = {str(c): float(v) for c, v in zip(m.classes_, p)}
48
+ print(q, len(I), len(J), flush=True)
49
+ def acc(split, its):
50
+ h = []
51
+ for it in its:
52
+ d = out[split].get(cid(it), {}).get(qk(it))
53
+ if d:
54
+ h.append(max(d, key=d.get) == str(it["keys"][it["y"]]))
55
+ return round(float(np.mean(h)), 4)
56
+ out["acc"] = {"train_oof": acc("oof", tr), "test": acc("test", te)}
57
+ json.dump(out, open(a.out, "w"))
58
+ print("TD_SKILL", out["acc"], flush=True)
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main()
reports/AUBIN_LEARN.md ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AUBIN-Learn — instant self-learning memory for AUBIN (Norovox core)
2
+
3
+ AUBIN-Learn plugs the Norovox self-learning core into AUBIN's fast decision loop. Knowledge is not baked into weights: verified cases live in an external **decision memory**. When AUBIN is unsure, it recalls the most similar solved cases of the same question type and fuses their vote with its own probabilities; when it is told the right answer, `learn()` writes it to memory and the very next decision uses it — no gradient step, no retraining.
4
+
5
+ ```python
6
+ from aubin.learn import DecisionMemory, AubinLearner
7
+ mem = DecisionMemory() # or DecisionMemory(embed_fn=<sentence embedder>)
8
+ agent = AubinLearner(score_fn=scorer.score, memory=mem, weights=dev_tuned_weights, margin=4.0,
9
+ research_fn=Retrieval().fetch) # Norovox Retrieval: local KB -> web, when memory has nothing
10
+ choice, logprobs, evidence = agent.decide(item)
11
+ agent.feedback(item, correct_index) # learned instantly
12
+ ```
13
+
14
+ ## Results at a glance
15
+
16
+ * **Learning from feedback works:** on the kev_test stream every one of 6 AUBIN variants improved (+1.0 to +1.3 points); best `ens_a12_b+a31lora2+a12_long` 84.3 → **85.6**. Online protocol (labels revealed after each answer) — not a static test score.
17
+ * **Never-seen sources (transfer, memory starts empty):** change -0.4 to +0.1 points — the self-calibrator keeps trust on the model when memory is not yet useful, so it does not hurt; a few hundred feedbacks per source are not enough to help.
18
+ * **Static locked test (no feedback):** fusing a frozen memory into an already-fine-tuned AUBIN changes kev_test by -1.0 to +0.7 points — no reliable gain; AUBIN already learned these sources.
19
+ * Latency: writing a case to memory takes well under a millisecond with the hashing embedder (tens of ms with a sentence embedder); recall is a matrix product over the partition.
20
+
21
+ ## Protocol
22
+
23
+ * Memory = Kev decision-v7 **train** (+ kev_augment extra rows). Test / development / calibration / transfer items never enter memory.
24
+ * Model log-probabilities come from previously measured AUBIN runs (same item order; labels verified to match).
25
+ * Fusion weight (per source, by log-loss), neighbour count and temperature are selected on development data only (kev_dev; cal-300 when a run has no dev); kev_test and kev_transfer_test are reported once.
26
+ * Also measured: a learning curve (memory 0% → 100%), latency, and an online-feedback stream (separate protocol).
27
+
28
+ Memory: 15576 Kev decision-v7 train items + 67473 leak-free extra items (kev_augment.py: same HF source datasets, rows not used anywhere in Kev's suites).
29
+
30
+ ## Embedding `bge`, memory `kev+extra` (83049 items)
31
+
32
+ Latency: learn 30.746 ms (median, incl. embedding) · recall 96.126 ms/query (incl. embedding).
33
+
34
+ | model predictions | tuned on | kev_test model | kev_test + memory | memory alone | kev_transfer_test model | + memory |
35
+ |---|---|---|---|---|---|---|
36
+ | a12_b | kev_dev | 83.1 | 83.8 | 68.6 | 81.5 | 81.5 |
37
+ | a31lora2 | kev_dev | 82.8 | 82.9 | 68.3 | 89.0 | 89.0 |
38
+ | a12_long | kev_dev | 83.0 | 82.8 | 67.8 | 84.0 | 84.0 |
39
+ | a12_dv_test | cal300 | 83.8 | 83.8 | 68.3 | 84.8 | 84.8 |
40
+ | a31_think_test | cal300 | 83.7 | 83.8 | 68.4 | 88.0 | 88.0 |
41
+ | ens_a12_b+a31lora2+a12_long | kev_dev | 84.3 | 84.1 | 68.3 | 87.7 | 87.7 |
42
+
43
+ Reference on kev_test (Kev's own training sources): Kev-9B 87.4, Kev-27B 87.0. Best row above: `ens_a12_b+a31lora2+a12_long` 84.1.
44
+
45
+ Per source (kev_test), model → model + memory:
46
+
47
+ | source | n | model | + memory |
48
+ |---|---|---|---|
49
+ | agnews | 24 | 75.0 | 75.0 |
50
+ | agnews_yn | 276 | 87.7 | 88.0 |
51
+ | amazon | 80 | 62.5 | 58.8 |
52
+ | banking77 | 116 | 59.5 | 63.8 |
53
+ | boolq | 80 | 91.2 | 92.5 |
54
+ | contrastive_age_eligibility | 40 | 100.0 | 100.0 |
55
+ | contrastive_quantity_limit | 40 | 97.5 | 95.0 |
56
+ | contrastive_return_window | 40 | 92.5 | 92.5 |
57
+ | contrastive_spend_threshold | 76 | 100.0 | 100.0 |
58
+ | dbpedia14 | 116 | 95.7 | 94.0 |
59
+ | imdb | 80 | 97.5 | 97.5 |
60
+ | mnli | 116 | 89.7 | 89.7 |
61
+ | sst5 | 80 | 61.3 | 58.8 |
62
+ | trec | 116 | 89.7 | 89.7 |
63
+ | yelp_yn | 160 | 77.5 | 76.2 |
64
+
65
+ Learning curve — the same model, memory grown from 0% to 100% (no retraining):
66
+
67
+ | memory fraction | items | kev_test |
68
+ |---|---|---|
69
+ | 0.0 | 0 | 84.3 |
70
+ | 0.05 | 4147 | 83.0 |
71
+ | 0.2 | 16563 | 84.7 |
72
+ | 0.5 | 41549 | 84.3 |
73
+ | 1.0 | 83049 | 84.1 |
74
+
75
+ Online feedback (separate protocol, not a static test score): answering kev_test as a stream and writing each correct label to memory after answering gives 83.5 overall, 86.0 on the second half.
76
+
77
+ ## Embedding `bge`, memory `kev_only` (15576 items)
78
+
79
+ Latency: learn 33.498 ms (median, incl. embedding) · recall 39.162 ms/query (incl. embedding).
80
+
81
+ | model predictions | tuned on | kev_test model | kev_test + memory | memory alone | kev_transfer_test model | + memory |
82
+ |---|---|---|---|---|---|---|
83
+ | a12_b | kev_dev | 83.1 | 83.5 | 66.4 | 81.5 | 81.5 |
84
+ | a31lora2 | kev_dev | 82.8 | 83.2 | 66.0 | 89.0 | 89.0 |
85
+ | a12_long | kev_dev | 83.0 | 83.1 | 65.6 | 84.0 | 84.0 |
86
+ | a12_dv_test | cal300 | 83.8 | 83.5 | 66.7 | 84.8 | 84.8 |
87
+ | a31_think_test | cal300 | 83.7 | 82.7 | 64.8 | 88.0 | 88.0 |
88
+ | ens_a12_b+a31lora2+a12_long | kev_dev | 84.3 | 84.2 | 66.0 | 87.7 | 87.7 |
89
+
90
+ Reference on kev_test (Kev's own training sources): Kev-9B 87.4, Kev-27B 87.0. Best row above: `ens_a12_b+a31lora2+a12_long` 84.2.
91
+
92
+ Per source (kev_test), model → model + memory:
93
+
94
+ | source | n | model | + memory |
95
+ |---|---|---|---|
96
+ | agnews | 24 | 75.0 | 75.0 |
97
+ | agnews_yn | 276 | 87.7 | 89.1 |
98
+ | amazon | 80 | 62.5 | 61.3 |
99
+ | banking77 | 116 | 59.5 | 60.3 |
100
+ | boolq | 80 | 91.2 | 92.5 |
101
+ | contrastive_age_eligibility | 40 | 100.0 | 100.0 |
102
+ | contrastive_quantity_limit | 40 | 97.5 | 92.5 |
103
+ | contrastive_return_window | 40 | 92.5 | 92.5 |
104
+ | contrastive_spend_threshold | 76 | 100.0 | 100.0 |
105
+ | dbpedia14 | 116 | 95.7 | 94.0 |
106
+ | imdb | 80 | 97.5 | 97.5 |
107
+ | mnli | 116 | 89.7 | 89.7 |
108
+ | sst5 | 80 | 61.3 | 61.3 |
109
+ | trec | 116 | 89.7 | 89.7 |
110
+ | yelp_yn | 160 | 77.5 | 76.2 |
111
+
112
+ Online feedback (separate protocol, not a static test score): answering kev_test as a stream and writing each correct label to memory after answering gives 82.5 overall, 86.4 on the second half.
113
+
114
+ ## Fast skills (learned from memory in seconds)
115
+
116
+ The Norovox skill-library idea applied to decisions: for every source, a small softmax classifier is fitted on the memory's embeddings (labels by name) in seconds on a CPU, and fused with AUBIN's probabilities. Regularisation and per-source fusion weights were selected on kev_dev only; test is reported once. A skill is switched on for a source only if, on kev_dev, it raises accuracy by at least 2 questions **and** lowers log-loss; everywhere else it stays off. (An ungated variant that picked weights by log-loss alone gave no gain — `reports/learn_skill_ungated.json`.)
117
+
118
+ | predictions | kev_test model | kev_test + skills | kev_transfer_test model | + skills |
119
+ |---|---|---|---|---|
120
+ | a12_b | 83.1 | 83.5 | 81.5 | 81.5 |
121
+ | a31lora2 | 82.8 | 83.5 | 89.0 | 89.0 |
122
+ | a12_long | 83.0 | 83.4 | 84.0 | 84.0 |
123
+ | ens_a12_b+a31lora2+a12_long | 84.3 | 84.8 | 87.7 | 87.7 |
124
+
125
+ Per source for `ens_a12_b+a31lora2+a12_long` (kev_test): n · model · + skills
126
+
127
+ * agnews: 24 · 75.0 · 75.0
128
+ * agnews_yn: 276 · 87.7 · 88.8
129
+ * amazon: 80 · 62.5 · 62.5
130
+ * banking77: 116 · 59.5 · 65.5
131
+ * boolq: 80 · 91.2 · 91.2
132
+ * contrastive_age_eligibility: 40 · 100.0 · 100.0
133
+ * contrastive_quantity_limit: 40 · 97.5 · 97.5
134
+ * contrastive_return_window: 40 · 92.5 · 92.5
135
+ * contrastive_spend_threshold: 76 · 100.0 · 100.0
136
+ * dbpedia14: 116 · 95.7 · 95.7
137
+ * imdb: 80 · 97.5 · 97.5
138
+ * mnli: 116 · 89.7 · 89.7
139
+ * sst5: 80 · 61.3 · 61.3
140
+ * trec: 116 · 89.7 · 89.7
141
+ * yelp_yn: 160 · 77.5 · 75.6
142
+
143
+ ## Online self-learning (feedback stream)
144
+
145
+ Questions arrive one by one; after each answer the correct label is revealed. AUBIN-Learn writes it to memory (instant) and its **self-calibrator** (Hedge / multiplicative weights over three experts — model, memory, fused) shifts trust per source towards whichever has been more accurate. On kev_transfer_test the memory starts **empty**: these sources were never seen in training by AUBIN or Kev. Hyper-parameters (η, initial trust) were selected on the development streams only. This is a separate protocol, not a static locked-test score.
146
+
147
+ | predictions | stream | model | AUBIN-Learn | model, 2nd half | AUBIN-Learn, 2nd half |
148
+ |---|---|---|---|---|---|
149
+ | a12_b | kev_transfer_test | 81.5 | 81.7 | 86.9 | 86.9 |
150
+ | a12_b | kev_test | 83.1 | 84.4 | 86.4 | 87.6 |
151
+ | a31lora2 | kev_transfer_test | 89.0 | 89.0 | 94.2 | 94.2 |
152
+ | a31lora2 | kev_test | 82.8 | 84.2 | 86.1 | 87.5 |
153
+ | a12_long | kev_transfer_test | 84.0 | 84.0 | 89.0 | 89.0 |
154
+ | a12_long | kev_test | 83.0 | 84.2 | 85.6 | 86.5 |
155
+ | a12_dv_test | kev_transfer_test | 84.8 | 84.4 | 90.0 | 90.0 |
156
+ | a12_dv_test | kev_test | 83.8 | 85.0 | 87.1 | 88.3 |
157
+ | a31_think_test | kev_transfer_test | 88.0 | 87.6 | 93.7 | 93.7 |
158
+ | a31_think_test | kev_test | 83.7 | 84.7 | 87.2 | 88.3 |
159
+ | ens_a12_b+a31lora2+a12_long | kev_transfer_test | 87.7 | 87.6 | 92.9 | 92.7 |
160
+ | ens_a12_b+a31lora2+a12_long | kev_test | 84.3 | 85.6 | 87.5 | 88.5 |
161
+
162
+ ## Honest notes
163
+
164
+ * Fusion weights, neighbour count and temperature were chosen on development data only; test numbers are reported once.
165
+ * Memory never contains test, development, calibration or transfer items.
166
+ * Sources unseen by the memory (all of transfer-v4) fall back to the model unchanged — memory cannot hurt them.
167
+ * Any comparison with Kev uses the same public Kev suites; Kev models are not part of AUBIN-Learn.
reports/AUBIN_RESULTS_2026-10-03.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AUBIN — results, 3 October 2026
2
+
3
+ These are all measured numbers. No result that uses a Kev model as a member is counted as "beating Kev". Each section states its protocol and what was used to select it.
4
+
5
+ ## 1. Kev public suites (Kev's own training sources): `kev_test` 1,440 questions, `kev_transfer_test` 764
6
+
7
+ How the ensemble was built:
8
+ - **Members, weights and temperature** were chosen only on the calibration split `cal300`. This split is disjoint from both test sets.
9
+ - **Selection method:** greedy forward selection on NLL. It picked 4 members with equal weight, at T = 0.8.
10
+ - **Test sets** were scored once, for reporting only.
11
+
12
+ | model | kev_test | kev_transfer_test |
13
+ |---|---|---|
14
+ | **AUBIN ensemble (E4B-v3 + 12B-b + 12B-d + 31B)** | **85.7** | **86.5** |
15
+ | AUBIN-12B-b (wide-option training, 3 Oct) | 85.1 | 84.7 |
16
+ | AUBIN-12B-d | 84.8 | 85.2 |
17
+ | AUBIN-12B-e | 84.4 | 83.6 |
18
+ | AUBIN-E4B-v3 | 84.3 | 83.9 |
19
+ | AUBIN-31B | 82.9 | **89.0** |
20
+ | Kev-0.8B | 83.8 | – |
21
+ | Kev-4B | 86.5 | – |
22
+ | Kev-27B | 87.0 | – |
23
+ | Kev-9B | 87.4 | – |
24
+
25
+ - **Calibration of the ensemble:** Brier 0.232 / 0.208 and ECE 0.033 / 0.058 (kev_test / transfer).
26
+ - **Status:** on Kev's own training sources, AUBIN beats Kev-0.8B. It is **1.7 points behind Kev-9B**.
27
+ - **New sources:** on sources Kev was not trained on, AUBIN-31B was already ahead (89.8 vs 89.6, report of 1 Oct).
28
+
29
+ Alternative selections, reported for transparency:
30
+ - cal300 accuracy-selected: 84.8
31
+ - 12B-b + 12B-e: 85.4
32
+ - equal-weight mix of the 4 new models: 85.2
33
+
34
+ ## 2. Typed decisions (`LocalLLaMA/typed-decisions`): 400 test cases × 5 questions = 2,000 decisions
35
+
36
+ | system | accuracy |
37
+ |---|---|
38
+ | **AUBIN-Learn (AUBIN-12B + NIVEN tree skill, equal weights, fixed before scoring)** | **77.55** |
39
+ | NIVEN (Norovox, 26 Sep) | 77.3 |
40
+ | NIVEN tree skill alone | 77.1 |
41
+ | meraGPT sd-1 | 76.8 |
42
+ | Laya | 76.65 |
43
+ | AUBIN-12B zero-shot | 72.9 |
44
+ | TypeSafe Jev 1.13.0 | 72.7 |
45
+
46
+ How the AUBIN-Learn row was produced:
47
+ - The fusion weights were fixed before the test was scored; they were not tuned on test.
48
+ - The tree skill is trained only on the 1,200 training cases.
49
+
50
+ Caveat: the dataset's teacher agrees with itself only about 73.5% of the time, so scores above ~75% are close to saturation. Differences of a few tenths are within noise. With 2,000 decisions, the 95% interval is roughly ±1.8 points.
51
+
52
+ ## 3. Computer use: Mind2Web (MindAct multiple-choice protocol)
53
+
54
+ Protocol:
55
+ - top-50 candidates from the official ranker
56
+ - groups of 5 + "None"
57
+ - iterative tournament
58
+ - 200 steps per split
59
+
60
+ | model | cross-task | cross-website | cross-domain |
61
+ |---|---|---|---|
62
+ | AUBIN-31B (no web fine-tuning) | – | **33.5** | **48.5** |
63
+ | AUBIN-12B-Web (1,200 steps on Mind2Web train) | 40.0 | 32.0 | 45.0 |
64
+ | MindAct Flan-T5-XL (paper, full split) | 52.0 | 38.9 | 39.6 |
65
+ | MindAct GPT-4 (paper, 50 tasks) | 36.2 | 30.1 | 26.4 |
66
+
67
+ The table shows step success rate (%). Element accuracy for AUBIN-31B is 54.0 / 41.0 (domain / website); operation F1 is 86.5 / 82.0.
68
+
69
+ How to read these numbers:
70
+ - The sample is 200 steps per split, not the full split, so each number is ±7 points.
71
+ - Cross-domain is the hardest split, because the domains are entirely unseen. AUBIN-31B is above the published MindAct baselines there.
72
+ - On cross-task and cross-website it is below MindAct-XL.
73
+ - AUBIN is **not** claimed to be the best open-source computer-use agent.
74
+
75
+ ## 4. Real-time control: AUBIN-12B-Control and AUBIN-E4B-Control
76
+
77
+ The benchmark is a command-following grid game with deadly lava: 100 episodes, never seen in training.
78
+
79
+ | controller | success | lava deaths |
80
+ |---|---|---|
81
+ | **AUBIN-12B-Control + safety shield** | **94%** | **0** |
82
+ | AUBIN-12B-Control, no shield | 79% | – |
83
+
84
+ The same shield is also applied to the rule baselines. Full table: model card of `emrevrg/AUBIN-12B-Control`.
85
+
86
+ ## 5. AUBIN-Learn: learning without retraining
87
+
88
+ Details: `reports/AUBIN_LEARN.md`.
89
+
90
+ **Feedback stream (kev_test).** The label is revealed after each answer. All 6 variants improve by **+1.0 to +1.3** points (84.3 → 85.6). This protocol is separate from the static scores above and must not be compared with them.
91
+
92
+ **Never-seen sources (transfer).** The result is −0.4 to +0.1 points: no harm, and no gain yet.
93
+
94
+ **Gated fast skills.** These are per-source classifiers learned from memory in seconds. Each one is switched on only if dev proves it.
95
+ - For the models before 3 Oct, they add +0.3 to +0.6 points on the locked test.
96
+ - For the 3 Oct models trained on wide-option data, the gate stays closed: there is no gain, and nothing is broken.
97
+
98
+ **Safety by construction.** Memory and skills sit outside the weights. The calibrator (Hedge) moves trust back to the model wherever memory does not help. A bad lesson therefore cannot overwrite what the model already knows; this is the "learn by trying without breaking" property.
99
+
100
+ ## 6. Integration
101
+
102
+ AUBIN-Learn exposes the same interface in every AUBIN repository (`INTEGRATION.md`):
103
+ - **Python:** `AubinLearning(model).decide(...)` and `.learn(...)`.
104
+ - **HTTP:** `aubin serve --learn mem.npz` serves `POST /decide`, `POST /learn` and `GET /health`.
105
+ - **OpenAI-compatible:** `POST /v1/chat/completions`, so existing OpenAI clients can connect.
106
+ - **MCP server:** AUBIN can be used as a tool by other assistants.
107
+
108
+ Code is in `code/`. Every number above can be reproduced from the scripts and run files in this repository.
reports/kev_ensemble_final.json ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "protocol": "\u00fcye se\u00e7imi + a\u011f\u0131rl\u0131k yaln\u0131z dev (cal300); s\u0131cakl\u0131k cal; test yaln\u0131z rapor",
3
+ "members": [
4
+ {
5
+ "file": "runs\\sat\\aubin-sat-12ab\\e12b.json",
6
+ "weight": 0.25,
7
+ "model": "google/gemma-4-12B-it",
8
+ "lora": null
9
+ },
10
+ {
11
+ "file": "runs\\sat\\aubin-sat-12cd\\e12d.json",
12
+ "weight": 0.25,
13
+ "model": "google/gemma-4-12B-it",
14
+ "lora": null
15
+ },
16
+ {
17
+ "file": "runs\\sat\\aubin-sat-e4bctl\\ee4g.json",
18
+ "weight": 0.25,
19
+ "model": "google/gemma-4-E4B-it",
20
+ "lora": null
21
+ },
22
+ {
23
+ "file": "runs\\f31l2\\a31lora2.json",
24
+ "weight": 0.25,
25
+ "model": "google/gemma-4-31B-it",
26
+ "lora": {
27
+ "steps": 500,
28
+ "bs": 2,
29
+ "lr": 3e-05,
30
+ "r": 16,
31
+ "seed": 1
32
+ }
33
+ }
34
+ ],
35
+ "temperature": 0.8,
36
+ "selection_path": [
37
+ [
38
+ "runs\\sat\\aubin-sat-e4bctl\\ee4g.json",
39
+ -0.5249
40
+ ],
41
+ [
42
+ "runs\\sat\\aubin-sat-12cd\\e12d.json",
43
+ -0.471
44
+ ],
45
+ [
46
+ "runs\\f31l2\\a31lora2.json",
47
+ -0.4549
48
+ ],
49
+ [
50
+ "runs\\sat\\aubin-sat-12ab\\e12b.json",
51
+ -0.4404
52
+ ]
53
+ ],
54
+ "cal300": {
55
+ "all": {
56
+ "n": 300,
57
+ "accuracy": 0.9,
58
+ "brier": 0.1701,
59
+ "nll": 0.4404,
60
+ "ece15": 0.0479
61
+ },
62
+ "by_source": {
63
+ "cal": {
64
+ "n": 300,
65
+ "accuracy": 0.9,
66
+ "brier": 0.1701,
67
+ "nll": 0.4404,
68
+ "ece15": 0.0479
69
+ }
70
+ }
71
+ },
72
+ "kev_test": {
73
+ "all": {
74
+ "n": 1440,
75
+ "accuracy": 0.8569,
76
+ "brier": 0.2323,
77
+ "nll": 0.7893,
78
+ "ece15": 0.0327
79
+ },
80
+ "by_source": {
81
+ "agnews": {
82
+ "n": 24,
83
+ "accuracy": 0.7917,
84
+ "brier": 0.2687,
85
+ "nll": 0.4624,
86
+ "ece15": 0.174
87
+ },
88
+ "agnews_yn": {
89
+ "n": 276,
90
+ "accuracy": 0.9058,
91
+ "brier": 0.1603,
92
+ "nll": 0.2992,
93
+ "ece15": 0.0541
94
+ },
95
+ "amazon": {
96
+ "n": 80,
97
+ "accuracy": 0.6,
98
+ "brier": 0.5724,
99
+ "nll": 1.076,
100
+ "ece15": 0.1594
101
+ },
102
+ "banking77": {
103
+ "n": 116,
104
+ "accuracy": 0.6466,
105
+ "brier": 0.6378,
106
+ "nll": 5.3509,
107
+ "ece15": 0.2763
108
+ },
109
+ "boolq": {
110
+ "n": 80,
111
+ "accuracy": 0.925,
112
+ "brier": 0.1413,
113
+ "nll": 0.2492,
114
+ "ece15": 0.0561
115
+ },
116
+ "contrastive_age_eligibility": {
117
+ "n": 40,
118
+ "accuracy": 1.0,
119
+ "brier": 0.0057,
120
+ "nll": 0.0545,
121
+ "ece15": 0.053
122
+ },
123
+ "contrastive_quantity_limit": {
124
+ "n": 40,
125
+ "accuracy": 1.0,
126
+ "brier": 0.0113,
127
+ "nll": 0.0844,
128
+ "ece15": 0.0804
129
+ },
130
+ "contrastive_return_window": {
131
+ "n": 40,
132
+ "accuracy": 1.0,
133
+ "brier": 0.0192,
134
+ "nll": 0.0935,
135
+ "ece15": 0.0881
136
+ },
137
+ "contrastive_spend_threshold": {
138
+ "n": 76,
139
+ "accuracy": 1.0,
140
+ "brier": 0.0068,
141
+ "nll": 0.0666,
142
+ "ece15": 0.0642
143
+ },
144
+ "dbpedia14": {
145
+ "n": 116,
146
+ "accuracy": 0.931,
147
+ "brier": 0.0967,
148
+ "nll": 0.2689,
149
+ "ece15": 0.1338
150
+ },
151
+ "imdb": {
152
+ "n": 80,
153
+ "accuracy": 0.975,
154
+ "brier": 0.0448,
155
+ "nll": 0.1068,
156
+ "ece15": 0.0316
157
+ },
158
+ "mnli": {
159
+ "n": 116,
160
+ "accuracy": 0.9397,
161
+ "brier": 0.1049,
162
+ "nll": 0.2341,
163
+ "ece15": 0.0923
164
+ },
165
+ "sst5": {
166
+ "n": 80,
167
+ "accuracy": 0.5875,
168
+ "brier": 0.6051,
169
+ "nll": 1.1158,
170
+ "ece15": 0.1738
171
+ },
172
+ "trec": {
173
+ "n": 116,
174
+ "accuracy": 0.9052,
175
+ "brier": 0.1728,
176
+ "nll": 0.3932,
177
+ "ece15": 0.063
178
+ },
179
+ "yelp_yn": {
180
+ "n": 160,
181
+ "accuracy": 0.7812,
182
+ "brier": 0.3463,
183
+ "nll": 0.6258,
184
+ "ece15": 0.1165
185
+ }
186
+ }
187
+ },
188
+ "kev_transfer_test": {
189
+ "all": {
190
+ "n": 764,
191
+ "accuracy": 0.8652,
192
+ "brier": 0.2078,
193
+ "nll": 0.4197,
194
+ "ece15": 0.0577
195
+ },
196
+ "by_source": {
197
+ "composition_final_combination": {
198
+ "n": 32,
199
+ "accuracy": 1.0,
200
+ "brier": 0.0092,
201
+ "nll": 0.062,
202
+ "ece15": 0.0595
203
+ },
204
+ "composition_final_exception": {
205
+ "n": 32,
206
+ "accuracy": 1.0,
207
+ "brier": 0.0094,
208
+ "nll": 0.0658,
209
+ "ece15": 0.0634
210
+ },
211
+ "composition_final_negation": {
212
+ "n": 32,
213
+ "accuracy": 1.0,
214
+ "brier": 0.0165,
215
+ "nll": 0.0865,
216
+ "ece15": 0.082
217
+ },
218
+ "contrastive_authorization": {
219
+ "n": 40,
220
+ "accuracy": 1.0,
221
+ "brier": 0.0044,
222
+ "nll": 0.0467,
223
+ "ece15": 0.0456
224
+ },
225
+ "contrastive_deadline": {
226
+ "n": 40,
227
+ "accuracy": 1.0,
228
+ "brier": 0.0274,
229
+ "nll": 0.1209,
230
+ "ece15": 0.1099
231
+ },
232
+ "emotion": {
233
+ "n": 116,
234
+ "accuracy": 0.6379,
235
+ "brier": 0.5321,
236
+ "nll": 1.1308,
237
+ "ece15": 0.1442
238
+ },
239
+ "mmlu": {
240
+ "n": 116,
241
+ "accuracy": 0.7759,
242
+ "brier": 0.3244,
243
+ "nll": 0.6186,
244
+ "ece15": 0.1858
245
+ },
246
+ "paws": {
247
+ "n": 80,
248
+ "accuracy": 0.8625,
249
+ "brier": 0.1994,
250
+ "nll": 0.328,
251
+ "ece15": 0.092
252
+ },
253
+ "qnli": {
254
+ "n": 80,
255
+ "accuracy": 0.925,
256
+ "brier": 0.1304,
257
+ "nll": 0.2437,
258
+ "ece15": 0.0606
259
+ },
260
+ "sciq": {
261
+ "n": 116,
262
+ "accuracy": 0.9828,
263
+ "brier": 0.0379,
264
+ "nll": 0.1348,
265
+ "ece15": 0.0976
266
+ },
267
+ "tweet_offensive": {
268
+ "n": 80,
269
+ "accuracy": 0.8,
270
+ "brier": 0.3282,
271
+ "nll": 0.535,
272
+ "ece15": 0.1419
273
+ }
274
+ }
275
+ },
276
+ "single": {
277
+ "runs\\sat\\aubin-sat-12ab\\e12b.json": {
278
+ "cal300": 0.87,
279
+ "kev_test": 0.8514,
280
+ "kev_transfer_test": 0.8469
281
+ },
282
+ "runs\\sat\\aubin-sat-12cd\\e12d.json": {
283
+ "cal300": 0.8966666666666666,
284
+ "kev_test": 0.8479,
285
+ "kev_transfer_test": 0.8521
286
+ },
287
+ "runs\\sat\\aubin-sat-12ef\\e12e.json": {
288
+ "cal300": 0.8733333333333333,
289
+ "kev_test": 0.8444,
290
+ "kev_transfer_test": 0.8364
291
+ },
292
+ "runs\\sat\\aubin-sat-e4bctl\\ee4g.json": {
293
+ "cal300": 0.8366666666666667,
294
+ "kev_test": 0.8431,
295
+ "kev_transfer_test": 0.839
296
+ },
297
+ "runs\\r12l\\a12_b.json": {
298
+ "cal300": 0.8566666666666667,
299
+ "kev_test": 0.8313,
300
+ "kev_transfer_test": 0.8154
301
+ },
302
+ "runs\\f31l2\\a31lora2.json": {
303
+ "cal300": 0.8433333333333334,
304
+ "kev_test": 0.8285,
305
+ "kev_transfer_test": 0.8901
306
+ }
307
+ }
308
+ }
reports/mind2web_final.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "runs/m2w31\\m2w31_domain.json": {
3
+ "split": "test_domain",
4
+ "model": "google/gemma-4-31B-it",
5
+ "adapter": "emrevrg/AUBIN-31B",
6
+ "protocol": "MindAct multi-choice (groups of 5 + None, iterative), top-50 by official ranker",
7
+ "summary": {
8
+ "n": 200,
9
+ "element_accuracy": 0.54,
10
+ "operation_f1": 0.8646,
11
+ "step_success_rate": 0.485,
12
+ "pos_in_topk_rate": 0.9,
13
+ "minutes": 96.5
14
+ },
15
+ "train": null
16
+ },
17
+ "runs/m2w31\\m2w31_website.json": {
18
+ "split": "test_website",
19
+ "model": "google/gemma-4-31B-it",
20
+ "adapter": "emrevrg/AUBIN-31B",
21
+ "protocol": "MindAct multi-choice (groups of 5 + None, iterative), top-50 by official ranker",
22
+ "summary": {
23
+ "n": 200,
24
+ "element_accuracy": 0.41,
25
+ "operation_f1": 0.8202,
26
+ "step_success_rate": 0.335,
27
+ "pos_in_topk_rate": 0.905,
28
+ "minutes": 108.7
29
+ },
30
+ "train": null
31
+ },
32
+ "runs/sat/aubin-sat-12ef\\m2wa_test_domain.json": {
33
+ "split": "test_domain",
34
+ "model": "google/gemma-4-12B-it",
35
+ "adapter": "hf:emrevrg/AUBIN-12B",
36
+ "protocol": "MindAct multi-choice (groups of 5 + None, iterative), top-50 by official ranker",
37
+ "summary": {
38
+ "n": 200,
39
+ "element_accuracy": 0.475,
40
+ "operation_f1": 0.8767,
41
+ "step_success_rate": 0.45,
42
+ "pos_in_topk_rate": 0.9,
43
+ "minutes": 228.6
44
+ },
45
+ "train": {
46
+ "steps": 1200,
47
+ "items": 7995,
48
+ "lr": 3e-05,
49
+ "bs": 4,
50
+ "minutes": 185.3,
51
+ "best_dev": [
52
+ 0.8133333333333334,
53
+ 1000
54
+ ],
55
+ "adapter_dir": "/kaggle/working/lora_m2wa"
56
+ }
57
+ },
58
+ "runs/sat/aubin-sat-12ef\\m2wa_test_task.json": {
59
+ "split": "test_task",
60
+ "model": "google/gemma-4-12B-it",
61
+ "adapter": "/kaggle/working/lora_m2wa",
62
+ "protocol": "MindAct multi-choice (groups of 5 + None, iterative), top-50 by official ranker",
63
+ "summary": {
64
+ "n": 200,
65
+ "element_accuracy": 0.48,
66
+ "operation_f1": 0.8145,
67
+ "step_success_rate": 0.4,
68
+ "pos_in_topk_rate": 0.945,
69
+ "minutes": 35.6
70
+ },
71
+ "train": null
72
+ },
73
+ "runs/sat/aubin-sat-12ef\\m2wa_test_website.json": {
74
+ "split": "test_website",
75
+ "model": "google/gemma-4-12B-it",
76
+ "adapter": "/kaggle/working/lora_m2wa",
77
+ "protocol": "MindAct multi-choice (groups of 5 + None, iterative), top-50 by official ranker",
78
+ "summary": {
79
+ "n": 200,
80
+ "element_accuracy": 0.375,
81
+ "operation_f1": 0.8162,
82
+ "step_success_rate": 0.32,
83
+ "pos_in_topk_rate": 0.905,
84
+ "minutes": 34.6
85
+ },
86
+ "train": null
87
+ }
88
+ }
reports/typed_decisions_final.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "n": 2000,
3
+ "AUBIN-12B zero-shot (T=1)": 0.729,
4
+ "NIVEN-Agac skill": 0.771,
5
+ "AUBIN-Learn (AUBIN T3.2 + NIVEN-Agac, equal, pre-specified)": 0.7755,
6
+ "reference": {
7
+ "meraGPT sd-1": 0.768,
8
+ "Laya": 0.7665,
9
+ "TypeSafe Jev 1.13.0": 0.727,
10
+ "NIVEN 26 Sep": 0.773
11
+ }
12
+ }