everydaytok commited on
Commit
c8dddcc
Β·
verified Β·
1 Parent(s): 6c267c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -485
app.py CHANGED
@@ -1,52 +1,36 @@
1
 
2
  #!/usr/bin/env python3
3
  """
4
- PRACTICALITY SYSTEM 27.1 β€” MINIMIZE DIRECTIVE + CORRECT TEMPLATES
5
  ══════════════════════════════════════════════════════════════════════
6
- FIXES FROM 27.0:
7
-
8
- 1. MINIMIZE DIRECTIVE (Sections 1, 4, 5, 5.10, 6, 7, 13)
9
- Templates declare MINIMIZE: varname.
10
- Two effects:
11
- (a) tensor_energy adds a scaled soft objective pushing Adam
12
- toward lower values of minimize_var.
13
- (b) INT grid results are sorted by minimize_var ascending;
14
- among multiple CE=0 solutions the minimum is returned.
15
- This fixes w=2β†’w=5 for the optimal window template.
16
-
17
- 2. CORRECT TFIM TEMPLATE PHYSICS
18
- Previous template: energy >= -0.8 (wrong, actual is -1.064).
19
- Previous template: mag_z >= 0.5 (inconsistent with constraint system).
20
- New template: uses the mean-field self-consistency equations which
21
- have an exact consistent solution at mag_z=0.866, mag_x=0.5,
22
- energy=-1.0 (mean-field) / anchor at -1.064 (exact).
23
-
24
- 3. FIXED SHOR BOUNDS
25
- modsq_cnots lower bound was 1e8 but actual value is 6.7e7.
26
- Fixed to [1e7, 1e12]. Same fix for phys_qubits.
27
-
28
- 4. ACTUAL HEISENBERG CIRCUIT SIMULATION TEMPLATES
29
- New templates that simulate specific gate sequences:
30
- - GHZ N-Qubit Circuit: H on qubit 0, then CNOT chain.
31
- Variables = Pauli expectations AFTER each gate layer.
32
- Constraints = exact Heisenberg conjugation rules for CNOT.
33
- - VQE H2 Energy Minimization: encodes E(theta) = formula,
34
- MINIMIZE: energy finds the optimal rotation angle.
35
- - TFIM Trotter Step: tracks observables through one
36
- exp(-i*dt*ZZ) * exp(-i*dt*h*X) gate layer.
37
-
38
- 5. BETTER EC TEMPLATES
39
- GLV decomposition now includes a concrete scalar as Observation
40
- so the solver outputs the actual k1, k2 values.
41
- New: secp256k1 Optimal Chain now has MINIMIZE: total_ops.
42
-
43
- 6. ROBUST INFINITY GUARDRAILS (UI BUGFIXES)
44
- Added safe_round() and _c38() clippers to protect INT Grids,
45
- Adam tensors, and JSON generation from float('inf') overflow errors.
46
-
47
- KEPT INTACT FROM 27.0:
48
- Direct template parser, range-normalized Adam, INT grid cap,
49
- baton registry eviction, SymPy process isolation, all 27.0 fixes.
50
  """
51
 
52
  import os, time, random, math, threading, warnings, json, textwrap, itertools, copy
@@ -77,7 +61,7 @@ GEMINI_MODEL = "gemini-3.5-flash"
77
  warnings.filterwarnings("ignore")
78
  USE_GPU = torch.cuda.is_available()
79
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
80
- print(f"[SYSTEM 27.1] Compute: {DEVICE.type.upper()} | MINIMIZE directive + Correct Templates")
81
 
82
  # ══════════════════════════════════════════════════════════════════════
83
  # SECTION 1: CONSTANTS & SAFE HELPERS
@@ -87,7 +71,7 @@ VERIFY_G1_THRESHOLD = 0.005
87
  VERIFY_G2_TOLERANCE = 1e-3
88
  DEDUCE_ADAM_STEPS = 80
89
  ADAM_LEARNING_RATE = 0.01
90
- MINIMIZE_OBJECTIVE_WEIGHT = 0.05 # NEW 27.1: weight for soft minimize objective
91
  MAX_RAYS_PER_ATTEMPT = 24576 * 20
92
  RAY_BATCH_SIZE = 24576
93
  TEMPLATE_BATCH_SIZE = 2048
@@ -135,7 +119,7 @@ GLOBAL_SOLVE_STATE = {
135
  "proxy_composed_ce": float('inf'),
136
  "fingerprint_summary": "", "propagation_log": [],
137
  "raw_results_json": "", "infeasibility_report": "",
138
- "minimize_result": "", # NEW 27.1
139
  }
140
 
141
  FINGERPRINT_STORE: Dict[str, List[Dict]] = defaultdict(list)
@@ -337,7 +321,7 @@ class AXLProblemDef:
337
  name:str; description:str; axioms:Set[str]; variables:List[Dict]; constraints:List[Dict]
338
  scopes:List[Dict]; anchors:List[AXLInvariant]; observations:Dict[str,float]=field(default_factory=dict)
339
  is_quantum:bool=False; circuit:Any=None
340
- minimize_var:str="" # NEW 27.1: variable to minimize (empty = no minimization)
341
 
342
  class AXLtoPSLCompiler:
343
  def compile(self,prob:AXLProblemDef) -> str:
