everydaytok commited on
Commit
fb1a734
Β·
verified Β·
1 Parent(s): 346e23e

Update practicality_oracle.py

Browse files
Files changed (1) hide show
  1. practicality_oracle.py +71 -10
practicality_oracle.py CHANGED
@@ -5,11 +5,9 @@ import numpy as np
5
  from fractions import Fraction
6
  from typing import Dict, Tuple, Optional, Any, Callable
7
  from dataclasses import dataclass, field
8
- from google import genai
9
- from google.genai import types
10
 
11
  # ══════════════════════════════════════════════════════════════════════
12
- # SECTION A: HEISENBERG QUANTUM SIMULATOR (Physics Rules)
13
  # ══════════════════════════════════════════════════════════════════════
14
  @dataclass
15
  class StabilizerTableau:
@@ -25,14 +23,23 @@ class HeisenbergSimulator:
25
  def __init__(self, n_qubits: int):
26
  self.n = n_qubits
27
  self.state = StabilizerTableau(n_qubits)
 
 
 
 
 
 
 
28
 
29
  def h(self, q: int):
 
30
  t = self.state.tableau
31
  for i in range(2*self.n):
32
  t[i, 2*self.n] ^= t[i, q] & t[i, self.n+q]
33
  t[i, q], t[i, self.n+q] = t[i, self.n+q], t[i, q]
34
 
35
  def cnot(self, c: int, target: int):
 
36
  n = self.n; t = self.state.tableau
37
  for i in range(2*n):
38
  t[i, 2*n] ^= t[i,c] & t[i,n+target] & (t[i,target] ^ t[i,n+c] ^ 1)
@@ -59,7 +66,7 @@ class HeisenbergSimulator:
59
  return 1.0
60
 
61
  # ══════════════════════════════════════════════════════════════════════
62
- # SECTION B: THE TRUTH ORACLE (Ground Truth Checking)
63
  # ══════════════════════════════════════════════════════════════════════
64
  FACTORIZATION_TEST_CASES = [(15, 3, 5), (35, 5, 7), (85, 5, 17), (143, 11, 13)]
65
 
