Md. Arafat Islam commited on
Commit ·
feaa032
1
Parent(s): 5d5c8a8
qAIR — Quantum-Inspired Multi-Hypothesis Reasoning, Gradio demo.
Browse files- README.md +14 -1
- __pycache__/app.cpython-312.pyc +0 -0
- __pycache__/config.cpython-312.pyc +0 -0
- app.py +217 -0
- ckpt/qair_v46_best.pt +3 -0
- config.py +304 -0
- models/__pycache__/answer_selector.cpython-312.pyc +0 -0
- models/__pycache__/classical_control_layer.cpython-312.pyc +0 -0
- models/__pycache__/collapse.cpython-312.pyc +0 -0
- models/__pycache__/encoder.cpython-312.pyc +0 -0
- models/__pycache__/energy_fusion.cpython-312.pyc +0 -0
- models/__pycache__/full_model.cpython-312.pyc +0 -0
- models/__pycache__/generator.cpython-312.pyc +0 -0
- models/__pycache__/interference.cpython-312.pyc +0 -0
- models/__pycache__/persistent_reasoner.cpython-312.pyc +0 -0
- models/__pycache__/quantum_layer.cpython-312.pyc +0 -0
- models/__pycache__/validator.cpython-312.pyc +0 -0
- models/answer_selector.py +219 -0
- models/classical_control_layer.py +151 -0
- models/collapse.py +112 -0
- models/encoder.py +64 -0
- models/energy_fusion.py +72 -0
- models/full_model.py +482 -0
- models/generator.py +451 -0
- models/interference.py +340 -0
- models/persistent_reasoner.py +314 -0
- models/quantum_layer.py +286 -0
- models/validator.py +216 -0
- requirements.txt +6 -0
README.md
CHANGED
|
@@ -12,4 +12,17 @@ license: mit
|
|
| 12 |
short_description: Quantum AI Reasoning System
|
| 13 |
---
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
short_description: Quantum AI Reasoning System
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# qAIR — Quantum-Inspired Multi-Hypothesis Reasoning
|
| 16 |
+
|
| 17 |
+
Ask a multiple-choice science question. For each option, a small LLM
|
| 18 |
+
generates a *supporting* and an *attacking* hypothesis. Every hypothesis
|
| 19 |
+
becomes a complex amplitude with a learned phase (partly read off a
|
| 20 |
+
simulated quantum circuit), and the answer distribution is the coherent
|
| 21 |
+
sum `|Σ_k c_k v_kn|²` — support and attack can interfere constructively
|
| 22 |
+
or destructively before the final answer is read out.
|
| 23 |
+
|
| 24 |
+
Trained on ARC-Challenge. This checkpoint is a small-scale run (80
|
| 25 |
+
train / 20 validation examples), so treat answers as a demo of the
|
| 26 |
+
mechanism, not a benchmark result.
|
| 27 |
+
|
| 28 |
+
Configuration reference: https://huggingface.co/docs/hub/spaces-config-reference
|
__pycache__/app.cpython-312.pyc
ADDED
|
Binary file (9.19 kB). View file
|
|
|
__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (2.97 kB). View file
|
|
|
app.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
qAIR — Quantum-Inspired Multi-Hypothesis Reasoning, Gradio demo.
|
| 3 |
+
|
| 4 |
+
Wires the same live pipeline as evaluation/sample_inference.py into a UI:
|
| 5 |
+
generate support/attack hypotheses per option -> encode -> single forward
|
| 6 |
+
pass through the trained QAIRvNext checkpoint -> coherent collapse.
|
| 7 |
+
|
| 8 |
+
Model + LLM are loaded once at import time so Space startup absorbs the
|
| 9 |
+
cost instead of the first visitor. Everything after that runs on CPU by
|
| 10 |
+
default (config.resolve_device falls back cuda > mps > cpu), so a single
|
| 11 |
+
query still takes tens of seconds -- most of it is the 0.5B generator LLM
|
| 12 |
+
producing 2 * n_options short completions.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import gradio as gr
|
| 19 |
+
|
| 20 |
+
from config import (
|
| 21 |
+
EMBEDDING_DIM,
|
| 22 |
+
MODEL_DIM,
|
| 23 |
+
N_QUBITS,
|
| 24 |
+
PERSISTENT_STEPS,
|
| 25 |
+
PHASE_MODE,
|
| 26 |
+
PHASE_SOURCE,
|
| 27 |
+
MIXING,
|
| 28 |
+
USE_LLM_PRIOR,
|
| 29 |
+
GEN_MODES,
|
| 30 |
+
CKPT_DIR,
|
| 31 |
+
resolve_device,
|
| 32 |
+
)
|
| 33 |
+
from models.generator import HypothesisGenerator
|
| 34 |
+
from models.encoder import HypothesisEncoder
|
| 35 |
+
from models.full_model import QAIRvNext
|
| 36 |
+
|
| 37 |
+
DEVICE = resolve_device()
|
| 38 |
+
CKPT_NAME = "qair_v46_best.pt"
|
| 39 |
+
CKPT_PATH = os.path.join(CKPT_DIR, CKPT_NAME)
|
| 40 |
+
|
| 41 |
+
EXAMPLES = [
|
| 42 |
+
[
|
| 43 |
+
"Why does ice float on water?",
|
| 44 |
+
"It is heavier than water",
|
| 45 |
+
"It is less dense than water",
|
| 46 |
+
"It absorbs heat",
|
| 47 |
+
"It contains oxygen",
|
| 48 |
+
],
|
| 49 |
+
[
|
| 50 |
+
"What gas do plants absorb from the atmosphere?",
|
| 51 |
+
"Oxygen",
|
| 52 |
+
"Nitrogen",
|
| 53 |
+
"Carbon dioxide",
|
| 54 |
+
"Hydrogen",
|
| 55 |
+
],
|
| 56 |
+
[
|
| 57 |
+
"Why do metal railway tracks have small gaps between sections?",
|
| 58 |
+
"To allow expansion during heating",
|
| 59 |
+
"To reduce weight",
|
| 60 |
+
"To increase friction",
|
| 61 |
+
"To improve color",
|
| 62 |
+
],
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
print(f"[qAIR] device = {DEVICE}")
|
| 67 |
+
print("[qAIR] loading generator LLM (Qwen2.5-0.5B-Instruct)...")
|
| 68 |
+
generator = HypothesisGenerator(device=DEVICE)
|
| 69 |
+
|
| 70 |
+
print("[qAIR] loading sentence encoder (all-MiniLM-L6-v2)...")
|
| 71 |
+
encoder = HypothesisEncoder(device=DEVICE)
|
| 72 |
+
|
| 73 |
+
print(f"[qAIR] building QAIRvNext and loading {CKPT_PATH} ...")
|
| 74 |
+
model = QAIRvNext(
|
| 75 |
+
dim=EMBEDDING_DIM,
|
| 76 |
+
model_dim=MODEL_DIM,
|
| 77 |
+
use_quantum=True,
|
| 78 |
+
use_validator=True,
|
| 79 |
+
persistent_steps=PERSISTENT_STEPS,
|
| 80 |
+
n_qubits=N_QUBITS,
|
| 81 |
+
phase_mode=PHASE_MODE,
|
| 82 |
+
phase_source=PHASE_SOURCE,
|
| 83 |
+
mixing=MIXING,
|
| 84 |
+
use_llm_prior=USE_LLM_PRIOR,
|
| 85 |
+
use_attack=True,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
_ckpt = torch.load(CKPT_PATH, map_location="cpu", weights_only=False)
|
| 89 |
+
model.load_state_dict(_ckpt["model"])
|
| 90 |
+
model.to(DEVICE)
|
| 91 |
+
model.eval()
|
| 92 |
+
|
| 93 |
+
print(f"[qAIR] ready (checkpoint best_acc={_ckpt.get('best_acc', '?')})")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@torch.no_grad()
|
| 97 |
+
def reason(question, opt_a, opt_b, opt_c, opt_d):
|
| 98 |
+
|
| 99 |
+
question = (question or "").strip()
|
| 100 |
+
options = [o.strip() for o in [opt_a, opt_b, opt_c, opt_d] if o and o.strip()]
|
| 101 |
+
|
| 102 |
+
if not question:
|
| 103 |
+
raise gr.Error("Enter a question.")
|
| 104 |
+
|
| 105 |
+
if len(options) < 2:
|
| 106 |
+
raise gr.Error("Enter at least two options.")
|
| 107 |
+
|
| 108 |
+
item = generator.generate_batch_with_flags(
|
| 109 |
+
[question], [options], modes=GEN_MODES
|
| 110 |
+
)[0]
|
| 111 |
+
|
| 112 |
+
hypotheses = item["hypotheses"]
|
| 113 |
+
|
| 114 |
+
llm_scores = generator.score_options([question], [options])[0]
|
| 115 |
+
|
| 116 |
+
H = encoder.encode(hypotheses).unsqueeze(0).to(DEVICE)
|
| 117 |
+
O = encoder.encode(options).unsqueeze(0).to(DEVICE)
|
| 118 |
+
Q = encoder.encode([question]).to(DEVICE)
|
| 119 |
+
|
| 120 |
+
K, N = H.shape[1], O.shape[1]
|
| 121 |
+
|
| 122 |
+
polarity = torch.tensor(
|
| 123 |
+
item["polarity"], dtype=H.dtype, device=DEVICE
|
| 124 |
+
).unsqueeze(0)
|
| 125 |
+
|
| 126 |
+
align = torch.zeros(1, K, N, dtype=H.dtype, device=DEVICE)
|
| 127 |
+
align[0, torch.arange(K), torch.tensor(item["hyp_option"])] = 1.0
|
| 128 |
+
|
| 129 |
+
llm_logprob = torch.tensor(
|
| 130 |
+
llm_scores, dtype=H.dtype, device=DEVICE
|
| 131 |
+
).unsqueeze(0)
|
| 132 |
+
|
| 133 |
+
outputs = model(
|
| 134 |
+
H, O, Q=Q, polarity=polarity, align=align, llm_logprob=llm_logprob,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
probs = outputs["collapse_probs"][0].detach().cpu().numpy()
|
| 138 |
+
pred_idx = int(probs.argmax())
|
| 139 |
+
interference_ratio = float(outputs["interference_ratio"])
|
| 140 |
+
|
| 141 |
+
prob_dict = {opt: float(p) for opt, p in zip(options, probs)}
|
| 142 |
+
|
| 143 |
+
lines = []
|
| 144 |
+
for i, opt in enumerate(options):
|
| 145 |
+
marker = "▶" if i == pred_idx else " "
|
| 146 |
+
lines.append(f"{marker} [{i}] {opt} (LLM logp {llm_scores[i]:+.3f})")
|
| 147 |
+
for m_i, mode in enumerate(GEN_MODES):
|
| 148 |
+
lines.append(
|
| 149 |
+
f" {mode:<8s}: {hypotheses[m_i * len(options) + i]}"
|
| 150 |
+
)
|
| 151 |
+
lines.append("")
|
| 152 |
+
|
| 153 |
+
hyp_text = "\n".join(lines)
|
| 154 |
+
|
| 155 |
+
answer_md = f"### {options[pred_idx]}"
|
| 156 |
+
|
| 157 |
+
return answer_md, prob_dict, hyp_text, f"{interference_ratio:.4f}"
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
with gr.Blocks(title="qAIR — Quantum AI Reasoning") as demo:
|
| 161 |
+
|
| 162 |
+
gr.Markdown(
|
| 163 |
+
"""
|
| 164 |
+
# qAIR — Quantum-Inspired Multi-Hypothesis Reasoning
|
| 165 |
+
|
| 166 |
+
For each option, a small LLM generates a *supporting* and an
|
| 167 |
+
*attacking* hypothesis. Every hypothesis becomes a complex
|
| 168 |
+
amplitude with a learned phase (partly read off a simulated
|
| 169 |
+
quantum circuit), and the answer distribution is the coherent
|
| 170 |
+
sum `|sum_k c_k v_kn|^2` — support and attack can constructively
|
| 171 |
+
or destructively interfere before the answer is read out.
|
| 172 |
+
|
| 173 |
+
Enter a question and 2–4 options. First query is slow (CPU
|
| 174 |
+
generation with the 0.5B hypothesis LLM); expect ~15–60s.
|
| 175 |
+
"""
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
with gr.Row():
|
| 179 |
+
|
| 180 |
+
with gr.Column():
|
| 181 |
+
|
| 182 |
+
question = gr.Textbox(
|
| 183 |
+
label="Question", lines=2,
|
| 184 |
+
placeholder="e.g. Why does ice float on water?",
|
| 185 |
+
)
|
| 186 |
+
opt_a = gr.Textbox(label="Option A")
|
| 187 |
+
opt_b = gr.Textbox(label="Option B")
|
| 188 |
+
opt_c = gr.Textbox(label="Option C (optional)")
|
| 189 |
+
opt_d = gr.Textbox(label="Option D (optional)")
|
| 190 |
+
|
| 191 |
+
run_btn = gr.Button("Reason", variant="primary")
|
| 192 |
+
|
| 193 |
+
gr.Examples(
|
| 194 |
+
examples=EXAMPLES,
|
| 195 |
+
inputs=[question, opt_a, opt_b, opt_c, opt_d],
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
with gr.Column():
|
| 199 |
+
|
| 200 |
+
answer = gr.Markdown(label="Predicted answer")
|
| 201 |
+
probs = gr.Label(label="Collapse probabilities", num_top_classes=4)
|
| 202 |
+
interference = gr.Textbox(
|
| 203 |
+
label="Interference ratio", interactive=False
|
| 204 |
+
)
|
| 205 |
+
hyps = gr.Textbox(
|
| 206 |
+
label="Generated hypotheses (support / attack)",
|
| 207 |
+
lines=16, interactive=False,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
run_btn.click(
|
| 211 |
+
reason,
|
| 212 |
+
inputs=[question, opt_a, opt_b, opt_c, opt_d],
|
| 213 |
+
outputs=[answer, probs, hyps, interference],
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
demo.launch()
|
ckpt/qair_v46_best.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1db25c855e6f1b100d9abfadfcf994f632f626e2ae4548c887e432b1370c04ce
|
| 3 |
+
size 12808367
|
config.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Shared defaults for the qAIR pipeline.
|
| 3 |
+
|
| 4 |
+
Single source of truth for values that were previously hardcoded in
|
| 5 |
+
multiple places (e.g. embedding dim was 768 in training/dataset.py but
|
| 6 |
+
384 in evaluation/sample_inference.py after the encoder model changed).
|
| 7 |
+
Import from here instead of re-hardcoding.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def resolve_device():
|
| 14 |
+
"""
|
| 15 |
+
cuda > mps > cpu. Used everywhere instead of hardcoding "cuda" so the
|
| 16 |
+
pipeline runs (falls back gracefully) on CPU-only machines and on
|
| 17 |
+
Apple Silicon Macs instead of crashing outright. Note: the quantum
|
| 18 |
+
circuit (models/quantum_layer.py) always runs on lightning.qubit
|
| 19 |
+
(CPU) regardless of what this resolves to -- PennyLane's TorchLayer
|
| 20 |
+
handles moving data to/from the circuit transparently.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
if torch.cuda.is_available():
|
| 24 |
+
return "cuda"
|
| 25 |
+
|
| 26 |
+
# getattr guard: torch.backends.mps does not exist before torch 1.12,
|
| 27 |
+
# and requirements.txt deliberately does not pin a torch version.
|
| 28 |
+
mps = getattr(torch.backends, "mps", None)
|
| 29 |
+
|
| 30 |
+
if mps is not None and mps.is_available():
|
| 31 |
+
return "mps"
|
| 32 |
+
|
| 33 |
+
return "cpu"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ==========================================================
|
| 37 |
+
# BENCHMARK
|
| 38 |
+
# ==========================================================
|
| 39 |
+
#
|
| 40 |
+
# v45: ARC-Challenge ONLY by default.
|
| 41 |
+
#
|
| 42 |
+
# Every previous version merged ARC-Challenge with ARC-Easy to triple
|
| 43 |
+
# the training pool. That is not defensible: they are distinct published
|
| 44 |
+
# benchmarks with different difficulty distributions, every paper reports
|
| 45 |
+
# them separately, and merging both makes the numbers incomparable to
|
| 46 |
+
# prior work AND confounds every effect with the Easy/Challenge mixture
|
| 47 |
+
# ratio. Set to "merged" only if you explicitly want the larger pool for
|
| 48 |
+
# training, and say so in any write-up.
|
| 49 |
+
#
|
| 50 |
+
# Cache files are named after this value (see cache_filename), so a
|
| 51 |
+
# Challenge cache and a merged cache cannot silently be mistaken for
|
| 52 |
+
# each other -- which is exactly what would have happened with the old
|
| 53 |
+
# flat "arc_train.pt" name.
|
| 54 |
+
ARC_CONFIG = "ARC-Challenge" # "ARC-Challenge" | "ARC-Easy" | "merged"
|
| 55 |
+
|
| 56 |
+
ARC_SPLIT_SIZES = {
|
| 57 |
+
"ARC-Challenge": {"train": 1119, "validation": 299, "test": 1172},
|
| 58 |
+
"ARC-Easy": {"train": 2251, "validation": 570, "test": 2376},
|
| 59 |
+
"merged": {"train": 3370, "validation": 869, "test": 3548},
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def arc_slug(arc_config=None):
|
| 64 |
+
|
| 65 |
+
return (arc_config or ARC_CONFIG).lower().replace("-", "_")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def cache_filename(split, arc_config=None):
|
| 69 |
+
"""
|
| 70 |
+
e.g. "arc_challenge_train.pt". The benchmark identity is part of the
|
| 71 |
+
filename on purpose -- see the ARC_CONFIG note above.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
return f"{arc_slug(arc_config)}_{split}.pt"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ==========================================================
|
| 78 |
+
# ENCODER
|
| 79 |
+
# ==========================================================
|
| 80 |
+
|
| 81 |
+
# v41: switched from all-mpnet-base-v2 (768-dim) to all-MiniLM-L6-v2
|
| 82 |
+
# (384-dim) and n_qubits 12 -> 6. The quantum circuit's simulation cost
|
| 83 |
+
# scales roughly O(n_qubits * 2^n_qubits) -- 12 qubits was the dominant
|
| 84 |
+
# per-epoch cost. Changing EMBEDDING_DIM invalidates any cache built
|
| 85 |
+
# under the old dim; training/dataset.py refuses to silently load a
|
| 86 |
+
# dim-mismatched cache (see its cache-loading dim check).
|
| 87 |
+
#
|
| 88 |
+
# KNOWN STRUCTURAL LIMIT: everything the generator LLM knows reaches the
|
| 89 |
+
# trainable model only through these frozen 6-layer sentence embeddings.
|
| 90 |
+
# That bottleneck is very likely a larger constraint on accuracy than
|
| 91 |
+
# the entire reasoning architecture. v45 works around it in one specific
|
| 92 |
+
# way -- the generator's per-option log-likelihood is cached as an
|
| 93 |
+
# explicit scalar feature (see USE_LLM_PRIOR) so at least that part of
|
| 94 |
+
# the LLM's judgement is not squeezed through MiniLM.
|
| 95 |
+
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
| 96 |
+
EMBEDDING_DIM = 384
|
| 97 |
+
|
| 98 |
+
# ==========================================================
|
| 99 |
+
# MODEL WIDTH (v45: capacity/data ratio)
|
| 100 |
+
# ==========================================================
|
| 101 |
+
#
|
| 102 |
+
# The v44 model was 10,578,677 parameters trained on 800 examples --
|
| 103 |
+
# 13,223 parameters per example. Train loss fell 54% over six epochs
|
| 104 |
+
# while validation accuracy DECLINED monotonically from its epoch-1 peak:
|
| 105 |
+
# it memorized the training set before it could learn any compositional
|
| 106 |
+
# use of the hypotheses. That is a hard confound -- at that ratio you
|
| 107 |
+
# cannot distinguish "hypotheses don't help" from "the model overfits
|
| 108 |
+
# before it learns to use them".
|
| 109 |
+
#
|
| 110 |
+
# Everything downstream of the input projection now runs at MODEL_DIM
|
| 111 |
+
# instead of EMBEDDING_DIM. Cost is quadratic in width across the big
|
| 112 |
+
# pairwise MLPs, so 384 -> 128 cuts the model roughly 9x, to ~1.1M.
|
| 113 |
+
# Set to None to run at full embedding width (the v44 behaviour).
|
| 114 |
+
MODEL_DIM = 128
|
| 115 |
+
|
| 116 |
+
N_QUBITS = 6
|
| 117 |
+
PERSISTENT_STEPS = 3
|
| 118 |
+
|
| 119 |
+
# Which PennyLane device backs the quantum circuit.
|
| 120 |
+
#
|
| 121 |
+
# "auto" -- try lightning.gpu (NVIDIA cuStateVec) first, fall
|
| 122 |
+
# back to the CPU simulator lightning.qubit if it
|
| 123 |
+
# can't be constructed (no GPU, no cuStateVec, or
|
| 124 |
+
# the plugin just isn't installed). Same circuit,
|
| 125 |
+
# same function, same trained result either way --
|
| 126 |
+
# this only changes what executes it. Default.
|
| 127 |
+
# "lightning.gpu" -- require the GPU device; raises loudly instead of
|
| 128 |
+
# silently training 20-30x slower on CPU. Use when
|
| 129 |
+
# a slow run should fail fast rather than limp.
|
| 130 |
+
# "lightning.qubit" -- force the CPU simulator even when a GPU is
|
| 131 |
+
# present, e.g. for a reproducibility check across
|
| 132 |
+
# machines without one.
|
| 133 |
+
#
|
| 134 |
+
# lightning.gpu is NOT in requirements.txt: it needs an NVIDIA GPU, the
|
| 135 |
+
# CUDA toolkit, and NVIDIA's cuStateVec library, none of which exist on a
|
| 136 |
+
# CPU-only machine (this project's own local dev environment, notably).
|
| 137 |
+
# Install it on a CUDA-capable box with:
|
| 138 |
+
# pip install pennylane-lightning[gpu]
|
| 139 |
+
# (the v45 Colab notebook does this in its install cell). "auto" is what
|
| 140 |
+
# makes the same code correct on both.
|
| 141 |
+
QUANTUM_DEVICE = "auto"
|
| 142 |
+
|
| 143 |
+
DROPOUT = 0.15
|
| 144 |
+
|
| 145 |
+
# ==========================================================
|
| 146 |
+
# HYPOTHESIS EVIDENCE (v45: the decisive fix)
|
| 147 |
+
# ==========================================================
|
| 148 |
+
#
|
| 149 |
+
# The v44 protocol asked the LLM, for each option, to "state the
|
| 150 |
+
# reasoning that would make this proposed answer correct". A competent
|
| 151 |
+
# model obliges -- for all four options. It manufactures symmetric
|
| 152 |
+
# support, and four equally fluent justifications contain no evidence
|
| 153 |
+
# about which option is true. Measured on the clean v44 cache (0%
|
| 154 |
+
# fallbacks, alignment verified):
|
| 155 |
+
#
|
| 156 |
+
# argmax diag(H . O) 0.2481 (chance = 0.2500)
|
| 157 |
+
# mean pairwise cos(H_k, H_j) 0.6466
|
| 158 |
+
# mean pairwise cos(O_k, O_j) 0.4773 <- hypotheses LESS diverse
|
| 159 |
+
# than the options they
|
| 160 |
+
# were generated from
|
| 161 |
+
#
|
| 162 |
+
# That is not a bug, it is exactly what the prompt requested, and no
|
| 163 |
+
# downstream architecture can recover a signal that was never generated.
|
| 164 |
+
#
|
| 165 |
+
# v45 generates BOTH directions per option: a supporting hypothesis and
|
| 166 |
+
# an attacking one ("state the specific reason this answer is wrong").
|
| 167 |
+
# A model that can attack a wrong option more convincingly than a right
|
| 168 |
+
# one produces ASYMMETRIC evidence, which is the only thing the
|
| 169 |
+
# marginalization has to work with. K = len(GEN_MODES) * n_options.
|
| 170 |
+
GEN_MODES = ("support", "attack")
|
| 171 |
+
|
| 172 |
+
# Batch size for offline hypothesis generation during cache building.
|
| 173 |
+
# Independent of BATCH_SIZE below -- that one governs the training
|
| 174 |
+
# DataLoader, this one governs how many QUESTIONS are queued before a
|
| 175 |
+
# generation flush. Each question expands into len(GEN_MODES) * n_options
|
| 176 |
+
# prompts, so the actual LLM batch is ~GEN_BATCH_SIZE * 8.
|
| 177 |
+
GEN_BATCH_SIZE = 8
|
| 178 |
+
|
| 179 |
+
# One 15-30 word sentence is ~45 tokens at 1.35 tokens/word, so 64 is
|
| 180 |
+
# ~50% headroom and parse_one() truncates at 60 words regardless.
|
| 181 |
+
#
|
| 182 |
+
# This is the main lever on cache-build time. generate() runs until every
|
| 183 |
+
# sequence in the batch hits EOS or this cap, so one rambling sample
|
| 184 |
+
# drags the whole batch to the ceiling -- lowering the cap bounds that
|
| 185 |
+
# directly. Build on a GPU if you have one; this is 20-30x faster there.
|
| 186 |
+
GEN_MAX_NEW_TOKENS = 64
|
| 187 |
+
|
| 188 |
+
# 0.3 is low for a method whose premise is maintaining DIVERSE
|
| 189 |
+
# hypotheses in superposition.
|
| 190 |
+
GEN_TEMPERATURE = 0.7
|
| 191 |
+
|
| 192 |
+
# ==========================================================
|
| 193 |
+
# INTERFERENCE (v45: making the Born rule non-trivial)
|
| 194 |
+
# ==========================================================
|
| 195 |
+
#
|
| 196 |
+
# With real, non-negative amplitudes, amplitude = exp(-E/2T) followed by
|
| 197 |
+
# L2 normalization and squaring is algebraically identical to
|
| 198 |
+
# softmax(-E/T) -- verified numerically to fp32 epsilon (5.96e-08). It
|
| 199 |
+
# adds no expressive content over a temperature-scaled softmax, and
|
| 200 |
+
# |sum_k c_k|^2 = sum_k |c_k|^2 exactly because there are no phases.
|
| 201 |
+
# No interference is possible; the module named "interference" could not
|
| 202 |
+
# interfere.
|
| 203 |
+
#
|
| 204 |
+
# v45 gives each hypothesis a learned PHASE. The answer amplitude for
|
| 205 |
+
# option n becomes A_n = sum_k c_k v_kn with c_k, v_kn complex, and
|
| 206 |
+
# P(n) ∝ |A_n|^2 now carries cross-terms 2*Re(c_i conj(c_j) ...) that
|
| 207 |
+
# can be NEGATIVE. Hypotheses can cancel. This is the one place the
|
| 208 |
+
# project earns the word "quantum", and it is falsifiable: models/
|
| 209 |
+
# interference.py reports `interference_ratio`, and PHASE_MODE="zero"
|
| 210 |
+
# / "classical" are parameter-matched controls in the ablation grid.
|
| 211 |
+
#
|
| 212 |
+
# "learned" -- full complex amplitudes, phases from the model
|
| 213 |
+
# "zero" -- coherent sum with all phases pinned to 0 (constructive
|
| 214 |
+
# only; isolates "phases" from "coherent summation")
|
| 215 |
+
# "classical" -- diagonal/decohered: P(n) = sum_k |c_k|^2 |v_kn|^2,
|
| 216 |
+
# i.e. exactly the v44 probability-weighted mixture
|
| 217 |
+
PHASE_MODE = "learned"
|
| 218 |
+
|
| 219 |
+
# v46: `destructive_fraction` is NOT on its own evidence of anything.
|
| 220 |
+
#
|
| 221 |
+
# With K = 2N matched support/attack pairs it is a step function of one
|
| 222 |
+
# scalar, models/full_model.py::polarity_phase. Sweeping that scalar
|
| 223 |
+
# through CoherentCollapse with everything else fixed gives 0.000 from 0
|
| 224 |
+
# to 1.6 rad, 0.494 at 2.4, 0.994 at 2.8, and 1.000 at 3.0 and above. It
|
| 225 |
+
# is initialized at pi -- already past the step -- so it reads 1.0 for an
|
| 226 |
+
# untrained model and stays there, and it cannot report the SIGN of the
|
| 227 |
+
# effect either: saturating at ~1 is consistent with the coherent ranking
|
| 228 |
+
# being far better than the decohered mixture AND with it being far worse.
|
| 229 |
+
#
|
| 230 |
+
# The test that decides is `coherent_acc` vs `classical_acc` in
|
| 231 |
+
# training/evaluate.py -- ranking options by the coherent sum against
|
| 232 |
+
# ranking them by the decohered limit of the same amplitudes over the same
|
| 233 |
+
# energies. Neither passes through the LLM prior, so the delta is the
|
| 234 |
+
# phase channel and nothing else.
|
| 235 |
+
|
| 236 |
+
# Where the hypothesis phase comes from when PHASE_MODE == "learned":
|
| 237 |
+
# "circuit" -- atan2(<Y>, <X>) of the quantum layer's own measurements,
|
| 238 |
+
# so the circuit drives a genuinely quantum operation
|
| 239 |
+
# instead of being a 54-parameter MLP wrapper
|
| 240 |
+
# "learned" -- a small classical head on the reasoned hypotheses
|
| 241 |
+
# "circuit" silently falls back to "learned" when there is no bottleneck
|
| 242 |
+
# layer (backend="none").
|
| 243 |
+
PHASE_SOURCE = "circuit"
|
| 244 |
+
|
| 245 |
+
# Mixing across hypotheses inside PersistentReasoner:
|
| 246 |
+
# "orthogonal" -- Cayley transform of an antisymmetric coupling matrix.
|
| 247 |
+
# Norm-preserving and invertible, so it provably cannot
|
| 248 |
+
# contract distinct hypotheses onto one vector, and its
|
| 249 |
+
# weights are SIGNED so cancellation is possible.
|
| 250 |
+
# "softmax" -- v44 behaviour: row-stochastic, hence a convex
|
| 251 |
+
# combination, hence incapable of cancellation. Kept as
|
| 252 |
+
# an ablation arm, not as a default.
|
| 253 |
+
MIXING = "orthogonal"
|
| 254 |
+
|
| 255 |
+
# Add the generator's cached per-option log-likelihood to the final
|
| 256 |
+
# score as an explicit, learned-weight log-prior. This is the audit's
|
| 257 |
+
# recommendation #1c and it is the only channel through which the LLM's
|
| 258 |
+
# own judgement reaches the answer without passing through the frozen
|
| 259 |
+
# 384-d encoder. It MUST be ablated (see training/ablations.py) and
|
| 260 |
+
# reported -- a system that wins only because of this feature has not
|
| 261 |
+
# demonstrated anything about multi-hypothesis reasoning.
|
| 262 |
+
USE_LLM_PRIOR = True
|
| 263 |
+
|
| 264 |
+
# ==========================================================
|
| 265 |
+
# TRAINING
|
| 266 |
+
# ==========================================================
|
| 267 |
+
|
| 268 |
+
BATCH_SIZE = 16
|
| 269 |
+
EPOCHS = 30
|
| 270 |
+
PATIENCE = 5
|
| 271 |
+
|
| 272 |
+
BASE_LR = 5e-4
|
| 273 |
+
NEW_LR = 2e-4
|
| 274 |
+
|
| 275 |
+
# Raised from 2e-2 with v45's smaller model: at 800 training examples the
|
| 276 |
+
# v44 configuration was still deep in the memorization regime.
|
| 277 |
+
WEIGHT_DECAY = 5e-2
|
| 278 |
+
|
| 279 |
+
LABEL_SMOOTHING = 0.05
|
| 280 |
+
|
| 281 |
+
SEED = 42
|
| 282 |
+
|
| 283 |
+
# Seeds for the multi-seed evaluation protocol. Single-run differences on
|
| 284 |
+
# ARC-Challenge's 299-example validation split have SE ~2.7pt, so 1-3
|
| 285 |
+
# point gaps between ablation arms are indistinguishable from seed noise.
|
| 286 |
+
SEEDS = (42, 43, 44, 45, 46)
|
| 287 |
+
|
| 288 |
+
CACHE_DIR = "./cache"
|
| 289 |
+
CKPT_DIR = "./ckpt"
|
| 290 |
+
|
| 291 |
+
# Bumped whenever the cache layout changes in a way that makes older
|
| 292 |
+
# files unusable.
|
| 293 |
+
#
|
| 294 |
+
# 33 -- added question embeddings ("Q"), per-hypothesis is_fallback
|
| 295 |
+
# flags, per-option generation
|
| 296 |
+
# 45 -- support+attack hypotheses (K = 2N), per-hypothesis polarity and
|
| 297 |
+
# option alignment, cached per-option LLM log-likelihood, and the
|
| 298 |
+
# benchmark identity in the filename
|
| 299 |
+
#
|
| 300 |
+
# A v33 cache CANNOT be migrated to v45: the attacking hypotheses and the
|
| 301 |
+
# option log-likelihoods do not exist in it and only the LLM can produce
|
| 302 |
+
# them. training/dataset.py refuses to load one rather than silently
|
| 303 |
+
# training on half the evidence channels.
|
| 304 |
+
CACHE_VERSION = 45
|
models/__pycache__/answer_selector.cpython-312.pyc
ADDED
|
Binary file (9.17 kB). View file
|
|
|
models/__pycache__/classical_control_layer.cpython-312.pyc
ADDED
|
Binary file (6.93 kB). View file
|
|
|
models/__pycache__/collapse.cpython-312.pyc
ADDED
|
Binary file (5.61 kB). View file
|
|
|
models/__pycache__/encoder.cpython-312.pyc
ADDED
|
Binary file (2.87 kB). View file
|
|
|
models/__pycache__/energy_fusion.cpython-312.pyc
ADDED
|
Binary file (2.9 kB). View file
|
|
|
models/__pycache__/full_model.cpython-312.pyc
ADDED
|
Binary file (14.3 kB). View file
|
|
|
models/__pycache__/generator.cpython-312.pyc
ADDED
|
Binary file (16.3 kB). View file
|
|
|
models/__pycache__/interference.cpython-312.pyc
ADDED
|
Binary file (11.9 kB). View file
|
|
|
models/__pycache__/persistent_reasoner.cpython-312.pyc
ADDED
|
Binary file (11.4 kB). View file
|
|
|
models/__pycache__/quantum_layer.cpython-312.pyc
ADDED
|
Binary file (12.1 kB). View file
|
|
|
models/__pycache__/validator.cpython-312.pyc
ADDED
|
Binary file (9.68 kB). View file
|
|
|
models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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from config import DROPOUT
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def bounded_phase(x):
|
| 11 |
+
"""Bound an unconstrained head into (-pi, pi]."""
|
| 12 |
+
|
| 13 |
+
return math.pi * torch.tanh(x)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _masked_standardize(x, valid, eps=1e-5):
|
| 17 |
+
"""
|
| 18 |
+
Zero-mean, unit-variance per sample over the (K, N) axes, ignoring
|
| 19 |
+
padded entries. Padded entries are returned as 0.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
m = valid.to(x.dtype)
|
| 23 |
+
|
| 24 |
+
n = m.sum(dim=(1, 2), keepdim=True).clamp(min=1.0)
|
| 25 |
+
|
| 26 |
+
mean = (x * m).sum(dim=(1, 2), keepdim=True) / n
|
| 27 |
+
|
| 28 |
+
var = (((x - mean) ** 2) * m).sum(dim=(1, 2), keepdim=True) / n
|
| 29 |
+
|
| 30 |
+
out = (x - mean) / torch.sqrt(var + eps)
|
| 31 |
+
|
| 32 |
+
return out * m
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class EnergyAnswerSelector(nn.Module):
|
| 36 |
+
"""
|
| 37 |
+
Pairwise (hypothesis x option) energy. Lower energy = better answer.
|
| 38 |
+
|
| 39 |
+
Fixed in v45
|
| 40 |
+
------------
|
| 41 |
+
* **Confidence self-gating removed.** v44 computed
|
| 42 |
+
`energy = energy * (0.5 + confidence)` where `confidence` was a
|
| 43 |
+
head reading the same features as the energy itself. That is a
|
| 44 |
+
multiplicative self-gate: it rescales each (k, n) pair by a
|
| 45 |
+
different learned factor, so energies stop being comparable across
|
| 46 |
+
pairs -- and the marginalization downstream compares them. It has
|
| 47 |
+
no probabilistic interpretation and it is gone. (The earlier form,
|
| 48 |
+
`energy / confidence.clamp(min=0.2)`, was worse: up to 5x
|
| 49 |
+
amplification straight into a +/-6 clamp, which saturated and
|
| 50 |
+
killed gradients -- the documented cause of the reverted warm-start
|
| 51 |
+
experiment.)
|
| 52 |
+
|
| 53 |
+
* **The three energies are scale-normalized before fusion.** They
|
| 54 |
+
live on different scales: `learned_energy` is an unbounded MLP
|
| 55 |
+
output, while `hamiltonian_energy` and `cosine_energy` are inner
|
| 56 |
+
products of normalized vectors, bounded in roughly [-1, 1].
|
| 57 |
+
Combining them with per-pair softmax weights meant the learned term
|
| 58 |
+
dominated by magnitude alone, whatever the weights said. Each term
|
| 59 |
+
is now standardized over the (K, N) axes per sample first, so the
|
| 60 |
+
fusion weights actually express a preference.
|
| 61 |
+
|
| 62 |
+
* **Alignment and polarity features.** v45 generates a supporting and
|
| 63 |
+
an attacking hypothesis per option. `align[k, n] = 1` when
|
| 64 |
+
hypothesis k is ABOUT option n, and `polarity[k] = +/-1` says which
|
| 65 |
+
direction it argues. Without these the support/attack distinction
|
| 66 |
+
would be a sign bit floating free of the option it refers to, and
|
| 67 |
+
"the objection to option 2" could not be used as evidence against
|
| 68 |
+
option 2 specifically.
|
| 69 |
+
|
| 70 |
+
* **Phase head.** Emits theta_kn for models/interference.py, so the
|
| 71 |
+
compatibility amplitude v_kn = t_kn * exp(i theta_kn) is complex
|
| 72 |
+
and the Born rule stops being a reparameterized softmax.
|
| 73 |
+
|
| 74 |
+
Kept from v44
|
| 75 |
+
-------------
|
| 76 |
+
Question conditioning (`use_question`) -- the largest measured single
|
| 77 |
+
effect in this project: on cached ARC embeddings a plain MLP scores
|
| 78 |
+
0.3585 from options alone and 0.4849 once the question is available.
|
| 79 |
+
The question text sat in the cache un-encoded for the project's whole
|
| 80 |
+
history.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(self, dim, use_question=True):
|
| 84 |
+
|
| 85 |
+
super().__init__()
|
| 86 |
+
|
| 87 |
+
self.use_question = use_question
|
| 88 |
+
|
| 89 |
+
self.hamiltonian = nn.Linear(dim, dim, bias=False)
|
| 90 |
+
|
| 91 |
+
# [H, O, H-O, H*O] plus, when available, [Q, Q*O, Q-O];
|
| 92 |
+
# then three scalars: align, polarity, align*polarity.
|
| 93 |
+
n_vec = 7 if use_question else 4
|
| 94 |
+
|
| 95 |
+
n_feat = dim * n_vec + 3
|
| 96 |
+
|
| 97 |
+
self.energy_net = nn.Sequential(
|
| 98 |
+
nn.Linear(n_feat, dim * 2),
|
| 99 |
+
nn.GELU(),
|
| 100 |
+
nn.LayerNorm(dim * 2),
|
| 101 |
+
nn.Dropout(DROPOUT),
|
| 102 |
+
nn.Linear(dim * 2, dim),
|
| 103 |
+
nn.GELU(),
|
| 104 |
+
nn.Linear(dim, 1),
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
self.fusion = nn.Sequential(
|
| 108 |
+
nn.Linear(n_feat, dim),
|
| 109 |
+
nn.GELU(),
|
| 110 |
+
nn.Linear(dim, 3),
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Deliberately a single linear map rather than an MLP: the phase
|
| 114 |
+
# is one bounded scalar per pair and this keeps the parameter
|
| 115 |
+
# cost of the complex-amplitude extension negligible, so a gain
|
| 116 |
+
# from it cannot be explained as extra capacity.
|
| 117 |
+
self.phase_net = nn.Linear(n_feat, 1)
|
| 118 |
+
|
| 119 |
+
self.temperature = nn.Parameter(torch.tensor(1.0))
|
| 120 |
+
|
| 121 |
+
def forward(self, H, O, Q=None, align=None, polarity=None,
|
| 122 |
+
H_mask=None, O_mask=None):
|
| 123 |
+
"""
|
| 124 |
+
H : (B, K, D)
|
| 125 |
+
O : (B, N, D)
|
| 126 |
+
Q : (B, D)
|
| 127 |
+
align : (B, K, N) 1.0 where hypothesis k is about option n
|
| 128 |
+
polarity : (B, K) +1 support / -1 attack
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
B, K, D = H.shape
|
| 132 |
+
_, N, _ = O.shape
|
| 133 |
+
|
| 134 |
+
H = F.normalize(H, dim=-1)
|
| 135 |
+
O = F.normalize(O, dim=-1)
|
| 136 |
+
|
| 137 |
+
O_proj = self.hamiltonian(O)
|
| 138 |
+
|
| 139 |
+
H_exp = H.unsqueeze(2).expand(B, K, N, D)
|
| 140 |
+
O_exp = O_proj.unsqueeze(1).expand(B, K, N, D)
|
| 141 |
+
|
| 142 |
+
parts = [H_exp, O_exp, H_exp - O_exp, H_exp * O_exp]
|
| 143 |
+
|
| 144 |
+
if self.use_question:
|
| 145 |
+
|
| 146 |
+
if Q is None:
|
| 147 |
+
raise ValueError(
|
| 148 |
+
"EnergyAnswerSelector was built with use_question=True "
|
| 149 |
+
"but forward() got Q=None. Rebuild the cache so it "
|
| 150 |
+
"carries question embeddings, or construct the model "
|
| 151 |
+
"with use_question=False."
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
Q_exp = F.normalize(Q, dim=-1).view(B, 1, 1, D).expand(B, K, N, D)
|
| 155 |
+
|
| 156 |
+
parts += [Q_exp, Q_exp * O_exp, Q_exp - O_exp]
|
| 157 |
+
|
| 158 |
+
if align is None:
|
| 159 |
+
align = torch.zeros(B, K, N, device=H.device, dtype=H.dtype)
|
| 160 |
+
|
| 161 |
+
if polarity is None:
|
| 162 |
+
polarity = torch.zeros(B, K, device=H.device, dtype=H.dtype)
|
| 163 |
+
|
| 164 |
+
a = align.unsqueeze(-1)
|
| 165 |
+
p = polarity.view(B, K, 1, 1).expand(B, K, N, 1)
|
| 166 |
+
|
| 167 |
+
parts += [a, p, a * p]
|
| 168 |
+
|
| 169 |
+
features = torch.cat(parts, dim=-1)
|
| 170 |
+
|
| 171 |
+
# ------------------------------------------------------------
|
| 172 |
+
# Three energies, standardized onto a common scale
|
| 173 |
+
# ------------------------------------------------------------
|
| 174 |
+
|
| 175 |
+
valid = torch.ones(B, K, N, dtype=torch.bool, device=H.device)
|
| 176 |
+
|
| 177 |
+
if H_mask is not None:
|
| 178 |
+
valid = valid & H_mask.view(B, K, 1)
|
| 179 |
+
|
| 180 |
+
if O_mask is not None:
|
| 181 |
+
valid = valid & O_mask.view(B, 1, N)
|
| 182 |
+
|
| 183 |
+
learned_energy = self.energy_net(features).squeeze(-1)
|
| 184 |
+
|
| 185 |
+
hamiltonian_energy = -torch.einsum("bkd,bnd->bkn", H, O_proj)
|
| 186 |
+
|
| 187 |
+
cosine_energy = -F.cosine_similarity(H_exp, O_exp, dim=-1)
|
| 188 |
+
|
| 189 |
+
learned_energy = _masked_standardize(learned_energy, valid)
|
| 190 |
+
hamiltonian_energy = _masked_standardize(hamiltonian_energy, valid)
|
| 191 |
+
cosine_energy = _masked_standardize(cosine_energy, valid)
|
| 192 |
+
|
| 193 |
+
fusion_weights = F.softmax(self.fusion(features), dim=-1)
|
| 194 |
+
|
| 195 |
+
energy = (
|
| 196 |
+
fusion_weights[..., 0] * learned_energy
|
| 197 |
+
+ fusion_weights[..., 1] * hamiltonian_energy
|
| 198 |
+
+ fusion_weights[..., 2] * cosine_energy
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
temperature = 0.5 + F.softplus(self.temperature)
|
| 202 |
+
|
| 203 |
+
energy = energy / temperature
|
| 204 |
+
|
| 205 |
+
# Wide safety net against runaway energies. Should not bind in
|
| 206 |
+
# normal training -- if it does, something upstream is diverging.
|
| 207 |
+
energy = torch.clamp(energy, -12, 12)
|
| 208 |
+
|
| 209 |
+
# ------------------------------------------------------------
|
| 210 |
+
# Compatibility phase for the coherent collapse
|
| 211 |
+
# ------------------------------------------------------------
|
| 212 |
+
|
| 213 |
+
phase = bounded_phase(self.phase_net(features).squeeze(-1))
|
| 214 |
+
|
| 215 |
+
return {
|
| 216 |
+
"energy": energy,
|
| 217 |
+
"phase": phase,
|
| 218 |
+
"fusion_weights": fusion_weights,
|
| 219 |
+
}
|
models/classical_control_layer.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from config import DROPOUT
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ClassicalControlLayer(nn.Module):
|
| 11 |
+
"""
|
| 12 |
+
Parameter-matched classical control for QuantumEvolutionLayer.
|
| 13 |
+
|
| 14 |
+
Same interface (H -> (q_state, energy)) and the same surrounding
|
| 15 |
+
compress / expand / fusion_gate / correction / energy_head
|
| 16 |
+
architecture -- the only thing that differs is what sits between
|
| 17 |
+
compress and expand. QuantumEvolutionLayer runs a PennyLane circuit
|
| 18 |
+
there; this runs a small classical MLP operating at the same width
|
| 19 |
+
(n_qubits*3, matching the circuit's flat measurement-vector size).
|
| 20 |
+
|
| 21 |
+
Used to isolate whether QuantumEvolutionLayer's benefit (if any)
|
| 22 |
+
comes from the quantum circuit's structure (superposition +
|
| 23 |
+
entanglement) specifically, or just from having *some* extra
|
| 24 |
+
nonlinear transform in that position of the pipeline. The quantum
|
| 25 |
+
circuit itself is a tiny fraction of QuantumEvolutionLayer's total
|
| 26 |
+
parameters (54 out of ~1.12M at dim=384, n_qubits=6, n_layers=3),
|
| 27 |
+
so keeping everything else identical and only swapping that one
|
| 28 |
+
small piece keeps total parameter count within a fraction of a
|
| 29 |
+
percent either way -- see the printed counts below.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, dim, n_qubits=6, n_layers=3, verbose=False):
|
| 33 |
+
|
| 34 |
+
super().__init__()
|
| 35 |
+
|
| 36 |
+
self.n_qubits = n_qubits
|
| 37 |
+
|
| 38 |
+
self.compress = nn.Sequential(
|
| 39 |
+
nn.Linear(dim, dim),
|
| 40 |
+
nn.GELU(),
|
| 41 |
+
nn.Linear(dim, n_qubits),
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
bottleneck_dim = n_qubits * 3
|
| 45 |
+
|
| 46 |
+
# n_layers of nonlinear transform at the circuit's measurement
|
| 47 |
+
# width: first layer projects n_qubits -> bottleneck_dim, the
|
| 48 |
+
# remaining (n_layers - 1) stay at bottleneck_dim.
|
| 49 |
+
transform_layers = [nn.Linear(n_qubits, bottleneck_dim), nn.GELU()]
|
| 50 |
+
|
| 51 |
+
for _ in range(n_layers - 1):
|
| 52 |
+
transform_layers += [
|
| 53 |
+
nn.Linear(bottleneck_dim, bottleneck_dim),
|
| 54 |
+
nn.GELU(),
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
self.classical_transform = nn.Sequential(*transform_layers)
|
| 58 |
+
|
| 59 |
+
self.expand = nn.Sequential(
|
| 60 |
+
nn.Linear(bottleneck_dim, dim),
|
| 61 |
+
nn.GELU(),
|
| 62 |
+
nn.LayerNorm(dim),
|
| 63 |
+
nn.Dropout(DROPOUT),
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
self.fusion_gate = nn.Sequential(
|
| 67 |
+
nn.Linear(dim * 2, dim),
|
| 68 |
+
nn.GELU(),
|
| 69 |
+
nn.Linear(dim, dim),
|
| 70 |
+
nn.Sigmoid(),
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
self.correction = nn.Sequential(
|
| 74 |
+
nn.Linear(dim, dim),
|
| 75 |
+
nn.GELU(),
|
| 76 |
+
nn.Dropout(DROPOUT),
|
| 77 |
+
nn.Linear(dim, dim),
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# Matches QuantumEvolutionLayer.phase_gain exactly. The phase
|
| 81 |
+
# itself is read off the classical bottleneck the same way the
|
| 82 |
+
# circuit's is read off its measurements (atan2 of two thirds of
|
| 83 |
+
# the vector), so the two arms differ only in what produced the
|
| 84 |
+
# numbers -- which is the entire point of this control.
|
| 85 |
+
self.phase_gain = nn.Parameter(torch.tensor(1.0))
|
| 86 |
+
|
| 87 |
+
self.energy_head = nn.Sequential(
|
| 88 |
+
nn.Linear(dim, dim),
|
| 89 |
+
nn.GELU(),
|
| 90 |
+
nn.LayerNorm(dim),
|
| 91 |
+
nn.Linear(dim, dim // 2),
|
| 92 |
+
nn.GELU(),
|
| 93 |
+
nn.Linear(dim // 2, 1),
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
self.norm = nn.LayerNorm(dim)
|
| 97 |
+
|
| 98 |
+
if verbose:
|
| 99 |
+
total_params = sum(p.numel() for p in self.parameters())
|
| 100 |
+
transform_params = sum(
|
| 101 |
+
p.numel() for p in self.classical_transform.parameters()
|
| 102 |
+
)
|
| 103 |
+
print(
|
| 104 |
+
f"[ClassicalControlLayer] total parameters: {total_params:,} "
|
| 105 |
+
f"(classical_transform slot: {transform_params:,})"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def forward(self, H):
|
| 109 |
+
|
| 110 |
+
B, K, D = H.shape
|
| 111 |
+
|
| 112 |
+
H_norm = F.normalize(H, dim=-1)
|
| 113 |
+
|
| 114 |
+
z = self.compress(H_norm.reshape(B * K, D))
|
| 115 |
+
|
| 116 |
+
# Same squashing QuantumEvolutionLayer applies before its circuit
|
| 117 |
+
# (there, to fit PennyLane's rotation-angle range) -- kept
|
| 118 |
+
# identical here so both arms see the exact same input
|
| 119 |
+
# distribution into the part that actually differs.
|
| 120 |
+
z = math.pi * torch.tanh(z)
|
| 121 |
+
|
| 122 |
+
measurements = self.classical_transform(z)
|
| 123 |
+
|
| 124 |
+
n = self.n_qubits
|
| 125 |
+
|
| 126 |
+
x_mean = measurements[:, :n].mean(dim=-1)
|
| 127 |
+
y_mean = measurements[:, n:2 * n].mean(dim=-1)
|
| 128 |
+
|
| 129 |
+
phase = self.phase_gain * torch.atan2(y_mean, x_mean)
|
| 130 |
+
|
| 131 |
+
q = self.expand(measurements)
|
| 132 |
+
|
| 133 |
+
H_flat = H.reshape(B * K, D)
|
| 134 |
+
|
| 135 |
+
gate = self.fusion_gate(torch.cat([H_flat, q], dim=-1))
|
| 136 |
+
|
| 137 |
+
q = gate * q + (1 - gate) * H_flat
|
| 138 |
+
|
| 139 |
+
q = self.norm(q + self.correction(q))
|
| 140 |
+
|
| 141 |
+
energy = self.energy_head(q)
|
| 142 |
+
|
| 143 |
+
energy = torch.tanh(energy).squeeze(-1)
|
| 144 |
+
|
| 145 |
+
q = q.reshape(B, K, D)
|
| 146 |
+
|
| 147 |
+
energy = energy.reshape(B, K)
|
| 148 |
+
|
| 149 |
+
phase = phase.reshape(B, K)
|
| 150 |
+
|
| 151 |
+
return q, energy, phase
|
models/collapse.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class CollapseController(nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
Adaptive per-sample temperature for the collapse, plus the collapse
|
| 9 |
+
diagnostics.
|
| 10 |
+
|
| 11 |
+
What changed in v45
|
| 12 |
+
-------------------
|
| 13 |
+
This module used to apply the Born rule itself: amplitude =
|
| 14 |
+
exp(-E/2T), L2-normalize, square. models/validator.py applied the
|
| 15 |
+
same pattern over a different axis, so the "Born rule" appeared twice
|
| 16 |
+
in one forward pass -- and in both places it was, with real
|
| 17 |
+
non-negative amplitudes, algebraically identical to softmax(-E/T)
|
| 18 |
+
(verified to fp32 epsilon, 5.96e-08). Two copies of a softmax wearing
|
| 19 |
+
a physics name.
|
| 20 |
+
|
| 21 |
+
The amplitudes now live in exactly one place, models/interference.py,
|
| 22 |
+
where they are COMPLEX and the squaring therefore produces genuine
|
| 23 |
+
cross-terms. What is left here is the part that was actually doing
|
| 24 |
+
something: a per-sample temperature read off the energy distribution,
|
| 25 |
+
which controls how sharply the state collapses for this particular
|
| 26 |
+
question, and the diagnostics.
|
| 27 |
+
|
| 28 |
+
Fixed in the v44 audit, kept
|
| 29 |
+
----------------------------
|
| 30 |
+
* `diversity` (variance of energy across hypotheses) and `spread`
|
| 31 |
+
(max - min) were ADDED to the loss with positive coefficients. Both
|
| 32 |
+
are globally minimized at exactly zero, attained when every
|
| 33 |
+
hypothesis has identical energy -- the loss was paying the model to
|
| 34 |
+
collapse the superposition it exists to maintain, and training duly
|
| 35 |
+
drove them to 8.2e-09 and 1.4e-08. They are diagnostics here; the
|
| 36 |
+
loss uses -tanh(diversity), a saturating reward.
|
| 37 |
+
* The fixed entropy target (0.5 nats) was applied here AND in
|
| 38 |
+
training/losses.py -- double-counted, and anti-calibration in the
|
| 39 |
+
first place. Gone; cross-entropy calibrates the distribution.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self):
|
| 43 |
+
|
| 44 |
+
super().__init__()
|
| 45 |
+
|
| 46 |
+
self.encoder = nn.Sequential(
|
| 47 |
+
nn.Linear(1, 32),
|
| 48 |
+
nn.GELU(),
|
| 49 |
+
nn.Linear(32, 32),
|
| 50 |
+
nn.GELU(),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
self.temperature = nn.Linear(32, 1)
|
| 54 |
+
|
| 55 |
+
self.confidence = nn.Sequential(
|
| 56 |
+
nn.Linear(32, 16),
|
| 57 |
+
nn.GELU(),
|
| 58 |
+
nn.Linear(16, 1),
|
| 59 |
+
nn.Sigmoid(),
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def forward(self, energy, mask=None):
|
| 63 |
+
"""
|
| 64 |
+
energy : (B, K) fused per-hypothesis energy
|
| 65 |
+
mask : (B, K) bool, True for real hypotheses
|
| 66 |
+
|
| 67 |
+
Returns a per-sample temperature of shape (B, 1) for
|
| 68 |
+
models/interference.py, and diagnostics on the raw energy.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
raw_energy = energy
|
| 72 |
+
|
| 73 |
+
z = self.encoder(torch.tanh(energy).unsqueeze(-1))
|
| 74 |
+
|
| 75 |
+
if mask is not None:
|
| 76 |
+
# Don't let padded hypotheses shift the pooled statistics the
|
| 77 |
+
# temperature and confidence heads read.
|
| 78 |
+
m = mask.unsqueeze(-1).to(z.dtype)
|
| 79 |
+
z_global = (z * m).sum(dim=1) / m.sum(dim=1).clamp(min=1.0)
|
| 80 |
+
else:
|
| 81 |
+
z_global = z.mean(dim=1)
|
| 82 |
+
|
| 83 |
+
temperature = 0.3 + F.softplus(self.temperature(z_global))
|
| 84 |
+
|
| 85 |
+
confidence = self.confidence(z_global).squeeze(-1)
|
| 86 |
+
|
| 87 |
+
# ------------------------------------------------------------
|
| 88 |
+
# Diagnostics (NOT loss terms -- see class docstring)
|
| 89 |
+
# ------------------------------------------------------------
|
| 90 |
+
|
| 91 |
+
if mask is not None:
|
| 92 |
+
valid = mask.to(raw_energy.dtype)
|
| 93 |
+
n = valid.sum(dim=1).clamp(min=1.0)
|
| 94 |
+
mean_e = (raw_energy * valid).sum(dim=1) / n
|
| 95 |
+
diversity = (
|
| 96 |
+
((raw_energy - mean_e.unsqueeze(-1)) ** 2) * valid
|
| 97 |
+
).sum(dim=1) / n
|
| 98 |
+
spread = (
|
| 99 |
+
raw_energy.masked_fill(~mask, float("-inf")).max(dim=1).values
|
| 100 |
+
- raw_energy.masked_fill(~mask, float("inf")).min(dim=1).values
|
| 101 |
+
)
|
| 102 |
+
else:
|
| 103 |
+
diversity = raw_energy.var(dim=1)
|
| 104 |
+
spread = raw_energy.max(dim=1).values - raw_energy.min(dim=1).values
|
| 105 |
+
|
| 106 |
+
return {
|
| 107 |
+
"temperature": temperature,
|
| 108 |
+
"confidence": confidence,
|
| 109 |
+
"raw_energy": raw_energy,
|
| 110 |
+
"diversity": diversity.mean(),
|
| 111 |
+
"spread": spread.mean(),
|
| 112 |
+
}
|
models/encoder.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
|
| 4 |
+
from transformers import AutoTokenizer, AutoModel
|
| 5 |
+
|
| 6 |
+
from config import EMBEDDING_MODEL, EMBEDDING_DIM, resolve_device
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class HypothesisEncoder:
|
| 10 |
+
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
model_name=EMBEDDING_MODEL,
|
| 14 |
+
device=None
|
| 15 |
+
):
|
| 16 |
+
|
| 17 |
+
self.device = device or resolve_device()
|
| 18 |
+
|
| 19 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 20 |
+
|
| 21 |
+
self.model = AutoModel.from_pretrained(model_name).to(self.device)
|
| 22 |
+
|
| 23 |
+
self.model.eval()
|
| 24 |
+
|
| 25 |
+
for p in self.model.parameters():
|
| 26 |
+
p.requires_grad = False
|
| 27 |
+
|
| 28 |
+
self.dim = self.model.config.hidden_size
|
| 29 |
+
|
| 30 |
+
if model_name == EMBEDDING_MODEL:
|
| 31 |
+
# Everything downstream (dataset.py, sample_inference.py, ...)
|
| 32 |
+
# reads dim from config.EMBEDDING_DIM rather than this instance,
|
| 33 |
+
# so a silent mismatch here would surface as a shape error far
|
| 34 |
+
# away from its cause. Catch it at the source instead.
|
| 35 |
+
assert self.dim == EMBEDDING_DIM, (
|
| 36 |
+
f"{model_name} produces {self.dim}-dim embeddings but "
|
| 37 |
+
f"config.EMBEDDING_DIM is {EMBEDDING_DIM}. Update config.py."
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
print(f"[ENCODER] Using {model_name}")
|
| 41 |
+
print(f"[ENCODER] Embedding dimension: {self.dim}")
|
| 42 |
+
|
| 43 |
+
@torch.no_grad()
|
| 44 |
+
def encode(self, texts):
|
| 45 |
+
|
| 46 |
+
inputs = self.tokenizer(
|
| 47 |
+
texts, padding=True, truncation=True, max_length=128, return_tensors="pt"
|
| 48 |
+
).to(self.device)
|
| 49 |
+
|
| 50 |
+
outputs = self.model(**inputs)
|
| 51 |
+
|
| 52 |
+
hidden = outputs.last_hidden_state
|
| 53 |
+
|
| 54 |
+
mask = inputs["attention_mask"].unsqueeze(-1)
|
| 55 |
+
|
| 56 |
+
pooled = (hidden * mask).sum(dim=1)
|
| 57 |
+
|
| 58 |
+
counts = mask.sum(dim=1)
|
| 59 |
+
|
| 60 |
+
pooled = pooled / counts.clamp(min=1e-9)
|
| 61 |
+
|
| 62 |
+
pooled = F.normalize(pooled, dim=-1)
|
| 63 |
+
|
| 64 |
+
return pooled
|
models/energy_fusion.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class EnergyFusion(nn.Module):
|
| 6 |
+
"""
|
| 7 |
+
Combines the answer selector's per-hypothesis energy with the optional
|
| 8 |
+
quantum and validator energy signals into a single collapse energy,
|
| 9 |
+
via learned sigmoid-gated blend weights.
|
| 10 |
+
|
| 11 |
+
Fixed in the audit
|
| 12 |
+
------------------
|
| 13 |
+
* Hypothesis energy was reduced over options with a hard
|
| 14 |
+
`torch.min`, which routes gradient to the argmin option only. It is
|
| 15 |
+
now a temperature-controlled soft-min (-tau * logsumexp(-E/tau)),
|
| 16 |
+
which is smooth, gradient-complete, and recovers the hard min as
|
| 17 |
+
tau -> 0.
|
| 18 |
+
* The validator term was added unbounded (`+ w * validator_energy`)
|
| 19 |
+
while the quantum term was a convex blend -- inconsistent
|
| 20 |
+
semantics, and the validator could dominate the energy scale
|
| 21 |
+
arbitrarily. Both are convex blends now.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self):
|
| 25 |
+
|
| 26 |
+
super().__init__()
|
| 27 |
+
|
| 28 |
+
self.energy_alpha = nn.Parameter(torch.tensor(0.0))
|
| 29 |
+
|
| 30 |
+
# Learnable validator guidance weight. sigmoid(0.0) = 0.5 at init --
|
| 31 |
+
# moderate influence, model can learn to trust it more or suppress
|
| 32 |
+
# it based on whether the validator's signal actually helps.
|
| 33 |
+
self.validator_alpha = nn.Parameter(torch.tensor(0.0))
|
| 34 |
+
|
| 35 |
+
def forward(
|
| 36 |
+
self,
|
| 37 |
+
answer_energy,
|
| 38 |
+
quantum_energy=None,
|
| 39 |
+
validator_energy=None,
|
| 40 |
+
tau=1.0,
|
| 41 |
+
option_mask=None,
|
| 42 |
+
):
|
| 43 |
+
"""
|
| 44 |
+
answer_energy : (B, K, N)
|
| 45 |
+
option_mask : (B, N) bool, True for real options -- padded
|
| 46 |
+
options must not win the soft-min.
|
| 47 |
+
returns : (B, K) collapse energy
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
e = answer_energy / tau
|
| 51 |
+
|
| 52 |
+
if option_mask is not None:
|
| 53 |
+
e = e.masked_fill(~option_mask.unsqueeze(1), float("inf"))
|
| 54 |
+
|
| 55 |
+
# Soft-min over options: -tau * logsumexp(-e / tau).
|
| 56 |
+
collapse_energy = -tau * torch.logsumexp(-e / tau, dim=-1)
|
| 57 |
+
|
| 58 |
+
if quantum_energy is not None:
|
| 59 |
+
|
| 60 |
+
alpha = torch.sigmoid(self.energy_alpha)
|
| 61 |
+
|
| 62 |
+
collapse_energy = alpha * collapse_energy + (1.0 - alpha) * quantum_energy
|
| 63 |
+
|
| 64 |
+
if validator_energy is not None:
|
| 65 |
+
|
| 66 |
+
v_weight = torch.sigmoid(self.validator_alpha)
|
| 67 |
+
|
| 68 |
+
collapse_energy = (
|
| 69 |
+
(1.0 - v_weight) * collapse_energy + v_weight * validator_energy
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
return collapse_energy
|
models/full_model.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from config import (
|
| 8 |
+
EMBEDDING_DIM,
|
| 9 |
+
MODEL_DIM,
|
| 10 |
+
PHASE_MODE,
|
| 11 |
+
PHASE_SOURCE,
|
| 12 |
+
MIXING,
|
| 13 |
+
USE_LLM_PRIOR,
|
| 14 |
+
QUANTUM_DEVICE,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
from models.validator import HypothesisValidator
|
| 18 |
+
from models.quantum_layer import QuantumEvolutionLayer
|
| 19 |
+
from models.classical_control_layer import ClassicalControlLayer
|
| 20 |
+
from models.persistent_reasoner import PersistentReasoner
|
| 21 |
+
from models.collapse import CollapseController
|
| 22 |
+
from models.answer_selector import EnergyAnswerSelector, bounded_phase
|
| 23 |
+
from models.energy_fusion import EnergyFusion
|
| 24 |
+
from models.interference import CoherentCollapse
|
| 25 |
+
|
| 26 |
+
BACKENDS = ("quantum", "classical_control", "none")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _masked_zscore(x, mask, eps=1e-5):
|
| 30 |
+
"""Per-sample standardization over the option axis, ignoring padding."""
|
| 31 |
+
|
| 32 |
+
m = mask.to(x.dtype) if mask is not None else torch.ones_like(x)
|
| 33 |
+
|
| 34 |
+
n = m.sum(dim=1, keepdim=True).clamp(min=1.0)
|
| 35 |
+
|
| 36 |
+
mean = (x * m).sum(dim=1, keepdim=True) / n
|
| 37 |
+
|
| 38 |
+
var = (((x - mean) ** 2) * m).sum(dim=1, keepdim=True) / n
|
| 39 |
+
|
| 40 |
+
return ((x - mean) / torch.sqrt(var + eps)) * m
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class QAIRvNext(nn.Module):
|
| 44 |
+
"""
|
| 45 |
+
qAIR-v45.
|
| 46 |
+
|
| 47 |
+
Q, H, O -> in_proj (384 -> MODEL_DIM)
|
| 48 |
+
-> PersistentReasoner (orthogonal mixing)
|
| 49 |
+
-> Quantum / classical layer (state + energy + PHASE)
|
| 50 |
+
-> HypothesisValidator (-> potential, fed back)
|
| 51 |
+
-> EnergyAnswerSelector (E_kn + compatibility phase)
|
| 52 |
+
-> EnergyFusion (-> E_k)
|
| 53 |
+
-> CollapseController (per-sample temperature)
|
| 54 |
+
-> CoherentCollapse (complex amplitudes,
|
| 55 |
+
|sum_k c_k v_kn|^2)
|
| 56 |
+
-> + LLM log-prior (optional, ablatable)
|
| 57 |
+
|
| 58 |
+
Three things are different from v44 in ways that matter, all of them
|
| 59 |
+
responses to specific measured failures rather than tuning:
|
| 60 |
+
|
| 61 |
+
1. **Width.** v44 ran 10.58M parameters over 800 training examples --
|
| 62 |
+
13,223 per example -- and its best validation accuracy was at
|
| 63 |
+
epoch 1, declining monotonically after while train loss fell 54%.
|
| 64 |
+
Everything past `in_proj` now runs at MODEL_DIM (128), roughly 1.1M
|
| 65 |
+
parameters. Below that ratio, "hypotheses don't help" and "the
|
| 66 |
+
model memorizes before it learns to use them" are not
|
| 67 |
+
distinguishable, so no mechanistic claim from v44 was safe.
|
| 68 |
+
|
| 69 |
+
2. **Evidence channels.** The cache now carries a supporting AND an
|
| 70 |
+
attacking hypothesis per option, each tagged with its polarity and
|
| 71 |
+
the option it argues about (`align`). v44's support-only
|
| 72 |
+
hypotheses were measured at argmax diag(H.O) = 0.2481 against a
|
| 73 |
+
chance of 0.2500 -- literally zero discriminative signal, because
|
| 74 |
+
asking a competent LLM to justify all four options gets all four
|
| 75 |
+
justified.
|
| 76 |
+
|
| 77 |
+
3. **Genuine interference.** The final distribution is
|
| 78 |
+
|sum_k c_k v_kn|^2 over complex amplitudes, so hypotheses can
|
| 79 |
+
cancel. See models/interference.py. `phase_mode="classical"`
|
| 80 |
+
recovers v44's real-amplitude mixture as a control, and
|
| 81 |
+
`interference_ratio` is reported every epoch so an inert phase
|
| 82 |
+
channel shows up as a number rather than hiding behind a plausible
|
| 83 |
+
accuracy.
|
| 84 |
+
|
| 85 |
+
The LLM log-prior (`use_llm_prior`) deserves its own warning. It adds
|
| 86 |
+
the generator's own cached per-option log-likelihood to the final
|
| 87 |
+
score. That is legitimate -- it is the only channel by which the LLM's
|
| 88 |
+
judgement reaches the answer without being squeezed through a frozen
|
| 89 |
+
384-d sentence encoder -- but it also means the model can score well
|
| 90 |
+
while ignoring every hypothesis. Always read
|
| 91 |
+
`evaluation/input_ablation.py` alongside accuracy, and always run the
|
| 92 |
+
`use_llm_prior=False` arm before attributing a gain to reasoning.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
dim=EMBEDDING_DIM,
|
| 98 |
+
model_dim=MODEL_DIM,
|
| 99 |
+
use_quantum=True,
|
| 100 |
+
use_validator=True,
|
| 101 |
+
persistent_steps=3,
|
| 102 |
+
n_qubits=12,
|
| 103 |
+
backend=None,
|
| 104 |
+
use_question=True,
|
| 105 |
+
validator_feedback=True,
|
| 106 |
+
keep_trajectory=False,
|
| 107 |
+
phase_mode=PHASE_MODE,
|
| 108 |
+
phase_source=PHASE_SOURCE,
|
| 109 |
+
mixing=MIXING,
|
| 110 |
+
use_llm_prior=USE_LLM_PRIOR,
|
| 111 |
+
use_attack=True,
|
| 112 |
+
quantum_device=QUANTUM_DEVICE,
|
| 113 |
+
verbose=False,
|
| 114 |
+
):
|
| 115 |
+
|
| 116 |
+
super().__init__()
|
| 117 |
+
|
| 118 |
+
# backend selects what occupies the quantum-layer slot:
|
| 119 |
+
# "quantum" -- QuantumEvolutionLayer (PennyLane circuit)
|
| 120 |
+
# "classical_control" -- ClassicalControlLayer (parameter-matched
|
| 121 |
+
# classical MLP in the same slot)
|
| 122 |
+
# "none" -- no bottleneck layer at all
|
| 123 |
+
# use_quantum is a backward-compatible alias (True -> "quantum",
|
| 124 |
+
# False -> "none") used only when backend isn't given explicitly.
|
| 125 |
+
# The submodule is stored as self.quantum regardless of backend so
|
| 126 |
+
# training/train.py's quantum./validator.-prefixed lower-LR
|
| 127 |
+
# parameter group applies identically to both -- the comparison
|
| 128 |
+
# between them should differ only in what's inside that slot, not
|
| 129 |
+
# in how it is optimized.
|
| 130 |
+
if backend is None:
|
| 131 |
+
backend = "quantum" if use_quantum else "none"
|
| 132 |
+
|
| 133 |
+
if backend not in BACKENDS:
|
| 134 |
+
raise ValueError(f"backend must be one of {BACKENDS}, got {backend!r}")
|
| 135 |
+
|
| 136 |
+
d = model_dim or dim
|
| 137 |
+
|
| 138 |
+
self.embed_dim = dim
|
| 139 |
+
self.model_dim = d
|
| 140 |
+
|
| 141 |
+
self.backend = backend
|
| 142 |
+
self.use_quantum = backend != "none"
|
| 143 |
+
self.use_validator = use_validator
|
| 144 |
+
self.use_question = use_question
|
| 145 |
+
self.use_llm_prior = use_llm_prior
|
| 146 |
+
self.use_attack = use_attack
|
| 147 |
+
self.phase_mode = phase_mode
|
| 148 |
+
self.phase_source = phase_source
|
| 149 |
+
self.mixing = mixing
|
| 150 |
+
self.quantum_device = quantum_device
|
| 151 |
+
self.persistent_steps = persistent_steps
|
| 152 |
+
|
| 153 |
+
# The validator computes a `potential` field that was never fed
|
| 154 |
+
# back into the reasoner before v44: forward() called
|
| 155 |
+
# self.reasoner(H) with no potential argument even though
|
| 156 |
+
# PersistentReasoner accepted one, so the validator only ever
|
| 157 |
+
# reached the answer through validator_energy. With feedback on,
|
| 158 |
+
# the reasoner runs twice: once to get hypotheses good enough to
|
| 159 |
+
# validate, then again guided by the resulting potential.
|
| 160 |
+
self.validator_feedback = validator_feedback and use_validator
|
| 161 |
+
|
| 162 |
+
# ------------------------------------------------------------
|
| 163 |
+
# Input projection: 384-d frozen embeddings -> model width
|
| 164 |
+
# ------------------------------------------------------------
|
| 165 |
+
|
| 166 |
+
if d == dim:
|
| 167 |
+
self.in_proj = nn.Identity()
|
| 168 |
+
else:
|
| 169 |
+
self.in_proj = nn.Sequential(nn.Linear(dim, d), nn.LayerNorm(d))
|
| 170 |
+
|
| 171 |
+
# Marks a hypothesis as supporting (+1) or attacking (-1) inside
|
| 172 |
+
# the vector itself, so the reasoner's mixing can tell the two
|
| 173 |
+
# channels apart rather than treating them as interchangeable.
|
| 174 |
+
self.polarity_embed = nn.Parameter(torch.zeros(d))
|
| 175 |
+
|
| 176 |
+
self.reasoner = PersistentReasoner(
|
| 177 |
+
d, steps=persistent_steps, keep_trajectory=keep_trajectory,
|
| 178 |
+
mixing=mixing,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
if backend == "quantum":
|
| 182 |
+
self.quantum = QuantumEvolutionLayer(
|
| 183 |
+
d, n_qubits=n_qubits, verbose=verbose,
|
| 184 |
+
quantum_device=quantum_device,
|
| 185 |
+
)
|
| 186 |
+
elif backend == "classical_control":
|
| 187 |
+
self.quantum = ClassicalControlLayer(d, n_qubits=n_qubits, verbose=verbose)
|
| 188 |
+
|
| 189 |
+
if use_validator:
|
| 190 |
+
self.validator = HypothesisValidator(d, use_question=use_question)
|
| 191 |
+
|
| 192 |
+
self.selector = EnergyAnswerSelector(d, use_question=use_question)
|
| 193 |
+
|
| 194 |
+
self.fusion = EnergyFusion()
|
| 195 |
+
|
| 196 |
+
self.collapse = CollapseController()
|
| 197 |
+
|
| 198 |
+
self.interference = CoherentCollapse(phase_mode=phase_mode)
|
| 199 |
+
|
| 200 |
+
# Classical fallback phase head, used when phase_source ==
|
| 201 |
+
# "learned" or when there is no bottleneck layer to read a phase
|
| 202 |
+
# off. One linear map to one bounded scalar per hypothesis.
|
| 203 |
+
self.phase_head = nn.Linear(d, 1)
|
| 204 |
+
|
| 205 |
+
# Relative phase between the two evidence directions, initialized
|
| 206 |
+
# to pi.
|
| 207 |
+
#
|
| 208 |
+
# This is the one piece of physics the architecture actually
|
| 209 |
+
# asserts, and it is worth stating plainly: an objection to
|
| 210 |
+
# option n is the NEGATION of the support for option n, so the
|
| 211 |
+
# natural relative phase between them is pi, where their
|
| 212 |
+
# amplitudes cancel. Without it the phase channel starts
|
| 213 |
+
# essentially uniform -- measured at initialization, phases from
|
| 214 |
+
# both the circuit and the learned head are concentrated tightly
|
| 215 |
+
# enough that the coherent sum is purely constructive and
|
| 216 |
+
# `destructive_fraction` is exactly 0. The mechanism the whole
|
| 217 |
+
# v45 claim rests on would begin dead and have to discover
|
| 218 |
+
# cancellation from a gradient signal that only exists once
|
| 219 |
+
# cancellation happens.
|
| 220 |
+
#
|
| 221 |
+
# It is a learnable parameter, not a constant: if support and
|
| 222 |
+
# attack turn out not to be opposites in any useful sense, the
|
| 223 |
+
# model can drive it to 0 and recover the in-phase behaviour.
|
| 224 |
+
# `phase_mode="zero"` and `phase_mode="classical"` bypass it
|
| 225 |
+
# entirely, so it is covered by the existing controls.
|
| 226 |
+
self.polarity_phase = nn.Parameter(torch.tensor(math.pi))
|
| 227 |
+
|
| 228 |
+
# Weight on the cached LLM log-prior. softplus keeps it
|
| 229 |
+
# non-negative (a prior the model can trust or ignore, but never
|
| 230 |
+
# invert); softplus(-1.0) = 0.313 at init -- present, not
|
| 231 |
+
# dominant.
|
| 232 |
+
self.llm_prior_weight = nn.Parameter(torch.tensor(-1.0))
|
| 233 |
+
|
| 234 |
+
def _run_quantum(self, H):
|
| 235 |
+
|
| 236 |
+
if H.is_cuda:
|
| 237 |
+
|
| 238 |
+
# Only construct a "cuda" autocast context on an actual CUDA
|
| 239 |
+
# tensor -- on CPU/MPS this context wouldn't do anything
|
| 240 |
+
# anyway (autocast is disabled either way in the training
|
| 241 |
+
# loop for non-CUDA devices), and some PyTorch versions
|
| 242 |
+
# validate device_type at construction even when disabled.
|
| 243 |
+
#
|
| 244 |
+
# Forcing fp32 here applies regardless of which PennyLane
|
| 245 |
+
# device is attached (see config.QUANTUM_DEVICE) -- PennyLane's
|
| 246 |
+
# autograd through lightning.qubit isn't mixed-precision safe,
|
| 247 |
+
# and lightning.gpu's cuStateVec backend is fp32/fp64
|
| 248 |
+
# statevectors, not fp16/bf16, so autocast has nothing valid to
|
| 249 |
+
# do to either one.
|
| 250 |
+
from torch.amp import autocast
|
| 251 |
+
|
| 252 |
+
with autocast(device_type="cuda", enabled=False):
|
| 253 |
+
return self.quantum(H.float())
|
| 254 |
+
|
| 255 |
+
return self.quantum(H.float())
|
| 256 |
+
|
| 257 |
+
def forward(self, H, O, Q=None, y=None, H_mask=None, O_mask=None,
|
| 258 |
+
polarity=None, align=None, llm_logprob=None):
|
| 259 |
+
"""
|
| 260 |
+
H : (B, K, D_embed) hypothesis embeddings, K = 2N
|
| 261 |
+
O : (B, N, D_embed) option embeddings
|
| 262 |
+
Q : (B, D_embed) question embedding
|
| 263 |
+
y : (B,) labels, training only -- used solely to build
|
| 264 |
+
the validator's BCE target, never to compute energy
|
| 265 |
+
H_mask : (B, K) bool, True for real hypotheses
|
| 266 |
+
O_mask : (B, N) bool, True for real options
|
| 267 |
+
polarity : (B, K) +1 support / -1 attack
|
| 268 |
+
align : (B, K, N) 1 where hypothesis k is about option n
|
| 269 |
+
llm_logprob : (B, N) cached per-option LLM log-likelihood
|
| 270 |
+
|
| 271 |
+
Masks matter: collate_fn pads ragged option/hypothesis counts with
|
| 272 |
+
zeros, and before the v44 audit those masks were computed and then
|
| 273 |
+
never passed to the model, so zero-padded options participated in
|
| 274 |
+
every reduction and could be returned as the argmax prediction.
|
| 275 |
+
"""
|
| 276 |
+
|
| 277 |
+
B, K, _ = H.shape
|
| 278 |
+
N = O.shape[1]
|
| 279 |
+
|
| 280 |
+
if H_mask is None:
|
| 281 |
+
H_mask = torch.ones(B, K, dtype=torch.bool, device=H.device)
|
| 282 |
+
|
| 283 |
+
if O_mask is None:
|
| 284 |
+
O_mask = torch.ones(B, N, dtype=torch.bool, device=O.device)
|
| 285 |
+
|
| 286 |
+
if polarity is None:
|
| 287 |
+
polarity = torch.ones(B, K, device=H.device, dtype=H.dtype)
|
| 288 |
+
|
| 289 |
+
# Support-only ablation: drop the attacking channel without
|
| 290 |
+
# touching the cache, so the comparison is over identical data.
|
| 291 |
+
if not self.use_attack:
|
| 292 |
+
H_mask = H_mask & (polarity >= 0)
|
| 293 |
+
|
| 294 |
+
# ------------------------------------------------------------
|
| 295 |
+
# Project into model width
|
| 296 |
+
# ------------------------------------------------------------
|
| 297 |
+
|
| 298 |
+
H = self.in_proj(H)
|
| 299 |
+
O = self.in_proj(O)
|
| 300 |
+
Q = self.in_proj(Q) if Q is not None else None
|
| 301 |
+
|
| 302 |
+
H = H + polarity.unsqueeze(-1) * self.polarity_embed
|
| 303 |
+
|
| 304 |
+
H = H * H_mask.unsqueeze(-1).to(H.dtype)
|
| 305 |
+
|
| 306 |
+
# ------------------------------------------------------------
|
| 307 |
+
# Reason
|
| 308 |
+
# ------------------------------------------------------------
|
| 309 |
+
|
| 310 |
+
H, trajectory, interaction = self.reasoner(H, mask=H_mask)
|
| 311 |
+
|
| 312 |
+
quantum_energy = None
|
| 313 |
+
quantum_phase = None
|
| 314 |
+
|
| 315 |
+
if self.use_quantum:
|
| 316 |
+
|
| 317 |
+
q_state, quantum_energy, quantum_phase = self._run_quantum(H)
|
| 318 |
+
|
| 319 |
+
H = H + q_state
|
| 320 |
+
|
| 321 |
+
validator_out = None
|
| 322 |
+
validator_energy = None
|
| 323 |
+
potential = None
|
| 324 |
+
|
| 325 |
+
if self.use_validator:
|
| 326 |
+
|
| 327 |
+
validator_out = self.validator(
|
| 328 |
+
H, O, Q=Q, y=y, H_mask=H_mask, O_mask=O_mask,
|
| 329 |
+
align=align, polarity=polarity,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
potential = validator_out["potential"]
|
| 333 |
+
|
| 334 |
+
validator_energy = validator_out["validator_energy"]
|
| 335 |
+
|
| 336 |
+
if self.validator_feedback:
|
| 337 |
+
|
| 338 |
+
# Second reasoning pass, guided by the validator's
|
| 339 |
+
# potential -- the feedback edge the architecture was
|
| 340 |
+
# described as having but did not until v44.
|
| 341 |
+
H, trajectory2, interaction = self.reasoner(
|
| 342 |
+
H, potential=potential, mask=H_mask
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
trajectory = trajectory + trajectory2
|
| 346 |
+
|
| 347 |
+
if self.use_quantum:
|
| 348 |
+
q_state, quantum_energy, quantum_phase = self._run_quantum(H)
|
| 349 |
+
H = H + q_state
|
| 350 |
+
|
| 351 |
+
validator_out = self.validator(
|
| 352 |
+
H, O, Q=Q, y=y, H_mask=H_mask, O_mask=O_mask,
|
| 353 |
+
align=align, polarity=polarity,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
potential = validator_out["potential"]
|
| 357 |
+
|
| 358 |
+
validator_energy = validator_out["validator_energy"]
|
| 359 |
+
|
| 360 |
+
# ------------------------------------------------------------
|
| 361 |
+
# Pairwise energy + compatibility phase
|
| 362 |
+
# ------------------------------------------------------------
|
| 363 |
+
|
| 364 |
+
selector = self.selector(
|
| 365 |
+
H, O, Q=Q, align=align, polarity=polarity,
|
| 366 |
+
H_mask=H_mask, O_mask=O_mask,
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
answer_energy = selector["energy"]
|
| 370 |
+
|
| 371 |
+
collapse_energy = self.fusion(
|
| 372 |
+
answer_energy,
|
| 373 |
+
quantum_energy=quantum_energy,
|
| 374 |
+
validator_energy=validator_energy,
|
| 375 |
+
option_mask=O_mask,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
collapse_out = self.collapse(collapse_energy, mask=H_mask)
|
| 379 |
+
|
| 380 |
+
# ------------------------------------------------------------
|
| 381 |
+
# Hypothesis phase
|
| 382 |
+
# ------------------------------------------------------------
|
| 383 |
+
|
| 384 |
+
if self.phase_source == "circuit" and quantum_phase is not None:
|
| 385 |
+
phase_h = quantum_phase
|
| 386 |
+
else:
|
| 387 |
+
phase_h = bounded_phase(self.phase_head(H).squeeze(-1))
|
| 388 |
+
|
| 389 |
+
# +0 for support (polarity +1), +polarity_phase for attack (-1).
|
| 390 |
+
phase_h = phase_h + 0.5 * (1.0 - polarity) * self.polarity_phase
|
| 391 |
+
|
| 392 |
+
phase_h = phase_h * H_mask.to(phase_h.dtype)
|
| 393 |
+
|
| 394 |
+
# ------------------------------------------------------------
|
| 395 |
+
# Coherent collapse -- |sum_k c_k v_kn|^2
|
| 396 |
+
# ------------------------------------------------------------
|
| 397 |
+
|
| 398 |
+
coherent = self.interference(
|
| 399 |
+
collapse_energy,
|
| 400 |
+
answer_energy,
|
| 401 |
+
phase_h=phase_h,
|
| 402 |
+
phase_kn=selector["phase"],
|
| 403 |
+
H_mask=H_mask,
|
| 404 |
+
O_mask=O_mask,
|
| 405 |
+
hyp_temperature=collapse_out["temperature"],
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
scores = coherent["log_probs"]
|
| 409 |
+
|
| 410 |
+
# ------------------------------------------------------------
|
| 411 |
+
# LLM log-prior (explicit, weighted, ablatable)
|
| 412 |
+
# ------------------------------------------------------------
|
| 413 |
+
|
| 414 |
+
llm_term = None
|
| 415 |
+
|
| 416 |
+
if self.use_llm_prior and llm_logprob is not None:
|
| 417 |
+
|
| 418 |
+
# Standardized per sample: raw mean-token log-likelihoods sit
|
| 419 |
+
# around -2 to -8 with a scale that varies with option length,
|
| 420 |
+
# and an unnormalized additive term at that scale would swamp
|
| 421 |
+
# log_probs outright.
|
| 422 |
+
llm_term = _masked_zscore(llm_logprob, O_mask)
|
| 423 |
+
|
| 424 |
+
scores = scores + F.softplus(self.llm_prior_weight) * llm_term
|
| 425 |
+
|
| 426 |
+
# Padded options must never be predicted or carry probability
|
| 427 |
+
# mass in the cross-entropy.
|
| 428 |
+
neg_inf = torch.finfo(scores.dtype).min / 2
|
| 429 |
+
scores = scores.masked_fill(~O_mask, neg_inf)
|
| 430 |
+
|
| 431 |
+
# Renormalized, so `scores` is a genuine log-probability vector
|
| 432 |
+
# and calibration metrics (evaluation ECE) are meaningful.
|
| 433 |
+
#
|
| 434 |
+
# The floor is not cosmetic: without it a padded option lands at
|
| 435 |
+
# exactly -inf, and label smoothing -- which puts a little mass on
|
| 436 |
+
# EVERY class -- multiplies that by epsilon and returns inf. The
|
| 437 |
+
# loss then NaNs on any batch containing a 3-option question,
|
| 438 |
+
# which ARC has. At -30 a padded option carries 9e-14 of the
|
| 439 |
+
# probability mass, i.e. nothing, while staying finite.
|
| 440 |
+
scores = torch.log_softmax(scores, dim=1).clamp(min=-30.0)
|
| 441 |
+
|
| 442 |
+
collapse_probs = coherent["collapse_probs"]
|
| 443 |
+
|
| 444 |
+
entropy = -(
|
| 445 |
+
collapse_probs * torch.log(collapse_probs + 1e-8)
|
| 446 |
+
).sum(dim=1).mean()
|
| 447 |
+
|
| 448 |
+
return {
|
| 449 |
+
"scores": scores,
|
| 450 |
+
"answer_energy": answer_energy,
|
| 451 |
+
"collapse_energy": collapse_energy,
|
| 452 |
+
"collapse_probs": collapse_probs,
|
| 453 |
+
"quantum_energy": quantum_energy,
|
| 454 |
+
"quantum_phase": quantum_phase,
|
| 455 |
+
"phase_h": phase_h,
|
| 456 |
+
"phase_kn": selector["phase"],
|
| 457 |
+
"interference": coherent["interference"],
|
| 458 |
+
"interference_ratio": coherent["interference_ratio"],
|
| 459 |
+
"phase_effect": coherent["phase_effect"],
|
| 460 |
+
"destructive_fraction": coherent["destructive_fraction"],
|
| 461 |
+
"coherent_contrast": coherent["coherent_contrast"],
|
| 462 |
+
"classical_weights": coherent["classical"],
|
| 463 |
+
"coherent_weights": coherent["coherent"],
|
| 464 |
+
"llm_prior": llm_term,
|
| 465 |
+
"llm_prior_weight": F.softplus(self.llm_prior_weight).detach(),
|
| 466 |
+
"entropy": entropy,
|
| 467 |
+
"diversity": collapse_out["diversity"],
|
| 468 |
+
"spread": collapse_out["spread"],
|
| 469 |
+
"peak": collapse_probs.max(dim=1).values.mean(),
|
| 470 |
+
"collapse_confidence": collapse_out["confidence"],
|
| 471 |
+
"validator_potential": potential,
|
| 472 |
+
"trajectory": trajectory,
|
| 473 |
+
"attention": interaction,
|
| 474 |
+
"validator": validator_out,
|
| 475 |
+
"H_mask": H_mask,
|
| 476 |
+
"O_mask": O_mask,
|
| 477 |
+
# Post-reasoning hypotheses, so training/evaluate.py can
|
| 478 |
+
# distinguish "the hypotheses merged into one vector" from
|
| 479 |
+
# "the selector learned to ignore them". Both make the
|
| 480 |
+
# multi-hypothesis mechanism inert, with different fixes.
|
| 481 |
+
"H_reasoned": H,
|
| 482 |
+
}
|
models/generator.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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5 |
+
--------------------------
|
| 6 |
+
This is the decisive change in v45, and the reason for it is worth
|
| 7 |
+
stating precisely, because it is a DESIGN flaw rather than a bug and no
|
| 8 |
+
amount of downstream architecture could have compensated for it.
|
| 9 |
+
|
| 10 |
+
v44 asked the LLM, for each option: "state the reasoning that would make
|
| 11 |
+
this proposed answer correct." A competent model obliges -- for all four
|
| 12 |
+
options. It manufactures symmetric support. Four equally fluent
|
| 13 |
+
justifications contain no evidence about which option is true, so the
|
| 14 |
+
hypotheses were, information-theoretically, close to constant with
|
| 15 |
+
respect to the label. Measured on the clean v44 cache (0% fallbacks,
|
| 16 |
+
alignment verified by construction, question encoded):
|
| 17 |
+
|
| 18 |
+
argmax diag(H . O) 0.2481 chance = 0.2500
|
| 19 |
+
mean pairwise cos(H_k, H_j) 0.6466
|
| 20 |
+
mean pairwise cos(O_k, O_j) 0.4773
|
| 21 |
+
|
| 22 |
+
The hypotheses were LESS diverse than the options they were generated
|
| 23 |
+
from, and their agreement with their own option carried exactly zero
|
| 24 |
+
information about correctness. That single fact explains every
|
| 25 |
+
downstream observation without needing any of the four bugs the v44
|
| 26 |
+
audit found: the selector ignored H because H was uninformative, the
|
| 27 |
+
collapse distribution was uniform because there was nothing to
|
| 28 |
+
discriminate, and accuracy tracked option priors because that was the
|
| 29 |
+
only signal present.
|
| 30 |
+
|
| 31 |
+
v45 generates TWO hypotheses per option:
|
| 32 |
+
|
| 33 |
+
support -- why this answer would be correct (as in v44)
|
| 34 |
+
attack -- the specific reason it is wrong
|
| 35 |
+
|
| 36 |
+
The model will happily fabricate an attack on the correct option too;
|
| 37 |
+
that is expected and is not a failure. The hypothesis being tested is
|
| 38 |
+
that an attack on a genuinely wrong option lands on a concrete
|
| 39 |
+
mechanism, while an attack on the correct one comes out generic or
|
| 40 |
+
self-contradictory -- an ASYMMETRY between the two channels. That
|
| 41 |
+
asymmetry is the only thing the marginalization has to work with, and
|
| 42 |
+
whether it exists at all is now measured directly at cache-build time
|
| 43 |
+
(training/dataset.py::report_quality) rather than assumed.
|
| 44 |
+
|
| 45 |
+
Alignment (v44, kept)
|
| 46 |
+
---------------------
|
| 47 |
+
One hypothesis per (question, option, mode) pair, each in its own
|
| 48 |
+
completion. Alignment is positional and cannot silently drift, which is
|
| 49 |
+
what broke pre-v44 caches where a free-form multi-hypothesis completion
|
| 50 |
+
was split on newlines and line k routinely described option k-1.
|
| 51 |
+
|
| 52 |
+
Option log-likelihood
|
| 53 |
+
---------------------
|
| 54 |
+
`score_options` caches the generator's own length-normalized
|
| 55 |
+
log-likelihood for each option. This is the direct-LLM baseline computed
|
| 56 |
+
once, offline -- and, more importantly, the only channel through which
|
| 57 |
+
the LLM's judgement reaches the trainable model without being squeezed
|
| 58 |
+
through the frozen 384-d sentence encoder.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
import re
|
| 62 |
+
import torch
|
| 63 |
+
|
| 64 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 65 |
+
|
| 66 |
+
from config import (
|
| 67 |
+
resolve_device,
|
| 68 |
+
GEN_MAX_NEW_TOKENS,
|
| 69 |
+
GEN_TEMPERATURE,
|
| 70 |
+
GEN_MODES,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
LLM_NAME = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 74 |
+
|
| 75 |
+
SYSTEM_PROMPT = "You are an expert scientific reasoning system."
|
| 76 |
+
|
| 77 |
+
# +1 support / -1 attack. The sign is carried through the cache and into
|
| 78 |
+
# the model as a per-hypothesis feature, so the selector can treat "the
|
| 79 |
+
# attack on option n" differently from "the support for option n"
|
| 80 |
+
# instead of averaging the two into mush.
|
| 81 |
+
POLARITY = {"support": 1.0, "attack": -1.0}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class HypothesisGenerator:
|
| 85 |
+
|
| 86 |
+
def __init__(self, device=None):
|
| 87 |
+
|
| 88 |
+
self.device = device or resolve_device()
|
| 89 |
+
|
| 90 |
+
# fp16 has no efficient kernels on most CPUs (and isn't relevant
|
| 91 |
+
# on MPS the same way it is on CUDA) -- only use it on an actual
|
| 92 |
+
# CUDA GPU, fp32 everywhere else.
|
| 93 |
+
dtype = torch.float16 if self.device == "cuda" else torch.float32
|
| 94 |
+
|
| 95 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 96 |
+
LLM_NAME,
|
| 97 |
+
trust_remote_code=True,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
# Left-padding is required for batched causal-LM generation: with
|
| 101 |
+
# left padding every sample's generated continuation starts at the
|
| 102 |
+
# same offset (inputs["input_ids"].shape[1]) regardless of prompt
|
| 103 |
+
# length, so generate_batch() can slice all outputs the same way.
|
| 104 |
+
# score_options() flips this to "right" for the duration of a
|
| 105 |
+
# scoring pass and restores it -- see the note there.
|
| 106 |
+
self.tokenizer.padding_side = "left"
|
| 107 |
+
|
| 108 |
+
if self.tokenizer.pad_token_id is None:
|
| 109 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 110 |
+
|
| 111 |
+
# device_map="auto" (via accelerate) targets CUDA specifically --
|
| 112 |
+
# on CPU/MPS just load normally and move the whole model over.
|
| 113 |
+
if self.device == "cuda":
|
| 114 |
+
|
| 115 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 116 |
+
LLM_NAME,
|
| 117 |
+
torch_dtype=dtype,
|
| 118 |
+
device_map="auto",
|
| 119 |
+
trust_remote_code=True,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
else:
|
| 123 |
+
|
| 124 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 125 |
+
LLM_NAME,
|
| 126 |
+
torch_dtype=dtype,
|
| 127 |
+
trust_remote_code=True,
|
| 128 |
+
).to(self.device)
|
| 129 |
+
|
| 130 |
+
self.model.eval()
|
| 131 |
+
|
| 132 |
+
# ==========================================================
|
| 133 |
+
# PROMPTS -- one option, one mode, at a time
|
| 134 |
+
# ==========================================================
|
| 135 |
+
|
| 136 |
+
def build_prompt(self, question, option, mode):
|
| 137 |
+
|
| 138 |
+
if mode == "support":
|
| 139 |
+
|
| 140 |
+
return (
|
| 141 |
+
f"Question: {question}\n"
|
| 142 |
+
f"Proposed answer: {option}\n\n"
|
| 143 |
+
"In ONE sentence of 15-30 words, state the scientific reasoning "
|
| 144 |
+
"that would make this proposed answer correct. Explain the "
|
| 145 |
+
"mechanism. Do not restate the answer, do not mention other "
|
| 146 |
+
"options, and do not say whether it is right or wrong.\n\n"
|
| 147 |
+
"Reasoning:"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
if mode == "attack":
|
| 151 |
+
|
| 152 |
+
return (
|
| 153 |
+
f"Question: {question}\n"
|
| 154 |
+
f"Proposed answer: {option}\n\n"
|
| 155 |
+
"In ONE sentence of 15-30 words, state the specific scientific "
|
| 156 |
+
"reason this proposed answer FAILS to answer the question. Name "
|
| 157 |
+
"the concrete fact, mechanism, or condition it gets wrong. Be "
|
| 158 |
+
"specific rather than generic; do not restate the answer and do "
|
| 159 |
+
"not mention other options.\n\n"
|
| 160 |
+
"Objection:"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
raise ValueError(f"unknown generation mode {mode!r}")
|
| 164 |
+
|
| 165 |
+
def _chat(self, prompt):
|
| 166 |
+
|
| 167 |
+
return self.tokenizer.apply_chat_template(
|
| 168 |
+
[
|
| 169 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 170 |
+
{"role": "user", "content": prompt},
|
| 171 |
+
],
|
| 172 |
+
tokenize=False,
|
| 173 |
+
add_generation_prompt=True,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# ==========================================================
|
| 177 |
+
# PARSER -- one hypothesis from one completion
|
| 178 |
+
# ==========================================================
|
| 179 |
+
|
| 180 |
+
def parse_one(self, text):
|
| 181 |
+
"""
|
| 182 |
+
Returns a cleaned hypothesis string, or None if the completion
|
| 183 |
+
produced nothing usable. Deliberately does NOT filter on content
|
| 184 |
+
words: the pre-v44 keyword blocklist ("question", "answer",
|
| 185 |
+
"generate", "hypothesis") threw away correct science.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
text = text.strip()
|
| 189 |
+
|
| 190 |
+
# Drop a leading bullet/enumerator/label if present.
|
| 191 |
+
text = re.sub(r"^\s*(?:[-*•]|\(?[A-Za-z0-9]{1,3}[\.\)\:])\s*", "", text)
|
| 192 |
+
|
| 193 |
+
# Strip surrounding markdown emphasis.
|
| 194 |
+
text = re.sub(r"[*_`]+", "", text)
|
| 195 |
+
|
| 196 |
+
# Keep the first sentence-ish chunk; the prompt asks for one
|
| 197 |
+
# sentence but small models often keep going.
|
| 198 |
+
text = text.split("\n")[0].strip()
|
| 199 |
+
|
| 200 |
+
if not text:
|
| 201 |
+
return None
|
| 202 |
+
|
| 203 |
+
words = text.split()
|
| 204 |
+
|
| 205 |
+
if len(words) < 5:
|
| 206 |
+
return None
|
| 207 |
+
|
| 208 |
+
if len(words) > 60:
|
| 209 |
+
text = " ".join(words[:60])
|
| 210 |
+
|
| 211 |
+
return text.strip()
|
| 212 |
+
|
| 213 |
+
# ==========================================================
|
| 214 |
+
# FALLBACK
|
| 215 |
+
# ==========================================================
|
| 216 |
+
|
| 217 |
+
def fallback(self, question, option, mode="support"):
|
| 218 |
+
"""
|
| 219 |
+
Used only when the model returns nothing usable. Callers get an
|
| 220 |
+
is_fallback flag alongside so these can be masked or dropped
|
| 221 |
+
rather than silently treated as real hypotheses.
|
| 222 |
+
|
| 223 |
+
Deliberately does NOT embed the option text. The pre-v44 fallback
|
| 224 |
+
did (`f"{option} correctly explains ..."`), which made it
|
| 225 |
+
maximally cosine-similar to its own option -- exactly the signal
|
| 226 |
+
the selector keys on, so the noise looked like signal.
|
| 227 |
+
"""
|
| 228 |
+
|
| 229 |
+
if mode == "attack":
|
| 230 |
+
return "No specific objection to this option was produced."
|
| 231 |
+
|
| 232 |
+
return "No supporting reasoning was produced for this option."
|
| 233 |
+
|
| 234 |
+
# ==========================================================
|
| 235 |
+
# GENERATE (single question, all its options, all modes)
|
| 236 |
+
# ==========================================================
|
| 237 |
+
|
| 238 |
+
@torch.no_grad()
|
| 239 |
+
def generate(self, question, options, modes=GEN_MODES):
|
| 240 |
+
|
| 241 |
+
out = self.generate_batch_with_flags([question], [options], modes=modes)
|
| 242 |
+
|
| 243 |
+
return out[0]["hypotheses"]
|
| 244 |
+
|
| 245 |
+
@torch.no_grad()
|
| 246 |
+
def generate_with_flags(self, question, options, modes=GEN_MODES):
|
| 247 |
+
|
| 248 |
+
return self.generate_batch_with_flags([question], [options], modes=modes)[0]
|
| 249 |
+
|
| 250 |
+
# ==========================================================
|
| 251 |
+
# GENERATE (batched across questions, options AND modes)
|
| 252 |
+
#
|
| 253 |
+
# Every (question, option, mode) triple becomes its own prompt; the
|
| 254 |
+
# flat list is batched through one model.generate() call and then
|
| 255 |
+
# regrouped. Alignment is positional and cannot drift.
|
| 256 |
+
# ==========================================================
|
| 257 |
+
|
| 258 |
+
@torch.no_grad()
|
| 259 |
+
def generate_batch(self, questions, options_list, modes=GEN_MODES):
|
| 260 |
+
|
| 261 |
+
return [
|
| 262 |
+
item["hypotheses"]
|
| 263 |
+
for item in self.generate_batch_with_flags(
|
| 264 |
+
questions, options_list, modes=modes
|
| 265 |
+
)
|
| 266 |
+
]
|
| 267 |
+
|
| 268 |
+
@torch.no_grad()
|
| 269 |
+
def generate_batch_with_flags(self, questions, options_list, modes=GEN_MODES):
|
| 270 |
+
"""
|
| 271 |
+
Returns one dict per input question:
|
| 272 |
+
|
| 273 |
+
{
|
| 274 |
+
"hypotheses": list[str] length len(modes) * n_options,
|
| 275 |
+
ordered mode-major:
|
| 276 |
+
[sup_0..sup_{N-1}, att_0..att_{N-1}]
|
| 277 |
+
"is_fallback": list[bool] same length
|
| 278 |
+
"polarity": list[float] +1 support / -1 attack
|
| 279 |
+
"hyp_option": list[int] which option each hypothesis is about
|
| 280 |
+
"modes": list[str]
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
Mode-major ordering matters: training/dataset.py::collate_fn
|
| 284 |
+
permutes options for shuffling and reorders each mode block by
|
| 285 |
+
the same permutation, which is only correct if the blocks are
|
| 286 |
+
contiguous and each is in option order.
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
flat_prompts = []
|
| 290 |
+
owners = []
|
| 291 |
+
|
| 292 |
+
for qi, (question, options) in enumerate(zip(questions, options_list)):
|
| 293 |
+
for mode in modes:
|
| 294 |
+
for oi, option in enumerate(options):
|
| 295 |
+
flat_prompts.append(
|
| 296 |
+
self._chat(self.build_prompt(question, option, mode))
|
| 297 |
+
)
|
| 298 |
+
owners.append((qi, oi, mode))
|
| 299 |
+
|
| 300 |
+
inputs = self.tokenizer(
|
| 301 |
+
flat_prompts,
|
| 302 |
+
return_tensors="pt",
|
| 303 |
+
padding=True,
|
| 304 |
+
).to(self.device)
|
| 305 |
+
|
| 306 |
+
outputs = self.model.generate(
|
| 307 |
+
**inputs,
|
| 308 |
+
max_new_tokens=GEN_MAX_NEW_TOKENS,
|
| 309 |
+
temperature=GEN_TEMPERATURE,
|
| 310 |
+
top_p=0.95,
|
| 311 |
+
do_sample=True,
|
| 312 |
+
repetition_penalty=1.10,
|
| 313 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
input_len = inputs["input_ids"].shape[1]
|
| 317 |
+
|
| 318 |
+
results = [
|
| 319 |
+
{
|
| 320 |
+
"hypotheses": [],
|
| 321 |
+
"is_fallback": [],
|
| 322 |
+
"polarity": [],
|
| 323 |
+
"hyp_option": [],
|
| 324 |
+
"modes": [],
|
| 325 |
+
}
|
| 326 |
+
for _ in questions
|
| 327 |
+
]
|
| 328 |
+
|
| 329 |
+
for i, (qi, oi, mode) in enumerate(owners):
|
| 330 |
+
|
| 331 |
+
decoded = self.tokenizer.decode(
|
| 332 |
+
outputs[i][input_len:],
|
| 333 |
+
skip_special_tokens=True,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
hyp = self.parse_one(decoded)
|
| 337 |
+
|
| 338 |
+
if hyp is None:
|
| 339 |
+
hyp = self.fallback(questions[qi], options_list[qi][oi], mode)
|
| 340 |
+
is_fallback = True
|
| 341 |
+
else:
|
| 342 |
+
is_fallback = False
|
| 343 |
+
|
| 344 |
+
r = results[qi]
|
| 345 |
+
r["hypotheses"].append(hyp)
|
| 346 |
+
r["is_fallback"].append(is_fallback)
|
| 347 |
+
r["polarity"].append(POLARITY[mode])
|
| 348 |
+
r["hyp_option"].append(oi)
|
| 349 |
+
r["modes"].append(mode)
|
| 350 |
+
|
| 351 |
+
return results
|
| 352 |
+
|
| 353 |
+
# ==========================================================
|
| 354 |
+
# OPTION LOG-LIKELIHOOD
|
| 355 |
+
# ==========================================================
|
| 356 |
+
|
| 357 |
+
@torch.no_grad()
|
| 358 |
+
def score_options(self, questions, options_list, batch_size=32):
|
| 359 |
+
"""
|
| 360 |
+
Length-normalized log P(option | question) under the generator
|
| 361 |
+
LLM, for every option of every question.
|
| 362 |
+
|
| 363 |
+
Returns a list of float lists, one per question.
|
| 364 |
+
|
| 365 |
+
This is the direct-LLM baseline, computed once at cache-build
|
| 366 |
+
time and stored alongside the embeddings. Two uses:
|
| 367 |
+
|
| 368 |
+
* evaluation/baselines.py reads it straight from the cache, so
|
| 369 |
+
the single most important missing number in the v44 audit
|
| 370 |
+
("does the pipeline beat the model it is built on?") costs
|
| 371 |
+
nothing to report;
|
| 372 |
+
* models/full_model.py can add it to the final score as an
|
| 373 |
+
explicit log-prior. It is the only path by which the LLM's
|
| 374 |
+
judgement reaches the answer without passing through the
|
| 375 |
+
frozen 384-d encoder.
|
| 376 |
+
|
| 377 |
+
Right padding for the duration of the call: with left padding the
|
| 378 |
+
prompt/answer boundary lands at a different offset in every row,
|
| 379 |
+
so the answer-token slice below would be wrong. __init__ sets
|
| 380 |
+
left padding because batched *generation* requires it; both are
|
| 381 |
+
correct, for different operations.
|
| 382 |
+
"""
|
| 383 |
+
|
| 384 |
+
pairs = []
|
| 385 |
+
owners = []
|
| 386 |
+
|
| 387 |
+
for qi, (question, options) in enumerate(zip(questions, options_list)):
|
| 388 |
+
for option in options:
|
| 389 |
+
prompt = f"Question: {question}\nAnswer:"
|
| 390 |
+
pairs.append((prompt, prompt + " " + option))
|
| 391 |
+
owners.append(qi)
|
| 392 |
+
|
| 393 |
+
scores = [None] * len(pairs)
|
| 394 |
+
|
| 395 |
+
previous_side = self.tokenizer.padding_side
|
| 396 |
+
self.tokenizer.padding_side = "right"
|
| 397 |
+
|
| 398 |
+
try:
|
| 399 |
+
|
| 400 |
+
for start in range(0, len(pairs), batch_size):
|
| 401 |
+
|
| 402 |
+
chunk = pairs[start:start + batch_size]
|
| 403 |
+
|
| 404 |
+
prompt_lens = [
|
| 405 |
+
self.tokenizer(p, return_tensors="pt").input_ids.shape[1]
|
| 406 |
+
for p, _ in chunk
|
| 407 |
+
]
|
| 408 |
+
|
| 409 |
+
enc = self.tokenizer(
|
| 410 |
+
[f for _, f in chunk],
|
| 411 |
+
return_tensors="pt",
|
| 412 |
+
padding=True,
|
| 413 |
+
).to(self.device)
|
| 414 |
+
|
| 415 |
+
ids = enc["input_ids"]
|
| 416 |
+
attn = enc["attention_mask"]
|
| 417 |
+
|
| 418 |
+
logits = self.model(**enc).logits[:, :-1]
|
| 419 |
+
|
| 420 |
+
targets = ids[:, 1:]
|
| 421 |
+
|
| 422 |
+
logprobs = torch.log_softmax(logits.float(), dim=-1).gather(
|
| 423 |
+
2, targets.unsqueeze(-1)
|
| 424 |
+
).squeeze(-1)
|
| 425 |
+
|
| 426 |
+
valid = attn[:, 1:].bool()
|
| 427 |
+
|
| 428 |
+
for row in range(len(chunk)):
|
| 429 |
+
|
| 430 |
+
# Token t of `targets` is predicted from position t,
|
| 431 |
+
# so the answer tokens start at prompt_len - 1.
|
| 432 |
+
lo = max(prompt_lens[row] - 1, 0)
|
| 433 |
+
|
| 434 |
+
keep = valid[row].clone()
|
| 435 |
+
keep[:lo] = False
|
| 436 |
+
|
| 437 |
+
n = int(keep.sum())
|
| 438 |
+
|
| 439 |
+
scores[start + row] = (
|
| 440 |
+
(logprobs[row][keep].sum() / n).item() if n else -1e9
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
finally:
|
| 444 |
+
self.tokenizer.padding_side = previous_side
|
| 445 |
+
|
| 446 |
+
grouped = [[] for _ in questions]
|
| 447 |
+
|
| 448 |
+
for score, qi in zip(scores, owners):
|
| 449 |
+
grouped[qi].append(score)
|
| 450 |
+
|
| 451 |
+
return grouped
|
models/interference.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Coherent collapse -- complex amplitudes and real interference.
|
| 3 |
+
|
| 4 |
+
Why this module exists
|
| 5 |
+
----------------------
|
| 6 |
+
Every "quantum" operation in v44 reduced to a classical one with a
|
| 7 |
+
physics name attached. The Born rule was the clearest case:
|
| 8 |
+
|
| 9 |
+
amplitude = exp(-E / 2T); L2-normalize; probability = amplitude^2
|
| 10 |
+
|
| 11 |
+
is *algebraically identical* to softmax(-E / T) when the amplitudes are
|
| 12 |
+
real and non-negative -- verified numerically to fp32 epsilon
|
| 13 |
+
(5.96e-08). And with no phases, |sum_k c_k|^2 = sum_k |c_k|^2 exactly:
|
| 14 |
+
there are no cross-terms, so nothing can interfere. The module named
|
| 15 |
+
"interference" could not interfere; the "collapse" was a temperature-
|
| 16 |
+
scaled softmax; the "superposition" was a tensor axis.
|
| 17 |
+
|
| 18 |
+
v45 gives each hypothesis a complex amplitude
|
| 19 |
+
|
| 20 |
+
c_k = r_k * exp(i * phi_k)
|
| 21 |
+
|
| 22 |
+
and each (hypothesis, option) compatibility a complex amplitude
|
| 23 |
+
|
| 24 |
+
v_kn = t_kn * exp(i * theta_kn), t_kn = exp(-E_kn / 2T)
|
| 25 |
+
|
| 26 |
+
and scores option n by the expectation of a rank-1 Hermitian projector
|
| 27 |
+
P_n = |v_n><v_n| in the hypothesis state |psi> = sum_k c_k |k>:
|
| 28 |
+
|
| 29 |
+
<psi| P_n |psi> = | sum_k c_k v_kn |^2
|
| 30 |
+
= sum_k |c_k|^2 |v_kn|^2 <- classical
|
| 31 |
+
+ sum_{i != j} 2 Re(c_i conj(c_j) v_in conj(v_jn))
|
| 32 |
+
|
| 33 |
+
The second line is the whole point. It is a genuine cross-term, it can
|
| 34 |
+
be NEGATIVE, and therefore two hypotheses can cancel each other's
|
| 35 |
+
support for an option. That is destructive interference, it is not
|
| 36 |
+
expressible as a mixture over a latent variable, and it is the one place
|
| 37 |
+
this project earns the word "quantum".
|
| 38 |
+
|
| 39 |
+
P_n is Hermitian and positive semi-definite, so <psi|P_n|psi> is
|
| 40 |
+
real and non-negative -- a legitimate measurement, not a metaphor.
|
| 41 |
+
The classical line is exactly the decohered (diagonal) limit, which
|
| 42 |
+
is what `phase_mode="classical"` computes.
|
| 43 |
+
|
| 44 |
+
Falsifiability
|
| 45 |
+
--------------
|
| 46 |
+
This is a claim, so it ships with the test. `interference_ratio` is
|
| 47 |
+
mean|coherent - classical| / mean(classical), reported every epoch. If
|
| 48 |
+
it sits at ~0, the phases learned nothing and the coherent formulation
|
| 49 |
+
is inert -- exactly the failure mode of every previous "quantum"
|
| 50 |
+
component here, and it will show up as a number instead of hiding behind
|
| 51 |
+
an accuracy that looks plausible. The ablation grid contains
|
| 52 |
+
parameter-matched `phase_mode="zero"` and `phase_mode="classical"` arms
|
| 53 |
+
so the effect can be attributed rather than assumed.
|
| 54 |
+
|
| 55 |
+
v46 adds the comparison those diagnostics cannot make. `interference_ratio`,
|
| 56 |
+
`phase_effect` and `destructive_fraction` all say the mechanism is LIVE;
|
| 57 |
+
none of them says it helps. `destructive_fraction` is the clearest case: with
|
| 58 |
+
K = 2N matched support/attack pairs and near-equal amplitudes it is a step
|
| 59 |
+
function of the single relative phase between the two channels
|
| 60 |
+
(models/full_model.py::polarity_phase). Sweeping that scalar through this
|
| 61 |
+
module with everything else held fixed gives 0.000 from 0 to 1.6 rad, 0.494
|
| 62 |
+
at 2.4, 0.994 at 2.8, and 1.000 at 3.0 and above -- and it is initialized at
|
| 63 |
+
pi, past the step, so it reads 1.0 for an untrained model.
|
| 64 |
+
|
| 65 |
+
The number that decides the claim is therefore `coherent_acc` vs
|
| 66 |
+
`classical_acc` in training/evaluate.py: the accuracy of ranking options by
|
| 67 |
+
`coherent` against ranking them by `classical`, the decohered limit of the
|
| 68 |
+
SAME amplitudes over the SAME energies in the same forward pass. If the
|
| 69 |
+
coherent sum does not rank options better than the mixture it replaced, the
|
| 70 |
+
complex amplitudes are not earning their place however live they measure.
|
| 71 |
+
|
| 72 |
+
Modes
|
| 73 |
+
-----
|
| 74 |
+
"learned" full complex amplitudes; phases supplied by the caller
|
| 75 |
+
"zero" coherent sum, all phases pinned to 0 -- constructive
|
| 76 |
+
only. Isolates "having phases" from "summing amplitudes
|
| 77 |
+
before squaring", which are two different claims.
|
| 78 |
+
"classical" diagonal/decohered: P(n) = sum_k |c_k|^2 |v_kn|^2, i.e.
|
| 79 |
+
a plain probability-weighted mixture over hypotheses,
|
| 80 |
+
the v44 behaviour.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
import torch
|
| 84 |
+
import torch.nn as nn
|
| 85 |
+
import torch.nn.functional as F
|
| 86 |
+
|
| 87 |
+
MODES = ("learned", "zero", "classical")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class CoherentCollapse(nn.Module):
|
| 91 |
+
|
| 92 |
+
def __init__(self, phase_mode="learned"):
|
| 93 |
+
|
| 94 |
+
super().__init__()
|
| 95 |
+
|
| 96 |
+
if phase_mode not in MODES:
|
| 97 |
+
raise ValueError(f"phase_mode must be one of {MODES}, got {phase_mode!r}")
|
| 98 |
+
|
| 99 |
+
self.phase_mode = phase_mode
|
| 100 |
+
|
| 101 |
+
# Two temperatures, one per axis. Stored as logits into
|
| 102 |
+
# 0.3 + softplus(.) so they stay strictly positive without a
|
| 103 |
+
# clamp, and start near 1.0.
|
| 104 |
+
self.hypothesis_temp = nn.Parameter(torch.tensor(0.5413))
|
| 105 |
+
self.option_temp = nn.Parameter(torch.tensor(0.5413))
|
| 106 |
+
|
| 107 |
+
def forward(
|
| 108 |
+
self,
|
| 109 |
+
collapse_energy,
|
| 110 |
+
answer_energy,
|
| 111 |
+
phase_h=None,
|
| 112 |
+
phase_kn=None,
|
| 113 |
+
H_mask=None,
|
| 114 |
+
O_mask=None,
|
| 115 |
+
hyp_temperature=None,
|
| 116 |
+
):
|
| 117 |
+
"""
|
| 118 |
+
collapse_energy : (B, K) fused per-hypothesis energy
|
| 119 |
+
answer_energy : (B, K, N) per (hypothesis, option) energy
|
| 120 |
+
phase_h : (B, K) hypothesis phases, radians
|
| 121 |
+
phase_kn : (B, K, N) compatibility phases, radians
|
| 122 |
+
H_mask : (B, K) bool
|
| 123 |
+
O_mask : (B, N) bool
|
| 124 |
+
hyp_temperature : (B, 1) optional per-sample temperature from
|
| 125 |
+
models/collapse.py, overriding the global one
|
| 126 |
+
|
| 127 |
+
Returns log-probabilities over options. They are already
|
| 128 |
+
normalized, so F.cross_entropy(log_probs, y) is exact:
|
| 129 |
+
log_softmax(log p) = log p - log(sum p) = log p.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
B, K, N = answer_energy.shape
|
| 133 |
+
|
| 134 |
+
# ------------------------------------------------------------
|
| 135 |
+
# Hypothesis amplitudes r_k, normalized so sum_k r_k^2 = 1
|
| 136 |
+
# ------------------------------------------------------------
|
| 137 |
+
|
| 138 |
+
if hyp_temperature is not None:
|
| 139 |
+
t_hyp = hyp_temperature
|
| 140 |
+
else:
|
| 141 |
+
t_hyp = 0.3 + F.softplus(self.hypothesis_temp)
|
| 142 |
+
|
| 143 |
+
log_r = -collapse_energy / (2.0 * t_hyp)
|
| 144 |
+
|
| 145 |
+
if H_mask is not None:
|
| 146 |
+
log_r = log_r.masked_fill(~H_mask, float("-inf"))
|
| 147 |
+
|
| 148 |
+
log_r = log_r - log_r.max(dim=1, keepdim=True).values
|
| 149 |
+
|
| 150 |
+
r = torch.exp(log_r)
|
| 151 |
+
|
| 152 |
+
r = r / torch.sqrt((r ** 2).sum(dim=1, keepdim=True) + 1e-8)
|
| 153 |
+
|
| 154 |
+
# |c_k|^2 -- the marginal weight of each hypothesis. Same object
|
| 155 |
+
# v44 called `collapse_probs`, kept under that name so the
|
| 156 |
+
# existing collapse diagnostics and input-ablation checks read
|
| 157 |
+
# the same quantity.
|
| 158 |
+
collapse_probs = r.pow(2)
|
| 159 |
+
|
| 160 |
+
collapse_probs = collapse_probs / (
|
| 161 |
+
collapse_probs.sum(dim=1, keepdim=True) + 1e-8
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# ------------------------------------------------------------
|
| 165 |
+
# Compatibility amplitudes t_kn
|
| 166 |
+
# ------------------------------------------------------------
|
| 167 |
+
|
| 168 |
+
t_opt = 0.3 + F.softplus(self.option_temp)
|
| 169 |
+
|
| 170 |
+
log_t = -answer_energy / (2.0 * t_opt)
|
| 171 |
+
|
| 172 |
+
invalid = torch.zeros(B, K, N, dtype=torch.bool, device=log_t.device)
|
| 173 |
+
|
| 174 |
+
if H_mask is not None:
|
| 175 |
+
invalid = invalid | ~H_mask.view(B, K, 1)
|
| 176 |
+
|
| 177 |
+
if O_mask is not None:
|
| 178 |
+
invalid = invalid | ~O_mask.view(B, 1, N)
|
| 179 |
+
|
| 180 |
+
log_t = log_t.masked_fill(invalid, float("-inf"))
|
| 181 |
+
|
| 182 |
+
# Per-sample max subtraction over BOTH axes jointly: answer_energy
|
| 183 |
+
# is clamped to +/-12 upstream and the temperature can fall to
|
| 184 |
+
# 0.3, so exp(-E/2T) reaches e^20 without this.
|
| 185 |
+
log_t = log_t - log_t.reshape(B, -1).max(dim=1).values.view(B, 1, 1)
|
| 186 |
+
|
| 187 |
+
t = torch.exp(log_t)
|
| 188 |
+
|
| 189 |
+
# ------------------------------------------------------------
|
| 190 |
+
# Classical (decohered) and coherent option weights
|
| 191 |
+
# ------------------------------------------------------------
|
| 192 |
+
|
| 193 |
+
w = r.unsqueeze(-1) * t # |c_k| * |v_kn|
|
| 194 |
+
|
| 195 |
+
classical = (w ** 2).sum(dim=1) # (B, N)
|
| 196 |
+
|
| 197 |
+
# The in-phase (all phases 0) coherent sum. Reference point for
|
| 198 |
+
# `phase_effect` below, and the value used directly in "zero"
|
| 199 |
+
# mode.
|
| 200 |
+
in_phase = w.sum(dim=1) ** 2
|
| 201 |
+
|
| 202 |
+
if self.phase_mode == "classical":
|
| 203 |
+
|
| 204 |
+
coherent = classical
|
| 205 |
+
|
| 206 |
+
elif self.phase_mode == "zero" or phase_h is None:
|
| 207 |
+
|
| 208 |
+
coherent = in_phase
|
| 209 |
+
|
| 210 |
+
else:
|
| 211 |
+
|
| 212 |
+
phase = phase_h.unsqueeze(-1).expand_as(w)
|
| 213 |
+
|
| 214 |
+
if phase_kn is not None:
|
| 215 |
+
phase = phase + phase_kn
|
| 216 |
+
|
| 217 |
+
real = (w * torch.cos(phase)).sum(dim=1)
|
| 218 |
+
imag = (w * torch.sin(phase)).sum(dim=1)
|
| 219 |
+
|
| 220 |
+
coherent = real ** 2 + imag ** 2
|
| 221 |
+
|
| 222 |
+
interference = coherent - classical
|
| 223 |
+
|
| 224 |
+
# ------------------------------------------------------------
|
| 225 |
+
# Normalize to a distribution over options
|
| 226 |
+
# ------------------------------------------------------------
|
| 227 |
+
|
| 228 |
+
weights = coherent
|
| 229 |
+
|
| 230 |
+
if O_mask is not None:
|
| 231 |
+
weights = weights.masked_fill(~O_mask, 0.0)
|
| 232 |
+
|
| 233 |
+
weights = weights.clamp(min=1e-12)
|
| 234 |
+
|
| 235 |
+
log_probs = torch.log(weights) - torch.log(
|
| 236 |
+
weights.sum(dim=1, keepdim=True)
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
if O_mask is not None:
|
| 240 |
+
neg_inf = torch.finfo(log_probs.dtype).min / 2
|
| 241 |
+
log_probs = log_probs.masked_fill(~O_mask, neg_inf)
|
| 242 |
+
|
| 243 |
+
# ------------------------------------------------------------
|
| 244 |
+
# Diagnostics
|
| 245 |
+
# ------------------------------------------------------------
|
| 246 |
+
|
| 247 |
+
if O_mask is not None:
|
| 248 |
+
om = O_mask.to(classical.dtype)
|
| 249 |
+
else:
|
| 250 |
+
om = torch.ones_like(classical)
|
| 251 |
+
|
| 252 |
+
denom = om.sum().clamp(min=1.0)
|
| 253 |
+
|
| 254 |
+
def masked_mean(t):
|
| 255 |
+
return (t * om).sum() / denom
|
| 256 |
+
|
| 257 |
+
mean_classical = masked_mean(classical)
|
| 258 |
+
|
| 259 |
+
# How far the coherent sum is from the decohered mixture. Note
|
| 260 |
+
# that this is LARGE even with all phases at zero -- a purely
|
| 261 |
+
# constructive coherent sum is already a long way from a
|
| 262 |
+
# mixture -- so it says "amplitudes are being summed before
|
| 263 |
+
# squaring", not "the phases are doing something".
|
| 264 |
+
interference_ratio = masked_mean(interference.abs()) / (
|
| 265 |
+
mean_classical + 1e-12
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
# The two numbers that actually test the phase channel:
|
| 269 |
+
#
|
| 270 |
+
# phase_effect how much the learned phases move the
|
| 271 |
+
# result away from the in-phase sum. Zero
|
| 272 |
+
# means the phases are inert and this is
|
| 273 |
+
# just constructive summation.
|
| 274 |
+
# destructive_fraction the share of (sample, option) entries
|
| 275 |
+
# where the cross-term is NEGATIVE, i.e.
|
| 276 |
+
# hypotheses cancelling. It is identically
|
| 277 |
+
# 0 for phase_mode "zero" and "classical",
|
| 278 |
+
# because a sum of non-negative terms
|
| 279 |
+
# cannot cancel. Anything above 0 here is
|
| 280 |
+
# destructive interference, which no
|
| 281 |
+
# mixture over a latent variable can
|
| 282 |
+
# express.
|
| 283 |
+
phase_effect = masked_mean((coherent - in_phase).abs()) / (
|
| 284 |
+
masked_mean(in_phase) + 1e-12
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
destructive_fraction = masked_mean((interference < 0).to(classical.dtype))
|
| 288 |
+
|
| 289 |
+
# Relative spread of the option weights, (max - min) / mean, for
|
| 290 |
+
# the coherent sum and for the decohered mixture it replaced.
|
| 291 |
+
#
|
| 292 |
+
# Read the obvious way round this is actively misleading, so state
|
| 293 |
+
# it explicitly: contrast RISES under cancellation. When the
|
| 294 |
+
# coherent sum nearly cancels, what survives is a small residual,
|
| 295 |
+
# and the relative spread of a small residual is amplified. A high
|
| 296 |
+
# `coherent_contrast` therefore says the phases pulled the option
|
| 297 |
+
# weights apart -- NOT that they pulled the correct option away
|
| 298 |
+
# from the rest. Separating those two takes `ece` and the
|
| 299 |
+
# coherent_acc vs classical_acc comparison in evaluate.py.
|
| 300 |
+
valid_opt = om > 0
|
| 301 |
+
|
| 302 |
+
n_opt = om.sum(dim=1).clamp(min=1.0)
|
| 303 |
+
|
| 304 |
+
def option_contrast(x):
|
| 305 |
+
|
| 306 |
+
x_mean = (x * om).sum(dim=1) / n_opt
|
| 307 |
+
|
| 308 |
+
x_max = x.masked_fill(~valid_opt, float("-inf")).max(dim=1).values
|
| 309 |
+
|
| 310 |
+
x_min = x.masked_fill(~valid_opt, float("inf")).min(dim=1).values
|
| 311 |
+
|
| 312 |
+
return ((x_max - x_min) / (x_mean + 1e-12)).mean()
|
| 313 |
+
|
| 314 |
+
coherent_contrast = option_contrast(coherent).detach()
|
| 315 |
+
|
| 316 |
+
classical_contrast = option_contrast(classical).detach()
|
| 317 |
+
|
| 318 |
+
entropy = -(
|
| 319 |
+
log_probs.exp() * log_probs.clamp(min=-30)
|
| 320 |
+
).sum(dim=1)
|
| 321 |
+
|
| 322 |
+
return {
|
| 323 |
+
"log_probs": log_probs,
|
| 324 |
+
"probabilities": log_probs.exp(),
|
| 325 |
+
"collapse_probs": collapse_probs,
|
| 326 |
+
"amplitude": r,
|
| 327 |
+
"classical": classical,
|
| 328 |
+
"coherent": coherent,
|
| 329 |
+
"interference": interference,
|
| 330 |
+
"interference_ratio": interference_ratio,
|
| 331 |
+
"phase_effect": phase_effect,
|
| 332 |
+
"destructive_fraction": destructive_fraction,
|
| 333 |
+
"coherent_contrast": coherent_contrast,
|
| 334 |
+
"classical_contrast": classical_contrast,
|
| 335 |
+
"answer_entropy": entropy.mean(),
|
| 336 |
+
"hypothesis_temperature": (
|
| 337 |
+
t_hyp.detach().mean() if torch.is_tensor(t_hyp) else t_hyp
|
| 338 |
+
),
|
| 339 |
+
"option_temperature": t_opt.detach(),
|
| 340 |
+
}
|
models/persistent_reasoner.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from config import DROPOUT
|
| 8 |
+
|
| 9 |
+
MIXINGS = ("orthogonal", "softmax")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class PersistentReasoner(nn.Module):
|
| 13 |
+
"""
|
| 14 |
+
Persistent multi-hypothesis refinement.
|
| 15 |
+
|
| 16 |
+
Naming, honestly
|
| 17 |
+
----------------
|
| 18 |
+
Earlier versions called this "Persistent Hamiltonian Reasoning". It
|
| 19 |
+
was not Hamiltonian in any sense a physicist would accept:
|
| 20 |
+
`interaction = softmax(metric(H) H^T / sqrt(d))` is not Hermitian (W
|
| 21 |
+
is unconstrained), and `H <- LayerNorm(H + g * dt * field)` is not
|
| 22 |
+
unitary. Unitary evolution U = exp(-i H t) preserves norm and is
|
| 23 |
+
invertible, so it *cannot* map two distinct states onto the same
|
| 24 |
+
one. The implemented map was dissipative and provably contractive:
|
| 25 |
+
it collapsed to a constant fixed point (mean pairwise cosine ->
|
| 26 |
+
1.000000, output independent of input to 1.9e-03).
|
| 27 |
+
|
| 28 |
+
What v45 actually fixes
|
| 29 |
+
-----------------------
|
| 30 |
+
The mixing across hypotheses -- the only part that can oversmooth --
|
| 31 |
+
is now an ORTHOGONAL operator, built by the Cayley transform of an
|
| 32 |
+
antisymmetric coupling matrix:
|
| 33 |
+
|
| 34 |
+
S = metric(H_norm) H_norm^T / sqrt(d)
|
| 35 |
+
A = (S - S^T) / 2 (antisymmetric)
|
| 36 |
+
X = dt * A / 2
|
| 37 |
+
U = (I - X)^{-1} (I + X) (orthogonal, exactly)
|
| 38 |
+
|
| 39 |
+
Three consequences, all of them the point:
|
| 40 |
+
|
| 41 |
+
* ||U H||_F = ||H||_F and U is invertible, so distinct hypotheses
|
| 42 |
+
stay distinct. The v44 collapse is not merely discouraged, it is
|
| 43 |
+
unreachable through the mixing path.
|
| 44 |
+
* (I - X) is always invertible: the eigenvalues of a real
|
| 45 |
+
antisymmetric matrix are purely imaginary, so 1 - i*lambda is
|
| 46 |
+
never zero. No numerical guard is needed.
|
| 47 |
+
* U's entries are SIGNED. v44's row-softmax made every mixing
|
| 48 |
+
weight non-negative, so field_k was a convex combination of the
|
| 49 |
+
hypotheses and cancellation was arithmetically impossible -- the
|
| 50 |
+
module named "interference" could not interfere. Signed weights
|
| 51 |
+
restore that possibility, and unlike v44's pre-audit unnormalized
|
| 52 |
+
`tanh` (which was signed but unbounded, and is what caused the
|
| 53 |
+
collapse in the first place) an orthogonal operator cannot blow
|
| 54 |
+
up or contract.
|
| 55 |
+
|
| 56 |
+
What is NOT claimed
|
| 57 |
+
-------------------
|
| 58 |
+
The per-hypothesis refinement that follows the mixing -- the gated
|
| 59 |
+
residual, the FFN, the LayerNorms -- is a standard residual block and
|
| 60 |
+
is not norm-preserving. Only the hypothesis-mixing operator is
|
| 61 |
+
orthogonal. This block as a whole is not unitary evolution and is not
|
| 62 |
+
described as such anywhere.
|
| 63 |
+
|
| 64 |
+
`mixing="softmax"` restores the v44 row-stochastic behaviour as a
|
| 65 |
+
parameter-matched ablation arm.
|
| 66 |
+
|
| 67 |
+
Anti-collapse machinery kept from v44
|
| 68 |
+
-------------------------------------
|
| 69 |
+
* Each step re-anchors to the original hypotheses H0 through a gated
|
| 70 |
+
residual, so the map cannot forget its own input.
|
| 71 |
+
* `dt`, `memory_decay`, `validator_weight` and `anchor_weight` are
|
| 72 |
+
stored as LOGITS. They were once stored as post-sigmoid values by
|
| 73 |
+
mistake: `nn.Parameter(tensor(0.10))` then `sigmoid(...)` gives an
|
| 74 |
+
effective step size of 0.525, five times the intended 0.10, which
|
| 75 |
+
directly accelerated the collapse.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self, dim, steps=3, keep_trajectory=False, mixing="orthogonal"):
|
| 79 |
+
|
| 80 |
+
super().__init__()
|
| 81 |
+
|
| 82 |
+
if mixing not in MIXINGS:
|
| 83 |
+
raise ValueError(f"mixing must be one of {MIXINGS}, got {mixing!r}")
|
| 84 |
+
|
| 85 |
+
self.steps = steps
|
| 86 |
+
|
| 87 |
+
self.mixing = mixing
|
| 88 |
+
|
| 89 |
+
# trajectory.append(H.detach().cpu()) forces a device->host sync on
|
| 90 |
+
# every step of every forward pass. Only the visualization tools
|
| 91 |
+
# consume it, so it is off during training/eval by default.
|
| 92 |
+
self.keep_trajectory = keep_trajectory
|
| 93 |
+
|
| 94 |
+
####################################################
|
| 95 |
+
# Coupling
|
| 96 |
+
####################################################
|
| 97 |
+
|
| 98 |
+
self.metric = nn.Linear(dim, dim, bias=False)
|
| 99 |
+
|
| 100 |
+
self.coupling = nn.Linear(dim, dim, bias=False)
|
| 101 |
+
|
| 102 |
+
####################################################
|
| 103 |
+
# Interference network
|
| 104 |
+
####################################################
|
| 105 |
+
|
| 106 |
+
self.interference = nn.Sequential(
|
| 107 |
+
nn.Linear(dim, dim),
|
| 108 |
+
nn.GELU(),
|
| 109 |
+
nn.Linear(dim, dim),
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
####################################################
|
| 113 |
+
# Adaptive gate
|
| 114 |
+
####################################################
|
| 115 |
+
|
| 116 |
+
self.gate = nn.Sequential(
|
| 117 |
+
nn.Linear(dim * 2, dim),
|
| 118 |
+
nn.GELU(),
|
| 119 |
+
nn.Linear(dim, dim),
|
| 120 |
+
nn.Sigmoid(),
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
####################################################
|
| 124 |
+
# Feedforward refinement
|
| 125 |
+
####################################################
|
| 126 |
+
|
| 127 |
+
self.ffn = nn.Sequential(
|
| 128 |
+
nn.Linear(dim, dim * 2),
|
| 129 |
+
nn.GELU(),
|
| 130 |
+
nn.Dropout(DROPOUT),
|
| 131 |
+
nn.Linear(dim * 2, dim),
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
self.norm1 = nn.LayerNorm(dim)
|
| 135 |
+
self.norm2 = nn.LayerNorm(dim)
|
| 136 |
+
self.norm3 = nn.LayerNorm(dim)
|
| 137 |
+
|
| 138 |
+
####################################################
|
| 139 |
+
# Learnable evolution rate -- stored as a LOGIT.
|
| 140 |
+
# logit(0.10) = -2.1972, so sigmoid(dt) starts at 0.10.
|
| 141 |
+
####################################################
|
| 142 |
+
|
| 143 |
+
self.dt = nn.Parameter(torch.tensor(-2.1972))
|
| 144 |
+
|
| 145 |
+
####################################################
|
| 146 |
+
# Validator influence (logit; sigmoid -> 0.30)
|
| 147 |
+
####################################################
|
| 148 |
+
|
| 149 |
+
self.validator_weight = nn.Parameter(torch.tensor(-0.8473))
|
| 150 |
+
|
| 151 |
+
####################################################
|
| 152 |
+
# Persistent memory (logit; sigmoid -> 0.80)
|
| 153 |
+
####################################################
|
| 154 |
+
|
| 155 |
+
self.memory_decay = nn.Parameter(torch.tensor(1.3863))
|
| 156 |
+
|
| 157 |
+
####################################################
|
| 158 |
+
# Anchor back to the input hypotheses (logit; sigmoid -> 0.50)
|
| 159 |
+
####################################################
|
| 160 |
+
|
| 161 |
+
self.anchor_weight = nn.Parameter(torch.tensor(0.0))
|
| 162 |
+
|
| 163 |
+
# ==========================================================
|
| 164 |
+
# MIXING OPERATORS
|
| 165 |
+
# ==========================================================
|
| 166 |
+
|
| 167 |
+
def _orthogonal_mix(self, H, H_norm, mask, step_size):
|
| 168 |
+
"""
|
| 169 |
+
Returns (mixed, U). U is exactly orthogonal by construction.
|
| 170 |
+
|
| 171 |
+
Computed in fp32 regardless of autocast: torch.linalg.solve is
|
| 172 |
+
not implemented for half precision on several backends, and the
|
| 173 |
+
matrices here are tiny (K <= 8), so there is nothing to gain
|
| 174 |
+
from lower precision.
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
dtype = H.dtype
|
| 178 |
+
|
| 179 |
+
H32 = H.float()
|
| 180 |
+
|
| 181 |
+
S = torch.einsum(
|
| 182 |
+
"bkd,bjd->bkj", self.metric(H_norm).float(), H_norm.float()
|
| 183 |
+
) / math.sqrt(H.shape[-1])
|
| 184 |
+
|
| 185 |
+
A = 0.5 * (S - S.transpose(1, 2))
|
| 186 |
+
|
| 187 |
+
if mask is not None:
|
| 188 |
+
m = mask.float()
|
| 189 |
+
A = A * m.unsqueeze(1) * m.unsqueeze(2)
|
| 190 |
+
|
| 191 |
+
X = 0.5 * step_size.float() * A
|
| 192 |
+
|
| 193 |
+
eye = torch.eye(A.shape[1], device=A.device, dtype=A.dtype)
|
| 194 |
+
eye = eye.unsqueeze(0).expand_as(A)
|
| 195 |
+
|
| 196 |
+
U = torch.linalg.solve(eye - X, eye + X)
|
| 197 |
+
|
| 198 |
+
mixed = torch.bmm(U, H32)
|
| 199 |
+
|
| 200 |
+
return mixed.to(dtype), U.to(dtype)
|
| 201 |
+
|
| 202 |
+
def _softmax_mix(self, H, H_norm, mask):
|
| 203 |
+
"""
|
| 204 |
+
v44 behaviour, kept as an ablation arm. Row-stochastic, hence a
|
| 205 |
+
convex combination: field_k = sum_j a_kj H_j with every a_kj >= 0
|
| 206 |
+
can never cancel, and with an unmasked mean-like row it drives
|
| 207 |
+
every hypothesis toward the same vector.
|
| 208 |
+
"""
|
| 209 |
+
|
| 210 |
+
logits = torch.einsum(
|
| 211 |
+
"bkd,bjd->bkj", self.metric(H_norm), H_norm
|
| 212 |
+
) / math.sqrt(H.shape[-1])
|
| 213 |
+
|
| 214 |
+
if mask is not None:
|
| 215 |
+
logits = logits.masked_fill(~mask.unsqueeze(1), float("-inf"))
|
| 216 |
+
|
| 217 |
+
A = torch.softmax(logits, dim=-1)
|
| 218 |
+
|
| 219 |
+
return torch.einsum("bkj,bjd->bkd", A, H), A
|
| 220 |
+
|
| 221 |
+
# ==========================================================
|
| 222 |
+
# FORWARD
|
| 223 |
+
# ==========================================================
|
| 224 |
+
|
| 225 |
+
def forward(self, H, potential=None, mask=None):
|
| 226 |
+
"""
|
| 227 |
+
H : (B, K, D) hypothesis embeddings
|
| 228 |
+
potential: (B, K, D) optional validator guidance field
|
| 229 |
+
mask : (B, K) bool, True for real hypotheses. Padded entries
|
| 230 |
+
are excluded from the mixing so a zero-padded
|
| 231 |
+
hypothesis can't drag the field toward the origin.
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
H0 = H
|
| 235 |
+
|
| 236 |
+
trajectory = []
|
| 237 |
+
|
| 238 |
+
interaction = None
|
| 239 |
+
|
| 240 |
+
memory = torch.zeros_like(H)
|
| 241 |
+
|
| 242 |
+
step_size = torch.sigmoid(self.dt)
|
| 243 |
+
|
| 244 |
+
for _ in range(self.steps):
|
| 245 |
+
|
| 246 |
+
H_norm = F.normalize(H, dim=-1)
|
| 247 |
+
|
| 248 |
+
################################################
|
| 249 |
+
# Mixing across hypotheses
|
| 250 |
+
################################################
|
| 251 |
+
|
| 252 |
+
if self.mixing == "orthogonal":
|
| 253 |
+
field, interaction = self._orthogonal_mix(
|
| 254 |
+
H, H_norm, mask, step_size
|
| 255 |
+
)
|
| 256 |
+
else:
|
| 257 |
+
field, interaction = self._softmax_mix(H, H_norm, mask)
|
| 258 |
+
|
| 259 |
+
field = self.coupling(field)
|
| 260 |
+
|
| 261 |
+
################################################
|
| 262 |
+
# Interference network
|
| 263 |
+
################################################
|
| 264 |
+
|
| 265 |
+
field = field + self.interference(field)
|
| 266 |
+
|
| 267 |
+
################################################
|
| 268 |
+
# Persistent memory
|
| 269 |
+
################################################
|
| 270 |
+
|
| 271 |
+
decay = torch.sigmoid(self.memory_decay)
|
| 272 |
+
|
| 273 |
+
memory = decay * memory + (1.0 - decay) * field
|
| 274 |
+
|
| 275 |
+
field = field + memory
|
| 276 |
+
|
| 277 |
+
################################################
|
| 278 |
+
# Validator guidance
|
| 279 |
+
################################################
|
| 280 |
+
|
| 281 |
+
if potential is not None:
|
| 282 |
+
|
| 283 |
+
weight = torch.sigmoid(self.validator_weight)
|
| 284 |
+
|
| 285 |
+
field = field + weight * potential
|
| 286 |
+
|
| 287 |
+
################################################
|
| 288 |
+
# Gated evolution
|
| 289 |
+
################################################
|
| 290 |
+
|
| 291 |
+
gate = self.gate(torch.cat([H, field], dim=-1))
|
| 292 |
+
|
| 293 |
+
H = self.norm1(H + gate * step_size * field)
|
| 294 |
+
|
| 295 |
+
################################################
|
| 296 |
+
# Refinement
|
| 297 |
+
################################################
|
| 298 |
+
|
| 299 |
+
H = self.norm2(H + self.ffn(H))
|
| 300 |
+
|
| 301 |
+
################################################
|
| 302 |
+
# Re-anchor to the original hypotheses so the map
|
| 303 |
+
# cannot converge to an input-independent point.
|
| 304 |
+
################################################
|
| 305 |
+
|
| 306 |
+
H = self.norm3(H + torch.sigmoid(self.anchor_weight) * H0)
|
| 307 |
+
|
| 308 |
+
if mask is not None:
|
| 309 |
+
H = H * mask.unsqueeze(-1).to(H.dtype)
|
| 310 |
+
|
| 311 |
+
if self.keep_trajectory:
|
| 312 |
+
trajectory.append(H.detach().cpu())
|
| 313 |
+
|
| 314 |
+
return H, trajectory, interaction
|
models/quantum_layer.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import pennylane as qml
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
|
| 9 |
+
from config import DROPOUT, QUANTUM_DEVICE
|
| 10 |
+
|
| 11 |
+
DEVICE_CHOICES = ("auto", "lightning.gpu", "lightning.qubit")
|
| 12 |
+
|
| 13 |
+
# Printed at most once per process, not once per model construction --
|
| 14 |
+
# an 8-arm x 5-seed ablation grid builds 40 of these, and 40 identical
|
| 15 |
+
# "falling back to CPU" lines would bury the one thing worth knowing.
|
| 16 |
+
_reported = set()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _try_construct(name, n_qubits):
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
# batch_obs batches the 3*n_qubits expval() observables into fewer
|
| 23 |
+
# statevector passes -- pure execution optimization, not a change
|
| 24 |
+
# to what's computed. Retry without it if this particular build
|
| 25 |
+
# doesn't expose the kwarg, rather than treating the absence of a
|
| 26 |
+
# batching optimization as a reason to fail over to a different
|
| 27 |
+
# simulator entirely.
|
| 28 |
+
return qml.device(name, wires=n_qubits, batch_obs=True)
|
| 29 |
+
except TypeError:
|
| 30 |
+
return qml.device(name, wires=n_qubits)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _build_device(n_qubits, preference, verbose):
|
| 34 |
+
"""
|
| 35 |
+
Resolves which PennyLane device actually backs the circuit. See
|
| 36 |
+
config.QUANTUM_DEVICE for what each preference means.
|
| 37 |
+
|
| 38 |
+
A fallback here is a device SWAP, not an algorithm change -- lightning
|
| 39 |
+
.gpu and lightning.qubit compute the identical function, exactly. It is
|
| 40 |
+
reported (once) because a training run silently spending 20-30x longer
|
| 41 |
+
than expected because a GPU didn't attach is a footgun worth knowing
|
| 42 |
+
about immediately, not because the choice changes any result.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
if preference not in DEVICE_CHOICES:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
f"QUANTUM_DEVICE must be one of {DEVICE_CHOICES}, got "
|
| 48 |
+
f"{preference!r}"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
order = ["lightning.gpu", "lightning.qubit"] if preference == "auto" else [preference]
|
| 52 |
+
|
| 53 |
+
errors = []
|
| 54 |
+
|
| 55 |
+
for name in order:
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
dev = _try_construct(name, n_qubits)
|
| 59 |
+
|
| 60 |
+
except Exception as e:
|
| 61 |
+
|
| 62 |
+
errors.append(f"{name}: {type(e).__name__}: {e}")
|
| 63 |
+
continue
|
| 64 |
+
|
| 65 |
+
if name == "lightning.gpu" and "gpu_attached" not in _reported:
|
| 66 |
+
_reported.add("gpu_attached")
|
| 67 |
+
print("[QuantumEvolutionLayer] circuit running on lightning.gpu "
|
| 68 |
+
"(NVIDIA cuStateVec)")
|
| 69 |
+
|
| 70 |
+
elif name == "lightning.qubit" and preference == "auto" and errors:
|
| 71 |
+
key = "cpu_fallback"
|
| 72 |
+
if key not in _reported:
|
| 73 |
+
_reported.add(key)
|
| 74 |
+
print(
|
| 75 |
+
f"[QuantumEvolutionLayer] lightning.gpu unavailable "
|
| 76 |
+
f"({errors[-1]}) -- circuit running on lightning.qubit "
|
| 77 |
+
f"(CPU) instead. Measured 20-30x slower than the GPU "
|
| 78 |
+
f"device (notebooks/diagnose_quantum_speed.py). If this "
|
| 79 |
+
f"machine has an NVIDIA GPU, `pip install "
|
| 80 |
+
f"pennylane-lightning[gpu]`; if not, this is the "
|
| 81 |
+
f"correct fallback and nothing is wrong."
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
if verbose:
|
| 85 |
+
print(f"[QuantumEvolutionLayer] device: {name}")
|
| 86 |
+
|
| 87 |
+
return dev, name
|
| 88 |
+
|
| 89 |
+
if preference != "auto":
|
| 90 |
+
raise RuntimeError(
|
| 91 |
+
f"QUANTUM_DEVICE={preference!r} was requested explicitly but "
|
| 92 |
+
f"device construction failed: {errors[-1]}\n"
|
| 93 |
+
f"Install it with `pip install pennylane-lightning[gpu]` on a "
|
| 94 |
+
f"CUDA-capable machine, or set config.QUANTUM_DEVICE='auto' to "
|
| 95 |
+
f"fall back to lightning.qubit automatically instead of "
|
| 96 |
+
f"raising."
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
raise RuntimeError(
|
| 100 |
+
"No PennyLane device could be constructed, including the CPU "
|
| 101 |
+
"fallback lightning.qubit -- check the pennylane-lightning "
|
| 102 |
+
"install:\n" + "\n".join(errors)
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class QuantumEvolutionLayer(nn.Module):
|
| 107 |
+
"""
|
| 108 |
+
Quantum evolution layer: compress -> circuit -> expand, gated back
|
| 109 |
+
into the hypothesis stream.
|
| 110 |
+
|
| 111 |
+
v45: the circuit drives a phase
|
| 112 |
+
-------------------------------
|
| 113 |
+
The v44 audit's blunt finding was that this layer was decoration --
|
| 114 |
+
54 circuit parameters out of 10.58M (0.0005%), wrapped in a classical
|
| 115 |
+
MLP that did all the work, and bit-exactly a constant function until
|
| 116 |
+
the AngleEmbedding rotation was fixed. Removing it changed nothing
|
| 117 |
+
measurable, which is not a good place for the component a project is
|
| 118 |
+
named after.
|
| 119 |
+
|
| 120 |
+
v45 gives it something only a quantum circuit naturally produces: a
|
| 121 |
+
PHASE. The circuit already measures <X>, <Y> and <Z> per wire, and
|
| 122 |
+
|
| 123 |
+
phi = atan2(mean <Y>, mean <X>)
|
| 124 |
+
|
| 125 |
+
is the azimuthal angle of the measured Bloch vector -- the physically
|
| 126 |
+
meaningful phase of the state the circuit prepared. That angle is fed
|
| 127 |
+
to models/interference.py as the hypothesis phase, where it decides
|
| 128 |
+
whether two hypotheses reinforce or cancel each other's support for
|
| 129 |
+
an option. The circuit therefore participates in an operation with no
|
| 130 |
+
classical equivalent, rather than contributing a 54-parameter
|
| 131 |
+
perturbation to a residual stream.
|
| 132 |
+
|
| 133 |
+
ClassicalControlLayer computes its phase the same way from an equally
|
| 134 |
+
sized classical bottleneck (parameter counts stay matched to the
|
| 135 |
+
scalar), so `A1b_quantum_only` vs `A1c_classical_control_only` still
|
| 136 |
+
isolates the circuit and nothing else.
|
| 137 |
+
|
| 138 |
+
v45 also lets `lightning.gpu` (NVIDIA cuStateVec) back this circuit
|
| 139 |
+
instead of the CPU simulator `lightning.qubit` -- see
|
| 140 |
+
`config.QUANTUM_DEVICE`. Same circuit, same trained function; only the
|
| 141 |
+
hardware executing it changes. Doubling the hypothesis count (support
|
| 142 |
+
+ attack) doubled how often this runs per forward call, which is what
|
| 143 |
+
makes the GPU device worth having rather than optional polish.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def __init__(self, dim, n_qubits=12, n_layers=3, verbose=False,
|
| 147 |
+
quantum_device=QUANTUM_DEVICE):
|
| 148 |
+
|
| 149 |
+
super().__init__()
|
| 150 |
+
|
| 151 |
+
self.n_qubits = n_qubits
|
| 152 |
+
|
| 153 |
+
self.compress = nn.Sequential(
|
| 154 |
+
nn.Linear(dim, dim),
|
| 155 |
+
nn.GELU(),
|
| 156 |
+
nn.Linear(dim, n_qubits),
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
dev, self.device_name = _build_device(n_qubits, quantum_device, verbose)
|
| 160 |
+
|
| 161 |
+
@qml.qnode(dev, interface="torch")
|
| 162 |
+
def circuit(inputs, weights):
|
| 163 |
+
|
| 164 |
+
# Hadamard puts every wire in |+>, the +1 eigenstate of Pauli-X.
|
| 165 |
+
# AngleEmbedding's DEFAULT rotation is "X", and RX(t)|+> =
|
| 166 |
+
# exp(-i t/2)|+> -- a global phase, which no expectation value
|
| 167 |
+
# can observe. Written that way (as this layer was until the
|
| 168 |
+
# audit), the circuit's output is bit-exactly independent of
|
| 169 |
+
# `inputs`: measured std across distinct inputs was 0.000e+00,
|
| 170 |
+
# i.e. the whole layer was a learned constant and every quantum
|
| 171 |
+
# ablation run before this fix measured nothing.
|
| 172 |
+
#
|
| 173 |
+
# rotation="Y" keeps the intended "start in uniform
|
| 174 |
+
# superposition" motif while making the encoding observable:
|
| 175 |
+
# RY(t)|+> tilts the Bloch vector off the equator. Measured
|
| 176 |
+
# output std across inputs: 0.123 (vs 0.094 for dropping the
|
| 177 |
+
# Hadamard and keeping RX, 0.089 for RZ).
|
| 178 |
+
for i in range(n_qubits):
|
| 179 |
+
qml.Hadamard(wires=i)
|
| 180 |
+
|
| 181 |
+
qml.AngleEmbedding(inputs, wires=range(n_qubits), rotation="Y")
|
| 182 |
+
|
| 183 |
+
qml.StronglyEntanglingLayers(weights, wires=range(n_qubits))
|
| 184 |
+
|
| 185 |
+
return (
|
| 186 |
+
[qml.expval(qml.PauliX(i)) for i in range(n_qubits)]
|
| 187 |
+
+ [qml.expval(qml.PauliY(i)) for i in range(n_qubits)]
|
| 188 |
+
+ [qml.expval(qml.PauliZ(i)) for i in range(n_qubits)]
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
weight_shapes = {"weights": (n_layers, n_qubits, 3)}
|
| 192 |
+
|
| 193 |
+
self.quantum = qml.qnn.TorchLayer(circuit, weight_shapes)
|
| 194 |
+
|
| 195 |
+
self.expand = nn.Sequential(
|
| 196 |
+
nn.Linear(n_qubits * 3, dim),
|
| 197 |
+
nn.GELU(),
|
| 198 |
+
nn.LayerNorm(dim),
|
| 199 |
+
nn.Dropout(DROPOUT),
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
self.fusion_gate = nn.Sequential(
|
| 203 |
+
nn.Linear(dim * 2, dim),
|
| 204 |
+
nn.GELU(),
|
| 205 |
+
nn.Linear(dim, dim),
|
| 206 |
+
nn.Sigmoid(),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
self.correction = nn.Sequential(
|
| 210 |
+
nn.Linear(dim, dim),
|
| 211 |
+
nn.GELU(),
|
| 212 |
+
nn.Dropout(DROPOUT),
|
| 213 |
+
nn.Linear(dim, dim),
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# Single scalar, matched by ClassicalControlLayer, so the phase
|
| 217 |
+
# channel cannot explain a quantum-vs-classical gap through
|
| 218 |
+
# parameter count.
|
| 219 |
+
self.phase_gain = nn.Parameter(torch.tensor(1.0))
|
| 220 |
+
|
| 221 |
+
self.energy_head = nn.Sequential(
|
| 222 |
+
nn.Linear(dim, dim),
|
| 223 |
+
nn.GELU(),
|
| 224 |
+
nn.LayerNorm(dim),
|
| 225 |
+
nn.Linear(dim, dim // 2),
|
| 226 |
+
nn.GELU(),
|
| 227 |
+
nn.Linear(dim // 2, 1),
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
self.norm = nn.LayerNorm(dim)
|
| 231 |
+
|
| 232 |
+
# Printed so it can be compared directly against
|
| 233 |
+
# ClassicalControlLayer's printed count at runtime, rather than
|
| 234 |
+
# trusting a hand calculation. Opt-in: this used to fire on every
|
| 235 |
+
# model construction, including inside evaluation loops.
|
| 236 |
+
if verbose:
|
| 237 |
+
total_params = sum(p.numel() for p in self.parameters())
|
| 238 |
+
circuit_params = sum(p.numel() for p in self.quantum.parameters())
|
| 239 |
+
print(
|
| 240 |
+
f"[QuantumEvolutionLayer] total parameters: {total_params:,} "
|
| 241 |
+
f"(circuit weights: {circuit_params:,}, device: {self.device_name})"
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
def forward(self, H):
|
| 245 |
+
|
| 246 |
+
B, K, D = H.shape
|
| 247 |
+
|
| 248 |
+
H_norm = F.normalize(H, dim=-1)
|
| 249 |
+
|
| 250 |
+
z = self.compress(H_norm.reshape(B * K, D))
|
| 251 |
+
|
| 252 |
+
z = math.pi * torch.tanh(z)
|
| 253 |
+
|
| 254 |
+
measurements = self.quantum(z)
|
| 255 |
+
|
| 256 |
+
# measurements is [<X_0..X_{n-1}>, <Y_0..Y_{n-1}>, <Z_0..Z_{n-1}>].
|
| 257 |
+
# The azimuthal angle of the mean Bloch vector is the phase the
|
| 258 |
+
# circuit actually prepared -- see the class docstring.
|
| 259 |
+
n = self.n_qubits
|
| 260 |
+
|
| 261 |
+
x_mean = measurements[:, :n].mean(dim=-1)
|
| 262 |
+
y_mean = measurements[:, n:2 * n].mean(dim=-1)
|
| 263 |
+
|
| 264 |
+
phase = self.phase_gain * torch.atan2(y_mean, x_mean)
|
| 265 |
+
|
| 266 |
+
q = self.expand(measurements)
|
| 267 |
+
|
| 268 |
+
H_flat = H.reshape(B * K, D)
|
| 269 |
+
|
| 270 |
+
gate = self.fusion_gate(torch.cat([H_flat, q], dim=-1))
|
| 271 |
+
|
| 272 |
+
q = gate * q + (1 - gate) * H_flat
|
| 273 |
+
|
| 274 |
+
q = self.norm(q + self.correction(q))
|
| 275 |
+
|
| 276 |
+
energy = self.energy_head(q)
|
| 277 |
+
|
| 278 |
+
energy = torch.tanh(energy).squeeze(-1)
|
| 279 |
+
|
| 280 |
+
q = q.reshape(B, K, D)
|
| 281 |
+
|
| 282 |
+
energy = energy.reshape(B, K)
|
| 283 |
+
|
| 284 |
+
phase = phase.reshape(B, K)
|
| 285 |
+
|
| 286 |
+
return q, energy, phase
|
models/validator.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
from config import DROPOUT
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class HypothesisValidator(nn.Module):
|
| 9 |
+
"""
|
| 10 |
+
Scores hypothesis-vs-option compatibility and emits a guidance
|
| 11 |
+
potential for the reasoner.
|
| 12 |
+
|
| 13 |
+
On the "Born rule" here
|
| 14 |
+
-----------------------
|
| 15 |
+
The distribution computed below weights the guidance potential. With
|
| 16 |
+
real, non-negative amplitudes it is a temperature-scaled softmax and
|
| 17 |
+
nothing more -- that is stated rather than dressed up. The place
|
| 18 |
+
where amplitudes are genuinely complex, and where the Born rule
|
| 19 |
+
therefore does real work, is models/interference.py; this module
|
| 20 |
+
feeds it (through `validator_energy`) but does not itself perform a
|
| 21 |
+
measurement.
|
| 22 |
+
|
| 23 |
+
Fixed in the v44 audit, kept
|
| 24 |
+
----------------------------
|
| 25 |
+
* Question conditioning. The question embedding was never computed
|
| 26 |
+
anywhere in the pipeline, so the validator judged options using
|
| 27 |
+
hypotheses alone -- a third of which were template fallbacks.
|
| 28 |
+
Measured with a plain MLP on cached ARC embeddings: options only
|
| 29 |
+
0.3585, +question 0.4849.
|
| 30 |
+
* L2 (not L1) normalization of the amplitude. L1 is not the Born
|
| 31 |
+
convention and gave this module half the collapse controller's
|
| 32 |
+
effective temperature at the same nominal T.
|
| 33 |
+
* Padded options are excluded from every mean over N.
|
| 34 |
+
|
| 35 |
+
New in v45
|
| 36 |
+
----------
|
| 37 |
+
* `align` / `polarity` features, so the validator can distinguish
|
| 38 |
+
"the support for option n" from "the objection to option n"
|
| 39 |
+
instead of averaging them together.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, dim, use_question=True):
|
| 43 |
+
|
| 44 |
+
super().__init__()
|
| 45 |
+
|
| 46 |
+
self.use_question = use_question
|
| 47 |
+
|
| 48 |
+
# [H, O, H-O, H*O] plus, when the question is available,
|
| 49 |
+
# [Q*O, Q-O]; then three scalars: align, polarity, align*polarity.
|
| 50 |
+
n_vec = 6 if use_question else 4
|
| 51 |
+
|
| 52 |
+
n_feat = dim * n_vec + 3
|
| 53 |
+
|
| 54 |
+
self.encoder = nn.Sequential(
|
| 55 |
+
nn.Linear(n_feat, dim * 2),
|
| 56 |
+
nn.GELU(),
|
| 57 |
+
nn.LayerNorm(dim * 2),
|
| 58 |
+
nn.Dropout(DROPOUT),
|
| 59 |
+
nn.Linear(dim * 2, dim),
|
| 60 |
+
nn.GELU(),
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
self.causal = nn.Linear(dim, 1)
|
| 64 |
+
self.diversity = nn.Linear(dim, 1)
|
| 65 |
+
self.specificity = nn.Linear(dim, 1)
|
| 66 |
+
self.relevance = nn.Linear(dim, 1)
|
| 67 |
+
|
| 68 |
+
self.observable_gate = nn.Sequential(
|
| 69 |
+
nn.Linear(dim, dim),
|
| 70 |
+
nn.GELU(),
|
| 71 |
+
nn.Linear(dim, 4),
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
self.reliability = nn.Sequential(
|
| 75 |
+
nn.Linear(dim, dim),
|
| 76 |
+
nn.GELU(),
|
| 77 |
+
nn.Linear(dim, 1),
|
| 78 |
+
nn.Sigmoid(),
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
self.potential = nn.Sequential(
|
| 82 |
+
nn.Linear(dim + 1, dim),
|
| 83 |
+
nn.GELU(),
|
| 84 |
+
nn.Dropout(DROPOUT),
|
| 85 |
+
nn.Linear(dim, dim),
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
self.temperature = nn.Parameter(torch.tensor(1.0))
|
| 89 |
+
|
| 90 |
+
def forward(self, H, O, Q=None, y=None, H_mask=None, O_mask=None,
|
| 91 |
+
align=None, polarity=None):
|
| 92 |
+
|
| 93 |
+
B, K, D = H.shape
|
| 94 |
+
_, N, _ = O.shape
|
| 95 |
+
|
| 96 |
+
H = F.normalize(H, dim=-1)
|
| 97 |
+
O = F.normalize(O, dim=-1)
|
| 98 |
+
|
| 99 |
+
H_exp = H.unsqueeze(2).expand(B, K, N, D)
|
| 100 |
+
O_exp = O.unsqueeze(1).expand(B, K, N, D)
|
| 101 |
+
|
| 102 |
+
parts = [H_exp, O_exp, H_exp - O_exp, H_exp * O_exp]
|
| 103 |
+
|
| 104 |
+
if self.use_question:
|
| 105 |
+
|
| 106 |
+
if Q is None:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
"HypothesisValidator was built with use_question=True "
|
| 109 |
+
"but forward() got Q=None. Rebuild the cache so it "
|
| 110 |
+
"carries question embeddings, or construct the model "
|
| 111 |
+
"with use_question=False."
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
Q_exp = F.normalize(Q, dim=-1).view(B, 1, 1, D).expand(B, K, N, D)
|
| 115 |
+
|
| 116 |
+
parts += [Q_exp * O_exp, Q_exp - O_exp]
|
| 117 |
+
|
| 118 |
+
if align is None:
|
| 119 |
+
align = torch.zeros(B, K, N, device=H.device, dtype=H.dtype)
|
| 120 |
+
|
| 121 |
+
if polarity is None:
|
| 122 |
+
polarity = torch.zeros(B, K, device=H.device, dtype=H.dtype)
|
| 123 |
+
|
| 124 |
+
a = align.unsqueeze(-1)
|
| 125 |
+
p = polarity.view(B, K, 1, 1).expand(B, K, N, 1)
|
| 126 |
+
|
| 127 |
+
parts += [a, p, a * p]
|
| 128 |
+
|
| 129 |
+
features = torch.cat(parts, dim=-1)
|
| 130 |
+
|
| 131 |
+
z = self.encoder(features)
|
| 132 |
+
|
| 133 |
+
causal = self.causal(z).squeeze(-1)
|
| 134 |
+
diversity = self.diversity(z).squeeze(-1)
|
| 135 |
+
specificity = self.specificity(z).squeeze(-1)
|
| 136 |
+
relevance = self.relevance(z).squeeze(-1)
|
| 137 |
+
|
| 138 |
+
target = None
|
| 139 |
+
|
| 140 |
+
if y is not None:
|
| 141 |
+
target = torch.zeros_like(relevance)
|
| 142 |
+
target[torch.arange(B, device=H.device), :, y] = 1.0
|
| 143 |
+
|
| 144 |
+
# ------------------------------------------------------------
|
| 145 |
+
# Masked reductions over the option axis
|
| 146 |
+
# ------------------------------------------------------------
|
| 147 |
+
|
| 148 |
+
if O_mask is not None:
|
| 149 |
+
om = O_mask.view(B, 1, N, 1).to(z.dtype)
|
| 150 |
+
denom = om.sum(dim=2).clamp(min=1.0)
|
| 151 |
+
z_mean = (z * om).sum(dim=2) / denom
|
| 152 |
+
om2 = O_mask.view(B, 1, N).to(causal.dtype)
|
| 153 |
+
d2 = om2.sum(dim=2).clamp(min=1.0)
|
| 154 |
+
mean = lambda t: (t * om2).sum(dim=2) / d2
|
| 155 |
+
else:
|
| 156 |
+
z_mean = z.mean(dim=2)
|
| 157 |
+
mean = lambda t: t.mean(dim=2)
|
| 158 |
+
|
| 159 |
+
gate = self.observable_gate(z_mean)
|
| 160 |
+
|
| 161 |
+
weights = F.softmax(gate, dim=-1)
|
| 162 |
+
|
| 163 |
+
energy = (
|
| 164 |
+
weights[..., 0] * mean(causal)
|
| 165 |
+
+ weights[..., 1] * mean(diversity)
|
| 166 |
+
+ weights[..., 2] * mean(specificity)
|
| 167 |
+
+ weights[..., 3] * mean(relevance)
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
energy = -energy
|
| 171 |
+
|
| 172 |
+
# ------------------------------------------------------------
|
| 173 |
+
# Weighting distribution over hypotheses (see class docstring:
|
| 174 |
+
# this is a softmax, and is not claimed to be more)
|
| 175 |
+
# ------------------------------------------------------------
|
| 176 |
+
|
| 177 |
+
temperature = 0.5 + F.softplus(self.temperature)
|
| 178 |
+
|
| 179 |
+
log_amp = -energy / (2.0 * temperature)
|
| 180 |
+
|
| 181 |
+
if H_mask is not None:
|
| 182 |
+
log_amp = log_amp.masked_fill(~H_mask, float("-inf"))
|
| 183 |
+
|
| 184 |
+
log_amp = log_amp - log_amp.max(dim=1, keepdim=True).values
|
| 185 |
+
|
| 186 |
+
amplitude = torch.exp(log_amp)
|
| 187 |
+
|
| 188 |
+
amplitude = amplitude / torch.sqrt(
|
| 189 |
+
(amplitude ** 2).sum(dim=1, keepdim=True) + 1e-8
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
probabilities = amplitude.pow(2)
|
| 193 |
+
|
| 194 |
+
probabilities = probabilities / (probabilities.sum(dim=1, keepdim=True) + 1e-8)
|
| 195 |
+
|
| 196 |
+
reliability = self.reliability(z_mean).squeeze(-1)
|
| 197 |
+
|
| 198 |
+
potential_input = torch.cat([z_mean, reliability.unsqueeze(-1)], dim=-1)
|
| 199 |
+
|
| 200 |
+
potential = self.potential(potential_input)
|
| 201 |
+
|
| 202 |
+
potential = potential * probabilities.unsqueeze(-1)
|
| 203 |
+
|
| 204 |
+
return {
|
| 205 |
+
"potential": potential,
|
| 206 |
+
"validator_energy": energy,
|
| 207 |
+
"validator_probabilities": probabilities,
|
| 208 |
+
"reliability": reliability,
|
| 209 |
+
"observable_weights": weights,
|
| 210 |
+
"causal": mean(causal),
|
| 211 |
+
"diversity": mean(diversity),
|
| 212 |
+
"specificity": mean(specificity),
|
| 213 |
+
"relevance": mean(relevance),
|
| 214 |
+
"relevance_logits": relevance,
|
| 215 |
+
"relevance_target": target,
|
| 216 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
|
| 3 |
+
transformers==4.52.4
|
| 4 |
+
|
| 5 |
+
pennylane==0.42.3
|
| 6 |
+
pennylane-lightning==0.42.0
|