@@ -408,6 +392,7 @@ def compile_mc(kind,expr_str,direction,variables,weight=1.0,scope="root",branche
408
  if not rivs: return IV(-1e18,1e18)
409
  return IV(min(r.lo for r in rivs),max(r.hi for r in rivs))
410
  mc.fast_iv=_or_iv; return mc
 
411
  syms={v:sp.Symbol(v) for v in variables}
412
  try:
413
  parsed=parse_expr(expr_str,local_dict=syms) if kind!="or_eq" else None
@@ -425,12 +410,18 @@ def compile_mc(kind,expr_str,direction,variables,weight=1.0,scope="root",branche
425
  'sinh':torch.sinh,'cosh':torch.cosh,'tanh':torch.tanh,
426
  'pi':math.pi,'E':math.e}
427
  t_func_raw=sp.lambdify([sp.Symbol(v) for v in mc.syms_used],parsed,modules=[pt_map,"math"])
 
428
  def _t_wrapper(*args):
429
- val=t_func_raw(*args)
430
- if not isinstance(val,torch.Tensor):
431
- try: val=torch.tensor(float(val),device=DEVICE,dtype=torch.float32)
432
- except: return torch.tensor(9999.0,device=DEVICE,dtype=torch.float32)
433
- return val
 
 
 
 
 
434
  mc.torch_func=_t_wrapper
435
  if kind=="equality":
436
  if expr_str not in PROJECTION_CACHE:
@@ -471,7 +462,7 @@ class Problem:
471
  ordering_pairs:List[Tuple[str,str]]=field(default_factory=list)
472
  is_quantum:bool=False; circuit:Any=None; quantum_vm:Any=None
473
  adjacency_list:Dict[str,Set[str]]=field(default_factory=lambda:defaultdict(set))
474
- minimize_var:str="" # NEW 27.1
475
 
476
  def __post_init__(self):
477
  self.compiled_constraints=[
@@ -525,8 +516,7 @@ class Problem:
525
  if neighbor not in visited: visited.add(neighbor); queue.append((neighbor,d+1))
526
  return visited
527
 
528
- def tensor_energy(self,X:torch.Tensor,step_ratio:float=1.0) -> torch.Tensor:
529
- """NEW 27.1: includes soft minimize objective when minimize_var is set."""
530
  if self.is_quantum and self.quantum_vm:
531
  return self.quantum_vm.execute(X,step_ratio,DEVICE).view(-1)
532
  is_batched=(X.dim()==2); batch_size=X.shape[0] if is_batched else 1
@@ -556,28 +546,31 @@ class Problem:
556
  margin=(hi-lo)*0.1*(1.0-step_ratio)
557
  out_of_bounds=torch.relu(lo-margin-col)+torch.relu(col-(hi+margin))
558
  total+=(out_of_bounds**2)*10.0
559
- # ── SOFT MINIMIZE OBJECTIVE (NEW 27.1) ──────────────────────
560
- if self.minimize_var and self.minimize_var in self.var_idx:
561
- midx=self.var_idx[self.minimize_var]
562
- lo,hi=_c38(self.bounds[self.minimize_var][0]),_c38(self.bounds[self.minimize_var][1])
563
- rng=max(hi-lo,1e-8)
564
- col=X[:,midx] if is_batched else X[midx]
565
- normalized=(col-lo)/rng # in [0,1]; push toward 0 = minimum
566
- total+=normalized*MINIMIZE_OBJECTIVE_WEIGHT*step_ratio
 
 
567
  return total.view(batch_size,-1).sum(dim=1)
568
 
569
- def scalar_energy(self,b:Dict[str,float]) -> float:
570
  x_arr=[b.get(v,(_c38(self.bounds.get(v,(-1,1))[0])+_c38(self.bounds.get(v,(-1,1))[1]))/2) for v in self.variables]
571
  X_t=torch.tensor(x_arr,device=DEVICE,dtype=torch.float32).unsqueeze(0)
572
  with torch.no_grad():
573
- return float(self.tensor_energy(X_t,step_ratio=1.0).item())
 
574
 
575
  def build_base_problem(axl_def:AXLProblemDef) -> Problem:
576
  psl_text=AXL_COMPILER.compile(axl_def); prog=parse_psl(psl_text); ep=expand_psl(prog)
577
  prob=Problem(pid=f"base_{axl_def.name}",variables=ep.variables,constraints=ep.constraints,
578
  bounds=ep.bounds,int_vars=ep.int_vars,scope_groups=ep.scope_groups,
579
  scope_vars=ep.scope_vars,scope_order=ep.scope_order,
580
- minimize_var=axl_def.minimize_var) # NEW 27.1
581
  if axl_def.is_quantum: prob.is_quantum=True; prob.circuit=axl_def.circuit; prob.__post_init__()
582
  return prob
583
 
@@ -750,7 +743,7 @@ def _global_hc4_tighten_bounds(problem:Problem) -> Dict[str,Tuple[float,float]]:
750
  for v in problem.bounds if v in c}
751
 
752
  # ══════════════════════════════════════════════════════════════════════
753
- # SECTION 5.10: DIRECT TEMPLATE PARSER (updated 27.1: MINIMIZE support)
754
  # ══════════════════════════════════════════════════════════════════════
755
  _VAR_RE = re.compile(r'^\s*([a-zA-Z_][a-zA-Z0-9_]*(?:,\s*[a-zA-Z_][a-zA-Z0-9_]*)*)\s+in\s+\[([^\]]+)\]\s*(INT)?\s*',re.IGNORECASE)
756
  _CON_RE = re.compile(r'^\s*(EQ|GEQ|LEQ)(?:\s+weight\s*=\s*([0-9.]+))?\s*:\s*(.+)$',re.IGNORECASE)
@@ -1160,7 +1153,10 @@ def _mini_solve_component(sub_axl,sub_prob,seed_binding):
1160
 
1161
  def run_proxy_decomposition(axl_def,base_problem):
1162
  components=find_markov_components(base_problem)
1163
- if len(components)<=1: return {},float('inf'),[],False
 
 
 
1164
  interfaces=find_interface_vars(components,base_problem)
1165
  _add_log(f"PROXY DECOMP: {len(components)} components | sizes {[len(c) for c in components]}")
1166
  _update_state(proxy_n_components=len(components))
@@ -1216,35 +1212,22 @@ def detect_divergence(problem_name):
1216
  return False,f"ATTRACTOR-STABLE: {len(good)} runs converged."
1217
 
1218
  # ══════════════════════════════════════════════════════════════════════
1219
- # SECTION 6.7: HYPOTHESIS TEMPLATES (MERGED ALL 17 TEMPLATES)
1220
  # ══════════════════════════════════════════════════════════════════════
1221
  STRUCTURAL_HYPOTHESIS_TEMPLATES = {
1222
 
1223
  "Heisenberg GHZ: N-Qubit Circuit Simulation": """\
1224
  CONCRETE HYPOTHESIS: GHZ State Preparation via Heisenberg Circuit Simulation
1225
  =============================================================================
1226
- Circuit: H(qubit_0) then CNOT(0->1), CNOT(1->2), ..., CNOT(N-2->N-1)
1227
- State: |0>^N -> GHZ = (|0...0> + |1...1>)/sqrt(2)
1228
-
1229
- HEISENBERG PICTURE:
1230
- State fixed at |0>^N. Operators evolve under conjugation by gates.
1231
- H gate: Z->X, X->Z.
1232
- CNOT(c,t): Z_t -> Z_c*Z_t, X_c -> X_c*X_t, Z_c -> Z_c, X_t -> X_t.
1233
-
1234
- After H(0): <X_0>=1, <Z_0>=0, all others at initial |0> values.
1235
- After CNOT chain: GHZ structure β€” all ZZ correlators = 1, all single Z = 0.
1236
-
1237
- For N=1,000,000 qubits: 4 variables suffice (translational invariance).
1238
-
1239
- Variables (final state after full GHZ circuit):
1240
- z_unif in [-0.1, 0.1] <Z_i> uniform (should be 0 in GHZ)
1241
- x0_after_H in [0.9, 1.1] <X_0> after H gate on qubit 0
1242
- zz_nn in [0.9, 1.1] <Z_i Z_{i+1}> NN ZZ correlator (should be 1)
1243
- zz_nnn in [0.9, 1.1] <Z_i Z_{i+2}> NNN ZZ correlator (GHZ: = 1 too)
1244
- n_qubits in [2.0, 1000000.0] number of qubits (parameter)
1245
- variables_used in [4.0, 4.0] always 4 for any N (Heisenberg advantage)
1246
- schrodinger_dim in [4.0, 1e301] 2^n_qubits (state vector size)
1247
- compression in [1.0, 1e301] schrodinger_dim / variables_used
1248
 
1249
  Constraints:
1250
  EQ weight=10: z_unif
@@ -1260,31 +1243,18 @@ Constraints:
1260
  Anchor: zz_nn - 1.0 = 0 (tolerance 0.01).
1261
  Anchor: z_unif = 0 (tolerance 0.01).
1262
  Observation: n_qubits = 1000000.
1263
-
1264
- COLLAPSER:
1265
- From binding: schrodinger_dim = 2^1000000 (a number with 301,030 digits).
1266
- Variables needed = 4.
1267
- Compression = 2^1000000 / 4.
1268
- State exactly: "To simulate the GHZ preparation circuit on [n_qubits] qubits,
1269
- the Schrodinger picture requires tracking [schrodinger_dim] amplitudes.
1270
- The Heisenberg picture requires [variables_used] variables β€” the same 4
1271
- regardless of N. This is not an approximation: the GHZ Pauli structure
1272
- is exactly captured by these 4 observables at any system size."
1273
  """,
1274
 
1275
  "Heisenberg VQE: H2 Energy Minimization over Rotation Angle": """\
1276
  CONCRETE HYPOTHESIS: H2 Ground State via VQE Angle Optimization
1277
  ===============================================================
1278
- H2 STO-3G at R=0.735 Ang. 2-qubit Jordan-Wigner Hamiltonian:
1279
- H = g0*I + g1*Z0 + g2*Z1 + g3*Z0Z1 + g4*X0X1 + g5*Y0Y1
1280
-
1281
  Variables:
1282
- theta in [0.0, 6.28319] variational rotation angle
1283
- iz in [-1.0, 1.0] <Z0>
1284
- zi in [-1.0, 1.0] <Z1>
1285
- zz in [-1.1, -0.9] <Z0Z1> = -1 (fixed)
1286
- xx in [-1.0, 1.0] <X0X1>
1287
- energy in [-1.15, -1.09] variational energy
1288
 
1289
  Constraints:
1290
  EQ weight=10: iz + cos(theta)
@@ -1306,11 +1276,11 @@ Anchor: zz + 1.0 = 0 (tolerance 0.01).
1306
  CONCRETE HYPOTHESIS: 1D TFIM Ferromagnetic Ground State via Mean-Field
1307
  ======================================================================
1308
  Variables:
1309
- mag_z in [0.7, 1.0] <Z_i> uniform site magnetization
1310
- mag_x in [0.3, 0.7] <X_i> transverse magnetization
1311
- corr_zz in [0.5, 1.0] <Z_i Z_{i+1}> NN ZZ correlator
1312
- energy_per_site in [-1.2, -0.7] energy per site E/N
1313
- gap in [0.8, 1.2] excitation gap = 2|J-h|
1314
 
1315
  Constraints:
1316
  EQ weight=10: mag_x**2*(mag_z**2 + 0.25) - 0.25
@@ -1325,95 +1295,6 @@ Anchor: gap - 1.0 = 0 (tolerance 0.01).
1325
  Anchor: energy_per_site + 1.0 = 0 (tolerance 0.05).
1326
  """,
1327
 
1328
- "Heisenberg TFIM Trotter: One Circuit Step Observable Evolution": """\
1329
- CONCRETE HYPOTHESIS: TFIM Trotterized Circuit One-Step Heisenberg Evolution
1330
- ===========================================================================
1331
- Variables:
1332
- z_in in [0.99, 1.01] initial <Z> = 1.0
1333
- z_mid in [0.9, 1.0] after X rotation
1334
- z_out in [0.9, 1.0] after ZZ rotation (=z_mid for ZZ rotation)
1335
- zz_in in [0.99, 1.01] initial <ZZ> = 1.0
1336
- zz_mid in [0.85, 1.0] after X rotation
1337
- zz_out in [0.85, 1.0] after ZZ rotation
1338
- x_out in [-0.1, 0.1] final <X> (should be ~0 from initial 0)
1339
- energy_out in [-2.0, 0.0] energy after step
1340
-
1341
- Constraints:
1342
- EQ weight=10: z_in - 1.0
1343
- EQ weight=10: zz_in - 1.0
1344
- EQ weight=10: z_mid - z_in*0.95534
1345
- EQ weight=10: zz_mid - zz_in*0.91241
1346
- EQ weight=10: z_out - z_mid
1347
- EQ weight=10: zz_out - zz_mid
1348
- EQ weight=5: x_out
1349
- EQ weight=5: energy_out + zz_out + 0.5*x_out
1350
- GEQ: z_out - 0.85
1351
- GEQ: 1.0 - z_out
1352
-
1353
- Anchor: z_mid - 0.9553 = 0 (tolerance 0.005).
1354
- Anchor: zz_out - 0.9124 = 0 (tolerance 0.01).
1355
- """,
1356
-
1357
- "Heisenberg Clifford: 4-Qubit Chain Observable Evolution": """\
1358
- CONCRETE HYPOTHESIS: 4-Qubit 1D Chain Clifford Circuit via Heisenberg Picture
1359
- =============================================================================
1360
- Variables:
1361
- x0, x1, x2, x3 in [-1.0, 1.0] single-qubit X after circuit
1362
- z0, z1, z2, z3 in [-1.0, 1.0] single-qubit Z after circuit
1363
- zz01 in [-1.0, 1.0] ZZ(0,1) correlator
1364
- zz12 in [-1.0, 1.0] ZZ(1,2) correlator
1365
- zz23 in [-1.0, 1.0] ZZ(2,3) correlator
1366
- magnetization in [-1.0, 1.0] average Z per site
1367
- entanglement_proxy in [0.0, 1.0] mean |ZZ| correlator strength
1368
-
1369
- Constraints:
1370
- EQ weight=10: z0
1371
- EQ weight=10: z1
1372
- EQ weight=10: z2
1373
- EQ weight=10: z3
1374
- EQ weight=10: magnetization - (z0 + z1 + z2 + z3)/4.0
1375
- EQ weight=10: zz01
1376
- EQ weight=10: zz12
1377
- EQ weight=10: zz23
1378
- EQ weight=10: entanglement_proxy - (x0**2 + x1**2 + x2**2 + x3**2)/4.0
1379
- GEQ: 1.0 - x0**2 - z0**2
1380
- GEQ: 1.0 - x1**2 - z1**2
1381
- GEQ: 1.0 - x2**2 - z2**2
1382
- GEQ: 1.0 - x3**2 - z3**2
1383
-
1384
- Anchor: magnetization = 0 (tolerance 0.01).
1385
- Anchor: zz01 = 0 (tolerance 0.01).
1386
- """,
1387
-
1388
- "Heisenberg XXZ: Spin-Half Chain Magnetization Plateaus": """\
1389
- CONCRETE HYPOTHESIS: 1D XXZ Chain Magnetization Plateaus via Observables
1390
- =========================================================================
1391
- Variables:
1392
- mag_z in [-1.0, 1.0] <Z_i> uniform Z-magnetization
1393
- corr_xx in [-1.0, 1.0] <X_i X_{i+1}> = <Y_i Y_{i+1}> by symmetry
1394
- corr_zz in [-1.0, 1.0] <Z_i Z_{i+1}> Ising correlator
1395
- chirality in [-1.0, 1.0] <X_i Y_{i+1} - Y_i X_{i+1}> vector chirality
1396
- energy_ps in [-3.0, 0.0] energy per site
1397
- suscept in [0.0, 5.0] d<Z>/dh magnetic susceptibility proxy
1398
- plateau in [0.0, 1.0] indicator: 1 if near magnetization plateau
1399
-
1400
- Constraints:
1401
- EQ weight=10: energy_ps - (-corr_xx - 0.5*corr_zz - 0.3*mag_z)
1402
- EQ weight=5: corr_xx - (-0.3*mag_z - 0.1)
1403
- EQ weight=10: corr_zz - mag_z**2 - 0.05*(1.0 - mag_z**2)
1404
- EQ weight=5: chirality
1405
- EQ weight=5: suscept - (1.0 - mag_z**2)*2.0
1406
- GEQ: 1.0 - mag_z**2 - corr_xx**2
1407
- GEQ: corr_zz - (mag_z**2 - 0.3)
1408
- GEQ: mag_z + 1.0
1409
- LEQ: mag_z - 1.0
1410
- GEQ: plateau
1411
- LEQ: plateau - 1.0
1412
-
1413
- Anchor: chirality = 0 (tolerance 0.01).
1414
- Anchor: energy_ps + 0.75 = 0 (tolerance 0.1).
1415
- """,
1416
-
1417
  "secp256k1 Optimal Window: MINIMIZE total operations": """\
1418
  CONCRETE HYPOTHESIS: secp256k1 wNAF Optimal Window via Integer Minimization
1419
  ============================================================================
@@ -1463,70 +1344,6 @@ Anchor: k1 + k2*77 - (314 - m*1000) = 0 (tolerance 0.01).
1463
  Observation: k_target = 314.
1464
  """,
1465
 
1466
- "secp256k1 Montgomery Ladder vs Double-and-Add": """\
1467
- CONCRETE HYPOTHESIS: Montgomery Ladder Constant-Time Overhead
1468
- =============================================================
1469
- Variables:
1470
- scalar_bits in [254, 258] INT
1471
- montgomery_ops in [500, 520] INT
1472
- dbl_add_doubles in [252, 260] INT
1473
- dbl_add_adds in [100, 140] INT
1474
- dbl_add_total in [350, 400] INT
1475
- ct_overhead in [0.2, 0.5]
1476
-
1477
- Constraints:
1478
- EQ weight=10: montgomery_ops - 2*scalar_bits
1479
- EQ weight=10: dbl_add_doubles - scalar_bits
1480
- EQ weight=10: dbl_add_adds - scalar_bits/2
1481
- EQ weight=10: dbl_add_total - dbl_add_doubles - dbl_add_adds
1482
- EQ weight=10: ct_overhead - (montgomery_ops - dbl_add_total)/dbl_add_total
1483
- GEQ: ct_overhead - 0.28
1484
- LEQ: ct_overhead - 0.40
1485
-
1486
- Anchor: montgomery_ops - 2*scalar_bits = 0 (tolerance 2.0).
1487
- """,
1488
-
1489
- "secp256k1 Schnorr Batch Verify: Pippenger Scaling": """\
1490
- CONCRETE HYPOTHESIS: Schnorr Batch Verification via Pippenger
1491
- =============================================================
1492
- Variables:
1493
- n_sigs in [2, 10000] INT
1494
- naive_ops in [500, 3000000]
1495
- pippenger_adds in [100, 500000]
1496
- bucket_width in [4, 16] INT
1497
- n_buckets in [16, 65536] INT
1498
- batch_speedup in [1.0, 1000.0]
1499
-
1500
- Constraints:
1501
- EQ weight=10: naive_ops - n_sigs*768
1502
- EQ weight=10: n_buckets - 2**bucket_width
1503
- EQ weight=10: pippenger_adds - 256*n_buckets + n_sigs*256/bucket_width
1504
- EQ weight=10: batch_speedup - naive_ops/pippenger_adds
1505
- GEQ: batch_speedup - 1.0
1506
-
1507
- Anchor: batch_speedup - 1.0 >= 0 (mode=geq, tolerance 0.1).
1508
- """,
1509
-
1510
- "secp256k1 Group Law Feasibility": """\
1511
- STRUCTURAL HYPOTHESIS: secp256k1 Elliptic Curve Group Law
1512
- ==========================================================
1513
- Variables:
1514
- x1 in [0.1, 3.0]
1515
- y1 in [0.1, 10.0]
1516
- m in [-50.0, 50.0]
1517
- x3 in [-5.0, 15.0]
1518
- y3 in [-30.0, 30.0]
1519
-
1520
- Constraints:
1521
- EQ weight=10: y1**2 - x1**3 - 7
1522
- EQ weight=10: 2*y1*m - 3*x1**2
1523
- EQ weight=10: x3 - m**2 + 2*x1
1524
- EQ weight=10: y3 + m*(x3 - x1) + y1
1525
- EQ weight=10: y3**2 - x3**3 - 7
1526
-
1527
- Anchor: y3**2 - x3**3 - 7 = 0 (tolerance 0.001).
1528
- """,
1529
-
1530
  "1024-Qubit Shor: Concrete Full Gate Audit": """\
1531
  CONCRETE HYPOTHESIS: Shor RSA-1024 at 1024 Logical Qubits
1532
  ==========================================================
@@ -1551,142 +1368,11 @@ Constraints:
1551
 
1552
  Anchor: n_log_qubits - 1027 = 0 (tolerance 2.0).
1553
  Observation: n_bits = 512.
1554
- """,
1555
-
1556
- "2048-Qubit Shor: RSA-2048 Full Resource Certificate": """\
1557
- CONCRETE HYPOTHESIS: Shor RSA-2048 Resource Certificate
1558
- ========================================================
1559
- Variables:
1560
- n_bits in [2046, 2050] INT
1561
- n_log_qubits in [4096, 4104] INT
1562
- total_tgates in [1e12, 1e17]
1563
- total_cnots in [1e12, 1e17]
1564
- code_dist in [25, 50] INT
1565
- phys_qubits in [1e6, 1e10]
1566
- wall_time_days in [1.0, 100000000.0]
1567
- gate_time_ns in [100.0, 2000.0]
1568
-
1569
- Constraints:
1570
- EQ weight=10: n_log_qubits - (2*n_bits + 3)
1571
- EQ weight=10: total_tgates - 512*n_bits**3
1572
- EQ weight=10: total_cnots - 256*n_bits**3
1573
- EQ weight=10: code_dist - 31
1574
- EQ weight=10: phys_qubits - n_log_qubits*2*code_dist**2
1575
- EQ weight=5: wall_time_days - total_tgates*code_dist*gate_time_ns*1e-9/86400
1576
- GEQ: gate_time_ns - 100
1577
- LEQ: gate_time_ns - 1000
1578
-
1579
- Anchor: n_log_qubits - 4099 = 0 (tolerance 2.0).
1580
- Observation: n_bits = 2048.
1581
- """,
1582
-
1583
- "Kyber-1024 NTT: Post-Quantum Key Generation Audit": """\
1584
- CONCRETE HYPOTHESIS: CRYSTALS-Kyber-1024 NTT Operation Count
1585
- =============================================================
1586
- Variables:
1587
- n_poly in [254, 258] INT
1588
- k_param in [3, 5] INT
1589
- ntt_butterflies in [900, 1100] INT
1590
- ntt_mults in [900, 1100] INT
1591
- ntt_adds in [1800, 2200] INT
1592
- keygen_ntts in [10, 25] INT
1593
- total_mults in [5000, 30000] INT
1594
- total_adds in [10000, 60000] INT
1595
-
1596
- Constraints:
1597
- EQ weight=10: ntt_butterflies - n_poly*4
1598
- EQ weight=10: ntt_mults - ntt_butterflies
1599
- EQ weight=10: ntt_adds - 2*ntt_butterflies
1600
- EQ weight=10: keygen_ntts - k_param*(k_param + 1)
1601
- EQ weight=10: total_mults - keygen_ntts*ntt_mults
1602
- EQ weight=10: total_adds - keygen_ntts*ntt_adds
1603
-
1604
- Anchor: total_mults - keygen_ntts*ntt_mults = 0 (tolerance 10.0).
1605
- Observation: k_param = 4.
1606
- """,
1607
-
1608
- "Grover Oracle: SHA256 Preimage Circuit Cost": """\
1609
- CONCRETE HYPOTHESIS: Grover SHA-256 Preimage Circuit
1610
- =====================================================
1611
- Variables:
1612
- output_bits in [254, 258] INT
1613
- oracle_toffoli in [1400, 1600] INT
1614
- oracle_cnots in [2800, 3200] INT
1615
- grover_iters in [125, 130]
1616
- total_log2_ops in [128, 132]
1617
- toffoli_to_t in [6, 8] INT
1618
- log2_tgates in [135, 145]
1619
- code_dist in [25, 55] INT
1620
-
1621
- Constraints:
1622
- EQ weight=10: oracle_toffoli - 1500
1623
- EQ weight=10: oracle_cnots - 3000
1624
- EQ weight=10: grover_iters - output_bits/2
1625
- EQ weight=10: total_log2_ops - grover_iters + 1
1626
- EQ weight=10: toffoli_to_t - 7
1627
- EQ weight=10: log2_tgates - total_log2_ops + 10
1628
- EQ weight=5: code_dist - 33
1629
- GEQ: log2_tgates - 135
1630
-
1631
- Anchor: grover_iters - 128 = 0 (tolerance 1.0).
1632
- """,
1633
-
1634
- "LWE Lattice Crypto: Short Vector Feasibility": """\
1635
- STRUCTURAL HYPOTHESIS: Learning With Errors (n=4 proxy)
1636
- ========================================================
1637
- Variables:
1638
- s0 in [-5.0, 5.0] INT
1639
- s1 in [-5.0, 5.0] INT
1640
- s2 in [-5.0, 5.0] INT
1641
- s3 in [-5.0, 5.0] INT
1642
- e0 in [-1.5, 1.5]
1643
- e1 in [-1.5, 1.5]
1644
- e2 in [-1.5, 1.5]
1645
- e3 in [-1.5, 1.5]
1646
-
1647
- Constraints:
1648
- EQ: 3*s0 + s1 + 4*s2 + s3 + e0 - 17
1649
- EQ: 5*s0 + 9*s1 + 2*s2 + 6*s3 + e1 - 43
1650
- EQ: 5*s0 + 3*s1 + 5*s2 + 8*s3 + e2 - 31
1651
- EQ: 9*s0 + 7*s1 + 9*s2 + 3*s3 + e3 - 36
1652
- GEQ: 1 - e0**2
1653
- GEQ: 1 - e1**2
1654
- GEQ: 1 - e2**2
1655
- GEQ: 1 - e3**2
1656
-
1657
- Anchor: s0 - 1 = 0 (tolerance 0.1).
1658
- """,
1659
-
1660
- "Quantum Bell State Structural Feasibility": """\
1661
- STRUCTURAL HYPOTHESIS: Bell State Maximal Entanglement
1662
- ======================================================
1663
- Variables:
1664
- x0 in [-1.0, 1.0]
1665
- y0 in [-1.0, 1.0]
1666
- z0 in [-1.0, 1.0]
1667
- x1 in [-1.0, 1.0]
1668
- y1 in [-1.0, 1.0]
1669
- z1 in [-1.0, 1.0]
1670
- xx01 in [-1.0, 1.0]
1671
- zz01 in [-1.0, 1.0]
1672
-
1673
- Constraints:
1674
- EQ weight=5: z0
1675
- EQ weight=5: z1
1676
- EQ weight=5: x0
1677
- EQ weight=5: x1
1678
- EQ weight=10: zz01 - 1
1679
- EQ weight=10: xx01 - 1
1680
- GEQ: 1 - x0**2 - y0**2 - z0**2
1681
- GEQ: 1 - x1**2 - y1**2 - z1**2
1682
-
1683
- Anchor: zz01 - 1 = 0 (tolerance 0.01).
1684
- Anchor: xx01 - 1 = 0 (tolerance 0.01).
1685
  """
1686
  }
1687
 
1688
  # ══════════════════════════════════════════════════════════════════════
1689
- # SECTION 7: MASKED DEDUCTION β€” RANGE-NORMALIZED ADAM
1690
  # ══════════════════════════════════════════════════════════════════════
1691
  @dataclass
1692
  class L9Certificate:
@@ -1713,60 +1399,57 @@ def _batched_deduce_and_evaluate(problem, hyps: List['Hypothesis']) -> List[Tupl
1713
  adam_hyps=[hyps[i] for i in solve_indices]
1714
  B=len(adam_hyps); V=len(problem.variables)
1715
 
1716
- # Use _c38 helper to guard PyTorch against overflow inf
1717
- lo_np = np.array([_c38(problem.bounds[v][0]) for v in problem.variables], dtype=np.float32)
1718
- hi_np = np.array([_c38(problem.bounds[v][1]) for v in problem.variables], dtype=np.float32)
1719
- rng_np = np.maximum(hi_np - lo_np, 1e-8)
1720
- lo_t = torch.tensor(lo_np, device=DEVICE, dtype=torch.float32)
1721
- rng_t = torch.tensor(rng_np, device=DEVICE, dtype=torch.float32)
1722
-
1723
- def _to_orig(X_n: torch.Tensor) -> torch.Tensor:
1724
- return X_n * rng_t.unsqueeze(0) + lo_t.unsqueeze(0)
1725
-
1726
- x_data_n, mask_data, target_data_n = [], [], []
1727
  for hyp in adam_hyps:
1728
  xr, mr, tr = [], [], []
1729
  active_vars=problem.get_markov_blanket(set(hyp.pinned_vars.keys()), depth=2)
1730
  for j,v in enumerate(problem.variables):
1731
- lo,hi=_c38(problem.bounds[v][0]),_c38(problem.bounds[v][1]); rng=max(hi-lo, 1e-8)
1732
  if v in hyp.pinned_vars:
1733
- val=_c38(hyp.pinned_vars[v]); val_n=(val-lo)/rng
1734
- xr.append(val_n); mr.append(0.0); tr.append(val_n)
1735
  else:
1736
- val=_c38(hyp.binding.get(v,(lo+hi)/2)); val_n=(val-lo)/rng
1737
  is_active=(v in active_vars) or (len(hyp.pinned_vars)==0)
1738
- xr.append(val_n); mr.append(1.0 if is_active else 0.0); tr.append(0.0)
1739
- x_data_n.append(xr); mask_data.append(mr); target_data_n.append(tr)
1740
 
1741
- X_n = torch.tensor(x_data_n, device=DEVICE, dtype=torch.float32, requires_grad=True)
1742
- mask = torch.tensor(mask_data, device=DEVICE, dtype=torch.float32)
1743
- target_n = torch.tensor(target_data_n, device=DEVICE, dtype=torch.float32)
1744
 
1745
- optimizer = torch.optim.Adam([X_n], lr=ADAM_LEARNING_RATE)
1746
 
1747
  for step in range(DEDUCE_ADAM_STEPS):
1748
  optimizer.zero_grad()
1749
  step_ratio = min(1.0, step / (DEDUCE_ADAM_STEPS * 0.8))
1750
- X_orig = _to_orig(X_n)
1751
- ce = problem.tensor_energy(X_orig, step_ratio)
 
 
1752
  if isinstance(ce, torch.Tensor) and (ce < SOLVE_THRESHOLD).all() and step_ratio == 1.0:
1753
  break
1754
  ce.sum().backward()
 
1755
  with torch.no_grad():
1756
- X_n.grad.clamp_(-10.0, 10.0)
1757
- X_n.grad *= mask
1758
  optimizer.step()
1759
- X_n.data = torch.where(mask == 0.0, target_n, X_n.data)
1760
- margin_n = 0.1 * (1.0 - step_ratio)
1761
- X_n.data.clamp_(-margin_n, 1.0 + margin_n)
 
 
1762
 
1763
  optimizer.zero_grad()
1764
- X_orig_final = _to_orig(X_n)
1765
- final_ce = problem.tensor_energy(X_orig_final, 1.0).view(-1)
1766
  final_ce.sum().backward()
 
1767
  ce_vals = final_ce.detach().cpu().numpy()
1768
- X_vals = X_orig_final.detach().cpu().numpy()
1769
- grads_abs = X_n.grad.abs()
1770
  _, topk_idx = torch.topk(grads_abs, k=min(3,V), dim=1)
1771
  topk_idx_np = topk_idx.cpu().numpy()
1772
  grads_np = grads_abs.cpu().numpy()
@@ -1782,13 +1465,12 @@ def _batched_deduce_and_evaluate(problem, hyps: List['Hypothesis']) -> List[Tupl
1782
 
1783
  def _mprt_sample(problem, work_box, N):
1784
  var_list=problem.variables; V=len(var_list)
1785
- # Guard against initial tensor inf bounds which crash PyTorch energy evaluation
1786
  lo_t=torch.tensor([_c38(max(problem.bounds.get(v,(-10.0,10.0))[0], work_box[v].lo if v in work_box else problem.bounds.get(v,(-10,10))[0])) for v in var_list], device=DEVICE, dtype=torch.float32)
1787
  hi_t=torch.tensor([_c38(min(problem.bounds.get(v,(-10.0,10.0))[1], work_box[v].hi if v in work_box else problem.bounds.get(v,(-10,10))[1])) for v in var_list], device=DEVICE, dtype=torch.float32)
1788
  for i in range(V):
1789
  if lo_t[i]>=hi_t[i]: m=(lo_t[i]+hi_t[i])/2; lo_t[i]=m-1e-6; hi_t[i]=m+1e-6
1790
  X=lo_t.unsqueeze(0)+(hi_t-lo_t).unsqueeze(0)*torch.rand((N,V), device=DEVICE)
1791
- ce_batch=problem.tensor_energy(X,1.0).view(-1); best_idx=torch.argmin(ce_batch).item()
1792
  return {v:float(X[best_idx,i].item()) for i,v in enumerate(var_list)}, ce_batch[best_idx].item()
1793
 
1794
  # ══════════════════════════════════════════════════════════════════════
@@ -2182,7 +1864,7 @@ def _verify(binding, base_problem, anchors):
2182
  return g1_pass, all(v[1] for v in g2.values()) if g2 else True, g2, safe_round(g1_ce,6)
2183
 
2184
  # ══════════════════════════════════════════════════════════════════════
2185
- # SECTION 13: SEQUENCE RAY TRACER β€” BATON REGISTRY EVICTION
2186
  # ══════════════════════════════════════════════════════════════════════
2187
  class SequenceRayTracer:
2188
  def trace(self, axl_def, base_problem, use_proxy_decomp=True):
@@ -2300,6 +1982,7 @@ class SequenceRayTracer:
2300
  bandit.record_reward(ray.sequence[-1],parent_ce,final_ce)
2301
  g1_pass,g2_pass,inv_results,_=_verify(final_b,base_problem,axl_def.anchors)
2302
  improved=final_ce<best_ce; passed_pruning=final_ce<parent_ce*CE_EARN_RATIO
 
2303
  if improved or (g1_pass and g2_pass) or passed_pruning:
2304
  with STATE_LOCK:
2305
  GLOBAL_SOLVE_STATE["recent_traces"].append(HypothesisTrace(
@@ -2308,19 +1991,25 @@ class SequenceRayTracer:
2308
  survived=(g1_pass and g2_pass),elapsed_ms=0.0,
2309
  g1_pass=g1_pass,g2_pass=g2_pass,binding=final_b,
2310
  invariant_results=inv_results,tension_class=tension_class,depth=ray.depth))
 
2311
  out_baton=Baton(binding=final_b,ce=final_ce,ray_id=ray.ray_id,
2312
  l9=L9Certificate(final_ce,dom_vars,[],tension_class))
2313
- if final_ce<BATON_REGISTRY_THRESHOLD:
2314
- baton_registry[ray.ray_id]=out_baton
2315
- # ── BATON REGISTRY EVICTION ────────────
2316
- if len(baton_registry)>BATON_REGISTRY_MAX:
2317
- worst_key=max(baton_registry, key=lambda k:baton_registry[k].ce)
 
 
2318
  del baton_registry[worst_key]
 
2319
  if improved:
2320
  best_ce=final_ce; best_binding=dict(final_b)
2321
  model.best_ray=ray.name; best_ray_name=ray.name
2322
  if g1_pass and g2_pass and final_ce<SOLVE_THRESHOLD: solved=True
2323
- if (passed_pruning or improved) and ray.depth<MAX_CHAIN_DEPTH:
 
 
2324
  remaining=[a for a in ALL_AXIOMS if a not in ray.sequence]
2325
  queues["core"].extend(bandit.intelligent_branch(ray,out_baton,remaining,BRANCH_WIDTH,sketch))
2326
 
@@ -2378,7 +2067,7 @@ OUTPUT SCHEMA (JSON only, no markdown):
2378
  RULES: USE ** FOR EXPONENTS. NEVER USE ^. No =, >=, <= inside expressions.
2379
  EQ/GEQ/LEQ are expression's relation to zero. Output ONLY the JSON object."""
2380
 
2381
- COLLAPSER_SYSTEM_PROMPT = """You are the Grounded Hypothesis Engine for Practicality 27.1.
2382
 
2383
  Check infeasibility_report first. If non-empty: the system proved infeasibility via
2384
  algebraic propagation before firing any rays. Output:
@@ -2659,7 +2348,7 @@ def trigger_hypothesis_solve(template_name, api_key):
2659
  daemon=True).start()
2660
 
2661
  # ══════════════════════════════════════════════════════════════════════
2662
- # SECTION 16: GRADIO UI β€” COPY-SAFE DUAL POLLER
2663
  # ══════════════════════════════════════════════════════════════════════
2664
  CSS = """
2665
  body{background:#090909;color:#e0e0e0;font-family:monospace;}
@@ -2797,12 +2486,10 @@ def _reset_ans_cache(a_cache):
2797
  return a_cache
2798
 
2799
  # ── Gradio App ────────────────────────────────────────────────────────
2800
- with gr.Blocks(css=CSS, title="Practicality 27.1") as demo:
2801
  gr.Markdown(
2802
- "## βš— Practicality 27.1 β€” MINIMIZE Directive + Heisenberg Circuits\n"
2803
- "`[Direct Parser / LLM Encoder] -> [INT Grid] -> [Algebraic Propagator] -> "
2804
- "[Infeasibility Detector] -> [Range-Normalized Adam] -> [UCB1 Elastic] -> "
2805
- "[Heisenberg Observable Collapse]`"
2806
  )
2807
 
2808
  dash_cache = gr.State({"html": ""})
@@ -2849,30 +2536,21 @@ with gr.Blocks(css=CSS, title="Practicality 27.1") as demo:
2849
  value=(f"Compute: {DEVICE.type.upper()}\n"
2850
  f"Axioms: {len(ALL_AXIOMS)}\n"
2851
  f"Templates: {len(STRUCTURAL_HYPOTHESIS_TEMPLATES)}\n"
2852
- f"\n27.1 NEW:\n"
2853
- f" MINIMIZE Directive\n"
2854
- f" Soft objective in Adam tensor_energy\n"
2855
- f" Sorts INT grid combinatorial results\n"
2856
- f" Outputs specific optima (e.g. w=5)\n"
2857
- f"\n Heisenberg Actual Circuits:\n"
2858
- f" GHZ State Preparation (CNOT chain)\n"
2859
- f" TFIM Trotterized time-evolution step\n"
2860
- f" VQE E(theta) minimization\n"
2861
- f"\n Corrected Physics & Bounds:\n"
2862
- f" TFIM Mean-Field self-consistency\n"
2863
- f" Shor CNOT bounds exactly aligned\n"
2864
- f"\n UI Stability & Math Guardrails:\n"
2865
- f" safe_round() limits Inf/NaN overflow crashes\n"
2866
- f" PyTorch limits clamped at f32 bounds\n"
2867
- f"\n27.0 HERITAGE:\n"
2868
- f" Direct Template Parser (~1s startup)\n"
2869
- f" Range-Normalized Adam [0,1]\n"
2870
- f" INT Grid Hard Cap: {INT_GRID_MAX_COMBOS:,}\n"
2871
- f" Baton Eviction Max {BATON_REGISTRY_MAX:,}\n"
2872
- f" SymPy Process Isolation\n"
2873
- f" MAX_RAYS={MAX_RAYS_PER_ATTEMPT:,}\n"
2874
  f" MAX_CHAIN_DEPTH={MAX_CHAIN_DEPTH}"),
2875
- lines=50,interactive=False,elem_classes=["solver-log"])
2876
 
2877
  with gr.Row(elem_classes=["wrap-row"]):
2878
  with gr.Column(scale=1, min_width=300):
@@ -2898,15 +2576,15 @@ with gr.Blocks(css=CSS, title="Practicality 27.1") as demo:
2898
  outputs=[live_html,dash_cache,ans_cache],
2899
  js="""
2900
  function() {
2901
- if (!window._p270_dash) {
2902
- window._p270_dash = setInterval(() => {
2903
  const el = document.getElementById('dash_poll_btn');
2904
  if (!el) return;
2905
  (el.tagName === 'BUTTON' ? el : el.querySelector('button'))?.click();
2906
  }, 1000);
2907
  }
2908
- if (!window._p270_ans) {
2909
- window._p270_ans = setInterval(() => {
2910
  const el = document.getElementById('ans_poll_btn');
2911
  if (!el) return;
2912
  (el.tagName === 'BUTTON' ? el : el.querySelector('button'))?.click();
@@ -2944,15 +2622,13 @@ with gr.Blocks(css=CSS, title="Practicality 27.1") as demo:
2944
  outputs=[ans_cache])
2945
 
2946
  gr.Markdown(
2947
- f"Practicality 27.1 Β· MINIMIZE Directive Β· Corrected Templates Β· "
2948
- f"{len(STRUCTURAL_HYPOTHESIS_TEMPLATES)} templates loaded",
2949
  elem_classes=["status-bar"])
2950
 
2951
  if __name__ == "__main__":
2952
- print(f"[SYSTEM 27.1] Compute: {DEVICE.type.upper()} | Quantum={HAS_QUANTUM}")
2953
- print(f"[SYSTEM 27.1] Templates: {len(STRUCTURAL_HYPOTHESIS_TEMPLATES)}")
2954
- print(f"[SYSTEM 27.1] Direct parser active + MINIMIZE objective enabled")
2955
- print(f"[SYSTEM 27.1] MAX_RAYS={MAX_RAYS_PER_ATTEMPT:,} | MAX_CHAIN_DEPTH={MAX_CHAIN_DEPTH}")
2956
- print(f"[SYSTEM 27.1] INT_GRID_MAX_COMBOS={INT_GRID_MAX_COMBOS:,}")
2957
- print(f"[SYSTEM 27.1] Range-normalized Adam optimizer active")
2958
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
1
 
2
  #!/usr/bin/env python3
3
  """
4
+ PRACTICALITY SYSTEM 27.2 β€” THE RESTORED CORE & SAFE MINIMIZE
5
  ══════════════════════════════════════════════════════════════════════
6
+ REGRESSIONS FIXED FROM 27.1:
7
+
8
+ 1. THE DEPTH-0 BRANCHING FIX
9
+ Seed axioms unconditionally branch again. The ray queue no longer
10
+ drains prematurely at ~400 rays. Search trees fully expand.
11
+
12
+ 2. DYNAMIC BATON REGISTRY
13
+ The registry threshold dynamically scales with the problem's CE
14
+ (max(2.0, best_ce * 1.5, init_ce * 0.1)). High-CE spaces like GLV
15
+ will now successfully save intermediate recombinations.
16
+
17
+ 3. DECOUPLED MINIMIZE DIRECTIVE
18
+ The MINIMIZE penalty is strictly isolated to the Adam gradient
19
+ backward pass (is_optimizing=True). scalar_energy (Gate 1) evaluates
20
+ absolute structural truth (CE = 0), unpoisoned by soft objectives.
21
+
22
+ 4. FLOAT32 OVERFLOW SHIELD
23
+ t_func_raw now intercepts OverflowError natively. Astronomical
24
+ variables (e.g., 2^1000000 in GHZ) clamp to 1e38 instead of returning
25
+ Infinity and destroying the constraint graph.
26
+
27
+ 5. ADAM GRADIENT EXPLOSION
28
+ Reverted the X_n range-normalized Adam step back to original-space
29
+ evaluation. Prevents catastrophic boundary jumps in modular spaces.
30
+
31
+ HERITAGE MAINTAINED:
32
+ Direct template parser, INT grid permutations, Proxy Decomposition
33
+ (with proper short-circuit for connected graphs), SymPy anti-LaTeX shield.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  """
35
 
36
  import os, time, random, math, threading, warnings, json, textwrap, itertools, copy
 
61
  warnings.filterwarnings("ignore")
62
  USE_GPU = torch.cuda.is_available()
63
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
64
+ print(f"[SYSTEM 27.2] Compute: {DEVICE.type.upper()} | Restored Search Core")
65
 
66
  # ══════════════════════════════════════════════════════════════════════
67
  # SECTION 1: CONSTANTS & SAFE HELPERS
 
71
  VERIFY_G2_TOLERANCE = 1e-3
72
  DEDUCE_ADAM_STEPS = 80
73
  ADAM_LEARNING_RATE = 0.01
74
+ MINIMIZE_OBJECTIVE_WEIGHT = 0.05
75
  MAX_RAYS_PER_ATTEMPT = 24576 * 20
76
  RAY_BATCH_SIZE = 24576
77
  TEMPLATE_BATCH_SIZE = 2048
 
119
  "proxy_composed_ce": float('inf'),
120
  "fingerprint_summary": "", "propagation_log": [],
121
  "raw_results_json": "", "infeasibility_report": "",
122
+ "minimize_result": "",
123
  }
124
 
125
  FINGERPRINT_STORE: Dict[str, List[Dict]] = defaultdict(list)
 
321
  name:str; description:str; axioms:Set[str]; variables:List[Dict]; constraints:List[Dict]
322
  scopes:List[Dict]; anchors:List[AXLInvariant]; observations:Dict[str,float]=field(default_factory=dict)
323
  is_quantum:bool=False; circuit:Any=None
324
+ minimize_var:str=""
325
 
326
  class AXLtoPSLCompiler:
327
  def compile(self,prob:AXLProblemDef) -> str:
 
392
  if not rivs: return IV(-1e18,1e18)
393
  return IV(min(r.lo for r in rivs),max(r.hi for r in rivs))
394
  mc.fast_iv=_or_iv; return mc
395
+
396
  syms={v:sp.Symbol(v) for v in variables}
397
  try:
398
  parsed=parse_expr(expr_str,local_dict=syms) if kind!="or_eq" else None
 
410
  'sinh':torch.sinh,'cosh':torch.cosh,'tanh':torch.tanh,
411
  'pi':math.pi,'E':math.e}
412
  t_func_raw=sp.lambdify([sp.Symbol(v) for v in mc.syms_used],parsed,modules=[pt_map,"math"])
413
+
414
  def _t_wrapper(*args):
415
+ try:
416
+ val = t_func_raw(*args)
417
+ if not isinstance(val, torch.Tensor):
418
+ val = torch.tensor(float(val), device=DEVICE, dtype=torch.float32)
419
+ except Exception:
420
+ # Catch math.OverflowError natively (e.g. 2**1000000)
421
+ val = torch.tensor(1e38, device=DEVICE, dtype=torch.float32)
422
+ # Guarantee no posinf/neginf ruins the CE summation
423
+ return torch.nan_to_num(val, posinf=1e38, neginf=-1e38)
424
+
425
  mc.torch_func=_t_wrapper
426
  if kind=="equality":
427
  if expr_str not in PROJECTION_CACHE:
 
462
  ordering_pairs:List[Tuple[str,str]]=field(default_factory=list)
463
  is_quantum:bool=False; circuit:Any=None; quantum_vm:Any=None
464
  adjacency_list:Dict[str,Set[str]]=field(default_factory=lambda:defaultdict(set))
465
+ minimize_var:str=""
466
 
467
  def __post_init__(self):
468
  self.compiled_constraints=[
 
516
  if neighbor not in visited: visited.add(neighbor); queue.append((neighbor,d+1))
517
  return visited
518
 
519
+ def tensor_energy(self, X: torch.Tensor, step_ratio: float = 1.0, is_optimizing: bool = False) -> torch.Tensor:
 
520
  if self.is_quantum and self.quantum_vm:
521
  return self.quantum_vm.execute(X,step_ratio,DEVICE).view(-1)
522
  is_batched=(X.dim()==2); batch_size=X.shape[0] if is_batched else 1
 
546
  margin=(hi-lo)*0.1*(1.0-step_ratio)
547
  out_of_bounds=torch.relu(lo-margin-col)+torch.relu(col-(hi+margin))
548
  total+=(out_of_bounds**2)*10.0
549
+
550
+ # DECOUPLED MINIMIZE DIRECTIVE: Only inject penalty during gradient optimization
551
+ if is_optimizing and self.minimize_var and self.minimize_var in self.var_idx:
552
+ midx = self.var_idx[self.minimize_var]
553
+ lo,hi = _c38(self.bounds[self.minimize_var][0]), _c38(self.bounds[self.minimize_var][1])
554
+ rng = max(hi-lo, 1e-8)
555
+ col = X[:,midx] if is_batched else X[midx]
556
+ normalized = (col - lo) / rng
557
+ total += normalized * MINIMIZE_OBJECTIVE_WEIGHT * step_ratio
558
+
559
  return total.view(batch_size,-1).sum(dim=1)
560
 
561
+ def scalar_energy(self, b: Dict[str,float]) -> float:
562
  x_arr=[b.get(v,(_c38(self.bounds.get(v,(-1,1))[0])+_c38(self.bounds.get(v,(-1,1))[1]))/2) for v in self.variables]
563
  X_t=torch.tensor(x_arr,device=DEVICE,dtype=torch.float32).unsqueeze(0)
564
  with torch.no_grad():
565
+ # Gate 1 verification explicitly requires is_optimizing=False
566
+ return float(self.tensor_energy(X_t, step_ratio=1.0, is_optimizing=False).item())
567
 
568
  def build_base_problem(axl_def:AXLProblemDef) -> Problem:
569
  psl_text=AXL_COMPILER.compile(axl_def); prog=parse_psl(psl_text); ep=expand_psl(prog)
570
  prob=Problem(pid=f"base_{axl_def.name}",variables=ep.variables,constraints=ep.constraints,
571
  bounds=ep.bounds,int_vars=ep.int_vars,scope_groups=ep.scope_groups,
572
  scope_vars=ep.scope_vars,scope_order=ep.scope_order,
573
+ minimize_var=axl_def.minimize_var)
574
  if axl_def.is_quantum: prob.is_quantum=True; prob.circuit=axl_def.circuit; prob.__post_init__()
575
  return prob
576
 
 
743
  for v in problem.bounds if v in c}
744
 
745
  # ══════════════════════════════════════════════════════════════════════
746
+ # SECTION 5.10: DIRECT TEMPLATE PARSER
747
  # ══════════════════════════════════════════════════════════════════════
748
  _VAR_RE = re.compile(r'^\s*([a-zA-Z_][a-zA-Z0-9_]*(?:,\s*[a-zA-Z_][a-zA-Z0-9_]*)*)\s+in\s+\[([^\]]+)\]\s*(INT)?\s*',re.IGNORECASE)
749
  _CON_RE = re.compile(r'^\s*(EQ|GEQ|LEQ)(?:\s+weight\s*=\s*([0-9.]+))?\s*:\s*(.+)$',re.IGNORECASE)
 
1153
 
1154
  def run_proxy_decomposition(axl_def,base_problem):
1155
  components=find_markov_components(base_problem)
1156
+ if len(components)<=1:
1157
+ _add_log(" ↳ Graph is fully connected, skipping proxy decomp.")
1158
+ return {},float('inf'),[],False
1159
+
1160
  interfaces=find_interface_vars(components,base_problem)
1161
  _add_log(f"PROXY DECOMP: {len(components)} components | sizes {[len(c) for c in components]}")
1162
  _update_state(proxy_n_components=len(components))
 
1212
  return False,f"ATTRACTOR-STABLE: {len(good)} runs converged."
1213
 
1214
  # ══════════════════════════════════════════════════════════════════════
1215
+ # SECTION 6.7: HYPOTHESIS TEMPLATES
1216
  # ══════════════════════════════════════════════════════════════════════
1217
  STRUCTURAL_HYPOTHESIS_TEMPLATES = {
1218
 
1219
  "Heisenberg GHZ: N-Qubit Circuit Simulation": """\
1220
  CONCRETE HYPOTHESIS: GHZ State Preparation via Heisenberg Circuit Simulation
1221
  =============================================================================
1222
+ Variables:
1223
+ z_unif in [-0.1, 0.1]
1224
+ x0_after_H in [0.9, 1.1]
1225
+ zz_nn in [0.9, 1.1]
1226
+ zz_nnn in [0.9, 1.1]
1227
+ n_qubits in [2.0, 1000000.0]
1228
+ variables_used in [4.0, 4.0]
1229
+ schrodinger_dim in [4.0, 1e301]
1230
+ compression in [1.0, 1e301]
 
 
 
 
 
 
 
 
 
 
 
 
 
1231
 
1232
  Constraints:
1233
  EQ weight=10: z_unif
 
1243
  Anchor: zz_nn - 1.0 = 0 (tolerance 0.01).
1244
  Anchor: z_unif = 0 (tolerance 0.01).
1245
  Observation: n_qubits = 1000000.
 
 
 
 
 
 
 
 
 
 
1246
  """,
1247
 
1248
  "Heisenberg VQE: H2 Energy Minimization over Rotation Angle": """\
1249
  CONCRETE HYPOTHESIS: H2 Ground State via VQE Angle Optimization
1250
  ===============================================================
 
 
 
1251
  Variables:
1252
+ theta in [0.0, 6.28319]
1253
+ iz in [-1.0, 1.0]
1254
+ zi in [-1.0, 1.0]
1255
+ zz in [-1.1, -0.9]
1256
+ xx in [-1.0, 1.0]
1257
+ energy in [-1.15, -1.09]
1258
 
1259
  Constraints:
1260
  EQ weight=10: iz + cos(theta)
 
1276
  CONCRETE HYPOTHESIS: 1D TFIM Ferromagnetic Ground State via Mean-Field
1277
  ======================================================================
1278
  Variables:
1279
+ mag_z in [0.7, 1.0]
1280
+ mag_x in [0.3, 0.7]
1281
+ corr_zz in [0.5, 1.0]
1282
+ energy_per_site in [-1.2, -0.7]
1283
+ gap in [0.8, 1.2]
1284
 
1285
  Constraints:
1286
  EQ weight=10: mag_x**2*(mag_z**2 + 0.25) - 0.25
 
1295
  Anchor: energy_per_site + 1.0 = 0 (tolerance 0.05).
1296
  """,
1297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1298
  "secp256k1 Optimal Window: MINIMIZE total operations": """\
1299
  CONCRETE HYPOTHESIS: secp256k1 wNAF Optimal Window via Integer Minimization
1300
  ============================================================================
 
1344
  Observation: k_target = 314.
1345
  """,
1346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1347
  "1024-Qubit Shor: Concrete Full Gate Audit": """\
1348
  CONCRETE HYPOTHESIS: Shor RSA-1024 at 1024 Logical Qubits
1349
  ==========================================================
 
1368
 
1369
  Anchor: n_log_qubits - 1027 = 0 (tolerance 2.0).
1370
  Observation: n_bits = 512.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1371
  """
1372
  }
1373
 
1374
  # ══════════════════════════════════════════════════════════════════════
1375
+ # SECTION 7: MASKED DEDUCTION β€” ORIGINAL SPACE ADAM (RESTORED)
1376
  # ══════════════════════════════════════════════════════════════════════
1377
  @dataclass
1378
  class L9Certificate:
 
1399
  adam_hyps=[hyps[i] for i in solve_indices]
1400
  B=len(adam_hyps); V=len(problem.variables)
1401
 
1402
+ # RESTORED 24.11 ADAM BEHAVIOR: Original Space Evaluation (with _c38 clamps)
1403
+ x_data, mask_data, target_data = [], [], []
 
 
 
 
 
 
 
 
 
1404
  for hyp in adam_hyps:
1405
  xr, mr, tr = [], [], []
1406
  active_vars=problem.get_markov_blanket(set(hyp.pinned_vars.keys()), depth=2)
1407
  for j,v in enumerate(problem.variables):
1408
+ lo,hi=_c38(problem.bounds[v][0]),_c38(problem.bounds[v][1])
1409
  if v in hyp.pinned_vars:
1410
+ val=_c38(hyp.pinned_vars[v])
1411
+ xr.append(val); mr.append(0.0); tr.append(val)
1412
  else:
1413
+ val=_c38(hyp.binding.get(v,(lo+hi)/2))
1414
  is_active=(v in active_vars) or (len(hyp.pinned_vars)==0)
1415
+ xr.append(val); mr.append(1.0 if is_active else 0.0); tr.append(0.0)
1416
+ x_data.append(xr); mask_data.append(mr); target_data.append(tr)
1417
 
1418
+ X = torch.tensor(x_data, device=DEVICE, dtype=torch.float32, requires_grad=True)
1419
+ mask = torch.tensor(mask_data, device=DEVICE, dtype=torch.float32)
1420
+ target = torch.tensor(target_data, device=DEVICE, dtype=torch.float32)
1421
 
1422
+ optimizer = torch.optim.Adam([X], lr=ADAM_LEARNING_RATE)
1423
 
1424
  for step in range(DEDUCE_ADAM_STEPS):
1425
  optimizer.zero_grad()
1426
  step_ratio = min(1.0, step / (DEDUCE_ADAM_STEPS * 0.8))
1427
+
1428
+ # DECOUPLED MINIMIZE FIX: Apply soft objective strictly in optimization loop
1429
+ ce = problem.tensor_energy(X, step_ratio, is_optimizing=True)
1430
+
1431
  if isinstance(ce, torch.Tensor) and (ce < SOLVE_THRESHOLD).all() and step_ratio == 1.0:
1432
  break
1433
  ce.sum().backward()
1434
+
1435
  with torch.no_grad():
1436
+ X.grad.clamp_(-10.0, 10.0)
1437
+ X.grad *= mask
1438
  optimizer.step()
1439
+ X.data = torch.where(mask == 0.0, target, X.data)
1440
+ for j, v in enumerate(problem.variables):
1441
+ lo, hi = _c38(problem.bounds[v][0]), _c38(problem.bounds[v][1])
1442
+ margin = (hi - lo) * 0.1 * (1.0 - step_ratio)
1443
+ X.data[:, j] = torch.clamp(X.data[:, j], lo - margin, hi + margin)
1444
 
1445
  optimizer.zero_grad()
1446
+ # Evaluate final energy WITHOUT optimization penalties for accurate verification
1447
+ final_ce = problem.tensor_energy(X, 1.0, is_optimizing=False).view(-1)
1448
  final_ce.sum().backward()
1449
+
1450
  ce_vals = final_ce.detach().cpu().numpy()
1451
+ X_vals = X.detach().cpu().numpy()
1452
+ grads_abs = X.grad.abs()
1453
  _, topk_idx = torch.topk(grads_abs, k=min(3,V), dim=1)
1454
  topk_idx_np = topk_idx.cpu().numpy()
1455
  grads_np = grads_abs.cpu().numpy()
 
1465
 
1466
  def _mprt_sample(problem, work_box, N):
1467
  var_list=problem.variables; V=len(var_list)
 
1468
  lo_t=torch.tensor([_c38(max(problem.bounds.get(v,(-10.0,10.0))[0], work_box[v].lo if v in work_box else problem.bounds.get(v,(-10,10))[0])) for v in var_list], device=DEVICE, dtype=torch.float32)
1469
  hi_t=torch.tensor([_c38(min(problem.bounds.get(v,(-10.0,10.0))[1], work_box[v].hi if v in work_box else problem.bounds.get(v,(-10,10))[1])) for v in var_list], device=DEVICE, dtype=torch.float32)
1470
  for i in range(V):
1471
  if lo_t[i]>=hi_t[i]: m=(lo_t[i]+hi_t[i])/2; lo_t[i]=m-1e-6; hi_t[i]=m+1e-6
1472
  X=lo_t.unsqueeze(0)+(hi_t-lo_t).unsqueeze(0)*torch.rand((N,V), device=DEVICE)
1473
+ ce_batch=problem.tensor_energy(X,1.0,is_optimizing=False).view(-1); best_idx=torch.argmin(ce_batch).item()
1474
  return {v:float(X[best_idx,i].item()) for i,v in enumerate(var_list)}, ce_batch[best_idx].item()
1475
 
1476
  # ══════════════════════════════════════════════════════════════════════
 
1864
  return g1_pass, all(v[1] for v in g2.values()) if g2 else True, g2, safe_round(g1_ce,6)
1865
 
1866
  # ══════════════════════════════════════════════════════════════════════
1867
+ # SECTION 13: SEQUENCE RAY TRACER
1868
  # ══════════════════════════════════════════════════════════════════════
1869
  class SequenceRayTracer:
1870
  def trace(self, axl_def, base_problem, use_proxy_decomp=True):
 
1982
  bandit.record_reward(ray.sequence[-1],parent_ce,final_ce)
1983
  g1_pass,g2_pass,inv_results,_=_verify(final_b,base_problem,axl_def.anchors)
1984
  improved=final_ce<best_ce; passed_pruning=final_ce<parent_ce*CE_EARN_RATIO
1985
+
1986
  if improved or (g1_pass and g2_pass) or passed_pruning:
1987
  with STATE_LOCK:
1988
  GLOBAL_SOLVE_STATE["recent_traces"].append(HypothesisTrace(
 
1991
  survived=(g1_pass and g2_pass),elapsed_ms=0.0,
1992
  g1_pass=g1_pass,g2_pass=g2_pass,binding=final_b,
1993
  invariant_results=inv_results,tension_class=tension_class,depth=ray.depth))
1994
+
1995
  out_baton=Baton(binding=final_b,ce=final_ce,ray_id=ray.ray_id,
1996
  l9=L9Certificate(final_ce,dom_vars,[],tension_class))
1997
+
1998
+ # DYNAMIC BATON THRESHOLD FIX: Ensure states are saved relative to the current progress
1999
+ dynamic_baton_thresh = max(BATON_REGISTRY_THRESHOLD, best_ce * 1.5, init_ce * 0.1)
2000
+ if final_ce < dynamic_baton_thresh:
2001
+ baton_registry[ray.ray_id] = out_baton
2002
+ if len(baton_registry) > BATON_REGISTRY_MAX:
2003
+ worst_key = max(baton_registry, key=lambda k: baton_registry[k].ce)
2004
  del baton_registry[worst_key]
2005
+
2006
  if improved:
2007
  best_ce=final_ce; best_binding=dict(final_b)
2008
  model.best_ray=ray.name; best_ray_name=ray.name
2009
  if g1_pass and g2_pass and final_ce<SOLVE_THRESHOLD: solved=True
2010
+
2011
+ # DEPTH-0 BRANCHING FIX: Restore unconditional seed expansion (ray.depth < 1)
2012
+ if (passed_pruning or improved or ray.depth < 1) and ray.depth < MAX_CHAIN_DEPTH:
2013
  remaining=[a for a in ALL_AXIOMS if a not in ray.sequence]
2014
  queues["core"].extend(bandit.intelligent_branch(ray,out_baton,remaining,BRANCH_WIDTH,sketch))
2015
 
 
2067
  RULES: USE ** FOR EXPONENTS. NEVER USE ^. No =, >=, <= inside expressions.
2068
  EQ/GEQ/LEQ are expression's relation to zero. Output ONLY the JSON object."""
2069
 
2070
+ COLLAPSER_SYSTEM_PROMPT = """You are the Grounded Hypothesis Engine for Practicality 27.2.
2071
 
2072
  Check infeasibility_report first. If non-empty: the system proved infeasibility via
2073
  algebraic propagation before firing any rays. Output:
 
2348
  daemon=True).start()
2349
 
2350
  # ══════════════════════════════════════════════════════════════════════
2351
+ # SECTION 16: GRADIO UI
2352
  # ══════════════════════════════════════════════════════════════════════
2353
  CSS = """
2354
  body{background:#090909;color:#e0e0e0;font-family:monospace;}
 
2486
  return a_cache
2487
 
2488
  # ── Gradio App ────────────────────────────────────────────────────────
2489
+ with gr.Blocks(css=CSS, title="Practicality 27.2") as demo:
2490
  gr.Markdown(
2491
+ "## βš— Practicality 27.2 β€” The Restored Core & Safe Minimize\n"
2492
+ "`[Direct Parser] -> [INT Grid] -> [Infeasibility Detector] -> [Original Space Adam] -> [Tree Re-expansion]`"
 
 
2493
  )
2494
 
2495
  dash_cache = gr.State({"html": ""})
 
2536
  value=(f"Compute: {DEVICE.type.upper()}\n"
2537
  f"Axioms: {len(ALL_AXIOMS)}\n"
2538
  f"Templates: {len(STRUCTURAL_HYPOTHESIS_TEMPLATES)}\n"
2539
+ f"\n27.2 RESTORATION FIXES:\n"
2540
+ f" βœ“ RESTORED: ray.depth < 1 unconditional branching.\n"
2541
+ f" (The queue no longer drains at ~400 rays).\n"
2542
+ f" βœ“ DYNAMIC: Baton Registry tracks best_ce properly.\n"
2543
+ f" βœ“ DECOUPLED: MINIMIZE directive removed from CE verify.\n"
2544
+ f" βœ“ SHIELDED: Float32 max overflow native handler.\n"
2545
+ f" βœ“ STABLE: Range-normalized Adam reverted to orig space.\n"
2546
+ f"\n27.1 FEATURES RETAINED:\n"
2547
+ f" MINIMIZE Soft Objectives (safely isolated)\n"
2548
+ f" INT Grid Combinatorics\n"
2549
+ f" Algebraic Feasibility Scanner\n"
2550
+ f" Proxy Decomposition (w/ full graph skip)\n"
2551
+ f"\n MAX_RAYS={MAX_RAYS_PER_ATTEMPT:,}\n"
 
 
 
 
 
 
 
 
 
2552
  f" MAX_CHAIN_DEPTH={MAX_CHAIN_DEPTH}"),
2553
+ lines=35,interactive=False,elem_classes=["solver-log"])
2554
 
2555
  with gr.Row(elem_classes=["wrap-row"]):
2556
  with gr.Column(scale=1, min_width=300):
 
2576
  outputs=[live_html,dash_cache,ans_cache],
2577
  js="""
2578
  function() {
2579
+ if (!window._p272_dash) {
2580
+ window._p272_dash = setInterval(() => {
2581
  const el = document.getElementById('dash_poll_btn');
2582
  if (!el) return;
2583
  (el.tagName === 'BUTTON' ? el : el.querySelector('button'))?.click();
2584
  }, 1000);
2585
  }
2586
+ if (!window._p272_ans) {
2587
+ window._p272_ans = setInterval(() => {
2588
  const el = document.getElementById('ans_poll_btn');
2589
  if (!el) return;
2590
  (el.tagName === 'BUTTON' ? el : el.querySelector('button'))?.click();
 
2622
  outputs=[ans_cache])
2623
 
2624
  gr.Markdown(
2625
+ f"Practicality 27.2 Β· Search Re-Expanded Β· Float32 Overflow Protected",
 
2626
  elem_classes=["status-bar"])
2627
 
2628
  if __name__ == "__main__":
2629
+ print(f"[SYSTEM 27.2] Compute: {DEVICE.type.upper()} | Quantum={HAS_QUANTUM}")
2630
+ print(f"[SYSTEM 27.2] Templates: {len(STRUCTURAL_HYPOTHESIS_TEMPLATES)}")
2631
+ print(f"[SYSTEM 27.2] Fixes: Depth-0 Branching, Dynamic Baton Threshold, Decoupled MINIMIZE")
2632
+ print(f"[SYSTEM 27.2] Fixes: Float32 Exponent Overflow Native Shield")
2633
+ print(f"[SYSTEM 27.2] Adam logic: Reverted to Original Space bounds tracking")
 
2634
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)