@@ -82,7 +89,6 @@ def extract_factors_from_binding(binding: Dict[str, float], N: int) -> Optional[
82
  return None
83
 
84
  def ground_truth_verify(binding: Dict[str, float], N: int) -> Tuple[bool, str]:
85
- """The Oracle: Prevents Hallucinations."""
86
  result = extract_factors_from_binding(binding, N)
87
  if result is None: return False, "No valid integer factor pair extractable from binding"
88
  p, q = result
@@ -110,7 +116,7 @@ class AdversaryPreFlight:
110
 
111
  binding = self.solver_callback(new_axl, N)
112
  if not binding:
113
- self.log(f" N={N}: SKIP (quick-solve failed)")
114
  continue
115
 
116
  ok, msg = ground_truth_verify(binding, N)
@@ -138,9 +144,42 @@ class AdversaryPreFlight:
138
  return "TYPE_B: Optimization landscape β€” increase rays or change initialization"
139
 
140
  # ══════════════════════════════════════════════════════════════════════
141
- # SECTION C: LLM PROMPTS & STRUCTURAL TEMPLATES
142
  # ══════════════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
 
 
 
144
  NOVEL_ISOMORPHISM_DISCOVERY_PROMPT = """\
145
  You are an isomorphism designer. Your task is to invent a continuous optimization encoding for integer factorization of N.
146
  HARD REQUIREMENTS:
@@ -153,15 +192,12 @@ Do NOT propose an isomorphism if you cannot answer these 5 constraints.
153
  """
154
 
155
  ENCODER_PROMPT = """You are the Encoder. CRITICAL RULE: Every problem MUST include an explicit INVERSE MAP in the description.
156
- If variables are x,y: inverse map is p=round(x), q=round(y).
157
- If variable is t: inverse map is p=round(t), q=N//p.
158
  OUTPUT SCHEMA (JSON only):
159
  {"name": string, "description": string, "variables": [{"name": string, "lo": number, "hi": number, "is_int": boolean}], "constraints": [{"kind": "EQ"|"GEQ"|"LEQ", "expr": string, "weight": number}], "anchors": [], "observations": {"variable_name": number}}
160
  RULES: Use ** for exponents. Variables > 10000 encode in log2 space."""
161
 
162
  COLLAPSER_PROMPT = """You are the Grounded Hypothesis Collapser.
163
  HARD RULE: For factorization problems, ALWAYS compute the integers (p, q) and verify p*q=N.
164
- If product != N: this is UNSOLVED even if CE is low. State this explicitly.
165
  OUTPUT SCHEMA (JSON only):
166
  {"scaled_formulas": {"metric": "expr"}, "hypothesis_markdown": "## Markdown output"}"""
167
 
@@ -213,5 +249,30 @@ Constraints:
213
 
214
  Anchor: snap = 0 (tolerance 0.01).
215
  Observation: snap = 0.0.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  """
217
  }
 
5
  from fractions import Fraction
6
  from typing import Dict, Tuple, Optional, Any, Callable
7
  from dataclasses import dataclass, field
 
 
8
 
9
  # ══════════════════════════════════════════════════════════════════════
10
+ # SECTION A: HEISENBERG QUANTUM SIMULATOR (CHP Stabilizer State)
11
  # ══════════════════════════════════════════════════════════════════════
12
  @dataclass
13
  class StabilizerTableau:
 
23
  def __init__(self, n_qubits: int):
24
  self.n = n_qubits
25
  self.state = StabilizerTableau(n_qubits)
26
+ self.gate_count = 0
27
+
28
+ def copy(self):
29
+ new_sim = HeisenbergSimulator(self.n)
30
+ new_sim.state = self.state.copy()
31
+ new_sim.gate_count = self.gate_count
32
+ return new_sim
33
 
34
  def h(self, q: int):
35
+ self.gate_count += 1
36
  t = self.state.tableau
37
  for i in range(2*self.n):
38
  t[i, 2*self.n] ^= t[i, q] & t[i, self.n+q]
39
  t[i, q], t[i, self.n+q] = t[i, self.n+q], t[i, q]
40
 
41
  def cnot(self, c: int, target: int):
42
+ self.gate_count += 1
43
  n = self.n; t = self.state.tableau
44
  for i in range(2*n):
45
  t[i, 2*n] ^= t[i,c] & t[i,n+target] & (t[i,target] ^ t[i,n+c] ^ 1)
 
66
  return 1.0
67
 
68
  # ══════════════════════════════════════════════════════════════════════
69
+ # SECTION B: THE TRUTH ORACLE (Ground Truth Verification)
70
  # ══════════════════════════════════════════════════════════════════════
71
  FACTORIZATION_TEST_CASES = [(15, 3, 5), (35, 5, 7), (85, 5, 17), (143, 11, 13)]
72
 
 
89
  return None
90
 
91
  def ground_truth_verify(binding: Dict[str, float], N: int) -> Tuple[bool, str]:
 
92
  result = extract_factors_from_binding(binding, N)
93
  if result is None: return False, "No valid integer factor pair extractable from binding"
94
  p, q = result
 
116
 
117
  binding = self.solver_callback(new_axl, N)
118
  if not binding:
119
+ self.log(f" N={N}: βœ— FAIL (Exact Integer Solver returned empty binding)")
120
  continue
121
 
122
  ok, msg = ground_truth_verify(binding, N)
 
144
  return "TYPE_B: Optimization landscape β€” increase rays or change initialization"
145
 
146
  # ══════════════════════════════════════════════════════════════════════
147
+ # SECTION C: SHOR DEMO & PHYSICS BENCHMARKS (No missing import bugs!)
148
  # ══════════════════════════════════════════════════════════════════════
149
+ def run_shors_demo(N: int):
150
+ print(f"\n=== Shor Demo: N={N} ===")
151
+ a = 2
152
+ r = 1
153
+ while pow(a, r, N) != 1: r += 1
154
+ print(f" Period r={r} (a={a} mod N={N})")
155
+
156
+ sim = HeisenbergSimulator(r)
157
+ for i in range(r-1):
158
+ sim.h(i)
159
+ sim.cnot(i, i+1)
160
+
161
+ zz = sim.get_operator_expectation('Z' * r)
162
+ print(f" ZZ...Z expectation = {zz:.4f}")
163
+ print(f" Variables tracked = {r} (vs 2^{r} = {2**r} SchrΓΆdinger amplitudes)")
164
+
165
+ half = pow(a, r//2, N)
166
+ f1 = math.gcd(half - 1, N)
167
+ f2 = math.gcd(half + 1, N)
168
+ print(f" Factors: gcd(a^(r/2)Β±1, N) = {f1}, {f2}")
169
+ print(f" Verify: {f1}Γ—{f2}={f1*f2} {'βœ“' if f1*f2==N else 'βœ—'}")
170
+
171
+ def benchmark_heisenberg_vs_schrodinger(n_max: int):
172
+ print(f"\n=== Heisenberg vs SchrΓΆdinger Scaling ===")
173
+ for n in range(2, n_max+1, 2):
174
+ heisenberg_vars = 2*n
175
+ schrodinger_dim = 2**n
176
+ compression = schrodinger_dim // heisenberg_vars
177
+ print(f" n={n:3d}: Heisenberg={heisenberg_vars:6d} vars | "
178
+ f"SchrΓΆdinger=2^{n} | Compression={compression:,}x")
179
 
180
+ # ═════════════════════════════════��════════════════════════════════════
181
+ # SECTION D: SYSTEM PROMPTS & STRUCTURAL TEMPLATES
182
+ # ══════════════════════════════════════════════════════════════════════
183
  NOVEL_ISOMORPHISM_DISCOVERY_PROMPT = """\
184
  You are an isomorphism designer. Your task is to invent a continuous optimization encoding for integer factorization of N.
185
  HARD REQUIREMENTS:
 
192
  """
193
 
194
  ENCODER_PROMPT = """You are the Encoder. CRITICAL RULE: Every problem MUST include an explicit INVERSE MAP in the description.
 
 
195
  OUTPUT SCHEMA (JSON only):
196
  {"name": string, "description": string, "variables": [{"name": string, "lo": number, "hi": number, "is_int": boolean}], "constraints": [{"kind": "EQ"|"GEQ"|"LEQ", "expr": string, "weight": number}], "anchors": [], "observations": {"variable_name": number}}
197
  RULES: Use ** for exponents. Variables > 10000 encode in log2 space."""
198
 
199
  COLLAPSER_PROMPT = """You are the Grounded Hypothesis Collapser.
200
  HARD RULE: For factorization problems, ALWAYS compute the integers (p, q) and verify p*q=N.
 
201
  OUTPUT SCHEMA (JSON only):
202
  {"scaled_formulas": {"metric": "expr"}, "hypothesis_markdown": "## Markdown output"}"""
203
 
 
249
 
250
  Anchor: snap = 0 (tolerance 0.01).
251
  Observation: snap = 0.0.
252
+ """,
253
+ "Shor Period-Finding: Heisenberg vs Schrodinger Resource Proof": """\
254
+ CONCRETE HYPOTHESIS: Shor Period-Finding Resource Comparison
255
+ ============================================================
256
+ Prove Heisenberg picture uses O(n^2) bits vs Schrodinger 2^n complex numbers.
257
+
258
+ Variables:
259
+ n_qubits in [4.0, 50.0]
260
+ log2_heisenberg_bits in [0.0, 14.0]
261
+ log2_schrodinger_bits in [4.0, 54.0]
262
+ log2_compression in [0.0, 50.0]
263
+ clifford_gate_count in [6.0, 1300.0]
264
+ n_operators_tracked in [8.0, 100.0]
265
+
266
+ Constraints:
267
+ EQ weight=10: log2_heisenberg_bits - log(2*n_qubits*(2*n_qubits+1))/log(2)
268
+ EQ weight=10: log2_schrodinger_bits - n_qubits - log(16)/log(2)
269
+ EQ weight=10: log2_compression - log2_schrodinger_bits + log2_heisenberg_bits
270
+ EQ weight=10: n_operators_tracked - 2*n_qubits
271
+ EQ weight=10: clifford_gate_count - n_qubits*(n_qubits+1)/2
272
+ GEQ: log2_compression - 1.0
273
+ GEQ: n_qubits - 4.0
274
+
275
+ Anchor: log2_compression >= 1.0 (mode=geq, tolerance 0.5).
276
+ Observation: n_qubits = 20.
277
  """
278
  }