everydaytok commited on
Commit
d052d73
Β·
verified Β·
1 Parent(s): d521875

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -48
app.py CHANGED
@@ -1,23 +1,23 @@
1
  #!/usr/bin/env python3
2
  """
3
- PRACTICALITY SYSTEM 27.3 β€” THE FAIL-FAST RESTORATION
4
  ══════════════════════════════════════════════════════════════════════
5
- REGRESSIONS FIXED FROM 27.2:
6
-
7
- 1. REMOVED LLM AUTO-RETRY LOOP (The "Endless Looping" Bug)
8
- The system now operates on a strict One-Shot paradigm. If the ray
9
- budget is exhausted (even if Gate 2 fails), it immediately collapses
10
- and returns the JSON/Markdown to the user for manual recalibration.
11
-
12
- 2. EARLY STOPPING CLARITY
13
- The system will only short-circuit if CE < SOLVE_THRESHOLD AND Gate 2
14
- (Anchors) pass. If an anchor is mathematically malformed (returns 999.0),
15
- it will exhaust the search budget trying to satisfy it, then fail-fast
16
- and report.
17
 
18
  HERITAGE MAINTAINED:
19
  All 17 domain templates. Original-Space Adam. Depth-0 Ray Expansion.
20
- Dynamic Baton Registry. Float32 Overflow Shield. Decoupled MINIMIZE.
21
  """
22
 
23
  import os, time, random, math, threading, warnings, json, textwrap, itertools, copy
@@ -48,7 +48,7 @@ GEMINI_MODEL = "gemini-3.5-flash"
48
  warnings.filterwarnings("ignore")
49
  USE_GPU = torch.cuda.is_available()
50
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
51
- print(f"[SYSTEM 27.3] Compute: {DEVICE.type.upper()} | Fail-Fast Core Active")
52
 
53
  # ══════════════════════════════════════════════════════════════════════
54
  # SECTION 1: CONSTANTS & SAFE HELPERS
@@ -83,10 +83,11 @@ def safe_round(val, ndigits=8):
83
  return round(val, ndigits)
84
  except: return val
85
 
86
- def _c38(v):
 
87
  try:
88
- if not math.isfinite(v): return 1e38 if v > 0 else -1e38
89
- return max(-1e38, min(1e38, float(v)))
90
  except: return 0.0
91
 
92
  # ══════════════════════════════════════════════════════════════════════
@@ -403,8 +404,9 @@ def compile_mc(kind,expr_str,direction,variables,weight=1.0,scope="root",branche
403
  if not isinstance(val, torch.Tensor):
404
  val = torch.tensor(float(val), device=DEVICE, dtype=torch.float32)
405
  except Exception:
406
- val = torch.tensor(1e38, device=DEVICE, dtype=torch.float32)
407
- return torch.nan_to_num(val, posinf=1e38, neginf=-1e38)
 
408
 
409
  mc.torch_func=_t_wrapper
410
  if kind=="equality":
@@ -525,16 +527,15 @@ class Problem:
525
  elif mc.direction=="geq": total+=(torch.relu(-val)**2)*eff_weight
526
  else: total+=(torch.relu(val)**2)*eff_weight
527
  for i,v in enumerate(self.variables):
528
- lo,hi=_c38(self.bounds[v][0]),_c38(self.bounds[v][1])
529
  col=X[:,i] if is_batched else X[i]
530
  margin=(hi-lo)*0.1*(1.0-step_ratio)
531
  out_of_bounds=torch.relu(lo-margin-col)+torch.relu(col-(hi+margin))
532
  total+=(out_of_bounds**2)*10.0
533
 
534
- # DECOUPLED MINIMIZE DIRECTIVE
535
  if is_optimizing and self.minimize_var and self.minimize_var in self.var_idx:
536
  midx = self.var_idx[self.minimize_var]
537
- lo,hi = _c38(self.bounds[self.minimize_var][0]), _c38(self.bounds[self.minimize_var][1])
538
  rng = max(hi-lo, 1e-8)
539
  col = X[:,midx] if is_batched else X[midx]
540
  normalized = (col - lo) / rng
@@ -543,7 +544,7 @@ class Problem:
543
  return total.view(batch_size,-1).sum(dim=1)
544
 
545
  def scalar_energy(self, b: Dict[str,float]) -> float:
546
- 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]
547
  X_t=torch.tensor(x_arr,device=DEVICE,dtype=torch.float32).unsqueeze(0)
548
  with torch.no_grad():
549
  return float(self.tensor_energy(X_t, step_ratio=1.0, is_optimizing=False).item())
@@ -1639,7 +1640,7 @@ Anchor: xx01 - 1 = 0 (tolerance 0.01).
1639
  }
1640
 
1641
  # ══════════════════════════════════════════════════════════════════════
1642
- # SECTION 7: MASKED DEDUCTION β€” ORIGINAL SPACE ADAM (RESTORED)
1643
  # ══════════════════════════════════════════════════════════════════════
1644
  @dataclass
1645
  class L9Certificate:
@@ -1666,18 +1667,17 @@ def _batched_deduce_and_evaluate(problem, hyps: List['Hypothesis']) -> List[Tupl
1666
  adam_hyps=[hyps[i] for i in solve_indices]
1667
  B=len(adam_hyps); V=len(problem.variables)
1668
 
1669
- # RESTORED 24.11 ADAM BEHAVIOR: Original Space Evaluation (with _c38 clamps)
1670
  x_data, mask_data, target_data = [], [], []
1671
  for hyp in adam_hyps:
1672
  xr, mr, tr = [], [], []
1673
  active_vars=problem.get_markov_blanket(set(hyp.pinned_vars.keys()), depth=2)
1674
  for j,v in enumerate(problem.variables):
1675
- lo,hi=_c38(problem.bounds[v][0]),_c38(problem.bounds[v][1])
1676
  if v in hyp.pinned_vars:
1677
- val=_c38(hyp.pinned_vars[v])
1678
  xr.append(val); mr.append(0.0); tr.append(val)
1679
  else:
1680
- val=_c38(hyp.binding.get(v,(lo+hi)/2))
1681
  is_active=(v in active_vars) or (len(hyp.pinned_vars)==0)
1682
  xr.append(val); mr.append(1.0 if is_active else 0.0); tr.append(0.0)
1683
  x_data.append(xr); mask_data.append(mr); target_data.append(tr)
@@ -1703,7 +1703,7 @@ def _batched_deduce_and_evaluate(problem, hyps: List['Hypothesis']) -> List[Tupl
1703
  optimizer.step()
1704
  X.data = torch.where(mask == 0.0, target, X.data)
1705
  for j, v in enumerate(problem.variables):
1706
- lo, hi = _c38(problem.bounds[v][0]), _c38(problem.bounds[v][1])
1707
  margin = (hi - lo) * 0.1 * (1.0 - step_ratio)
1708
  X.data[:, j] = torch.clamp(X.data[:, j], lo - margin, hi + margin)
1709
 
@@ -1729,8 +1729,8 @@ def _batched_deduce_and_evaluate(problem, hyps: List['Hypothesis']) -> List[Tupl
1729
 
1730
  def _mprt_sample(problem, work_box, N):
1731
  var_list=problem.variables; V=len(var_list)
1732
- 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)
1733
- 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)
1734
  for i in range(V):
1735
  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
1736
  X=lo_t.unsqueeze(0)+(hi_t-lo_t).unsqueeze(0)*torch.rand((N,V), device=DEVICE)
@@ -2185,7 +2185,6 @@ class SequenceRayTracer:
2185
  best_ce=final_ce; best_binding=dict(final_b)
2186
  model.best_ray=ray.name; best_ray_name=ray.name
2187
 
2188
- # STRICT EARLY EXIT: If CE is perfect AND anchors pass, stop everything.
2189
  if g1_pass and g2_pass and final_ce<SOLVE_THRESHOLD: solved=True
2190
 
2191
  if (passed_pruning or improved or ray.depth < 1) and ray.depth < MAX_CHAIN_DEPTH:
@@ -2246,7 +2245,7 @@ OUTPUT SCHEMA (JSON only, no markdown):
2246
  RULES: USE ** FOR EXPONENTS. NEVER USE ^. No =, >=, <= inside expressions.
2247
  EQ/GEQ/LEQ are expression's relation to zero. Output ONLY the JSON object."""
2248
 
2249
- COLLAPSER_SYSTEM_PROMPT = """You are the Grounded Hypothesis Engine for Practicality 27.3.
2250
 
2251
  Check infeasibility_report first. If non-empty: the system proved infeasibility via
2252
  algebraic propagation before firing any rays. Output:
@@ -2652,9 +2651,9 @@ def _reset_ans_cache(a_cache):
2652
  return a_cache
2653
 
2654
  # ── Gradio App ────────────────────────────────────────────────────────
2655
- with gr.Blocks(css=CSS, title="Practicality 27.3") as demo:
2656
  gr.Markdown(
2657
- "## βš— Practicality 27.3 β€” The Fail-Fast Core\n"
2658
  "`[Direct Parser / LLM] -> [INT Grid] -> [Orig Space Adam] -> [No Retry Loops β€” Manual Recalibration]`"
2659
  )
2660
 
@@ -2702,16 +2701,15 @@ with gr.Blocks(css=CSS, title="Practicality 27.3") as demo:
2702
  value=(f"Compute: {DEVICE.type.upper()}\n"
2703
  f"Axioms: {len(ALL_AXIOMS)}\n"
2704
  f"Templates: {len(STRUCTURAL_HYPOTHESIS_TEMPLATES)}\n"
2705
- f"\n27.3 UPDATES (Fail-Fast Paradigm):\n"
 
 
2706
  f" βœ“ REMOVED auto-retry loop entirely.\n"
2707
  f" βœ“ Stops 'looping from the beginning'.\n"
2708
- f" βœ“ CE=0 with Anchor=999 correctly explores, \n"
2709
- f" then fails fast to show broken constraint.\n"
2710
  f" βœ“ All 17 templates fully restored.\n"
2711
  f"\n27.2 FEATURES RETAINED:\n"
2712
  f" ray.depth < 1 unconditional branching.\n"
2713
  f" MINIMIZE Soft Objectives (isolated)\n"
2714
- f" Float32 max overflow native handler.\n"
2715
  f" Range-normalized Adam reverted to orig space.\n"
2716
  f"\n MAX_RAYS={MAX_RAYS_PER_ATTEMPT:,}\n"
2717
  f" MAX_CHAIN_DEPTH={MAX_CHAIN_DEPTH}"),
@@ -2741,15 +2739,15 @@ with gr.Blocks(css=CSS, title="Practicality 27.3") as demo:
2741
  outputs=[live_html,dash_cache,ans_cache],
2742
  js="""
2743
  function() {
2744
- if (!window._p273_dash) {
2745
- window._p273_dash = setInterval(() => {
2746
  const el = document.getElementById('dash_poll_btn');
2747
  if (!el) return;
2748
  (el.tagName === 'BUTTON' ? el : el.querySelector('button'))?.click();
2749
  }, 1000);
2750
  }
2751
- if (!window._p273_ans) {
2752
- window._p273_ans = setInterval(() => {
2753
  const el = document.getElementById('ans_poll_btn');
2754
  if (!el) return;
2755
  (el.tagName === 'BUTTON' ? el : el.querySelector('button'))?.click();
@@ -2787,11 +2785,11 @@ with gr.Blocks(css=CSS, title="Practicality 27.3") as demo:
2787
  outputs=[ans_cache])
2788
 
2789
  gr.Markdown(
2790
- f"Practicality 27.3 Β· Strict One-Shot Paradigm Β· Fail-Fast Core",
2791
  elem_classes=["status-bar"])
2792
 
2793
  if __name__ == "__main__":
2794
- print(f"[SYSTEM 27.3] Compute: {DEVICE.type.upper()} | Quantum={HAS_QUANTUM}")
2795
- print(f"[SYSTEM 27.3] Templates: {len(STRUCTURAL_HYPOTHESIS_TEMPLATES)}")
2796
- print(f"[SYSTEM 27.3] Fixes: Removed LLM auto-retry endless loop.")
2797
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
1
  #!/usr/bin/env python3
2
  """
3
+ PRACTICALITY SYSTEM 27.4 β€” THE FAIL-FAST CORE & L2 OVERFLOW SHIELD
4
  ══════════════════════════════════════════════════════════════════════
5
+ REGRESSIONS FIXED FROM 27.3:
6
+
7
+ 1. THE L2 LOSS OVERFLOW SHIELD (1e38 -> 1e15)
8
+ PyTorch calculates Constraint Energy by squaring residuals (MSE).
9
+ Clamping float32 limits to 1e38 caused the square to hit 1e76,
10
+ which natively overflowed to Infinity, destroying the landscape.
11
+ The clamp is now safely set to 1e15 (square = 1e30).
12
+
13
+ 2. FAIL-FAST PARADIGM ENFORCED
14
+ The LLM auto-retry loop is completely removed. If the geometric
15
+ budget is exhausted, the system immediately collapses and reports
16
+ the broken anchor/constraint for manual recalibration.
17
 
18
  HERITAGE MAINTAINED:
19
  All 17 domain templates. Original-Space Adam. Depth-0 Ray Expansion.
20
+ Dynamic Baton Registry. Decoupled MINIMIZE. Proxy Decomposition.
21
  """
22
 
23
  import os, time, random, math, threading, warnings, json, textwrap, itertools, copy
 
48
  warnings.filterwarnings("ignore")
49
  USE_GPU = torch.cuda.is_available()
50
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
51
+ print(f"[SYSTEM 27.4] Compute: {DEVICE.type.upper()} | Fail-Fast + L2 Shield")
52
 
53
  # ══════════════════════════════════════════════════════════════════════
54
  # SECTION 1: CONSTANTS & SAFE HELPERS
 
83
  return round(val, ndigits)
84
  except: return val
85
 
86
+ def _c15(v):
87
+ """Clamps floats to 1e15 so PyTorch MSE squaring doesn't trigger inf."""
88
  try:
89
+ if not math.isfinite(v): return 1e15 if v > 0 else -1e15
90
+ return max(-1e15, min(1e15, float(v)))
91
  except: return 0.0
92
 
93
  # ══════════════════════════════════════════════════════════════════════
 
404
  if not isinstance(val, torch.Tensor):
405
  val = torch.tensor(float(val), device=DEVICE, dtype=torch.float32)
406
  except Exception:
407
+ # Shield: Catch float32 overflow natively and clamp to 1e15
408
+ val = torch.tensor(1e15, device=DEVICE, dtype=torch.float32)
409
+ return torch.nan_to_num(val, posinf=1e15, neginf=-1e15)
410
 
411
  mc.torch_func=_t_wrapper
412
  if kind=="equality":
 
527
  elif mc.direction=="geq": total+=(torch.relu(-val)**2)*eff_weight
528
  else: total+=(torch.relu(val)**2)*eff_weight
529
  for i,v in enumerate(self.variables):
530
+ lo,hi=_c15(self.bounds[v][0]),_c15(self.bounds[v][1])
531
  col=X[:,i] if is_batched else X[i]
532
  margin=(hi-lo)*0.1*(1.0-step_ratio)
533
  out_of_bounds=torch.relu(lo-margin-col)+torch.relu(col-(hi+margin))
534
  total+=(out_of_bounds**2)*10.0
535
 
 
536
  if is_optimizing and self.minimize_var and self.minimize_var in self.var_idx:
537
  midx = self.var_idx[self.minimize_var]
538
+ lo,hi = _c15(self.bounds[self.minimize_var][0]), _c15(self.bounds[self.minimize_var][1])
539
  rng = max(hi-lo, 1e-8)
540
  col = X[:,midx] if is_batched else X[midx]
541
  normalized = (col - lo) / rng
 
544
  return total.view(batch_size,-1).sum(dim=1)
545
 
546
  def scalar_energy(self, b: Dict[str,float]) -> float:
547
+ x_arr=[b.get(v,(_c15(self.bounds.get(v,(-1,1))[0])+_c15(self.bounds.get(v,(-1,1))[1]))/2) for v in self.variables]
548
  X_t=torch.tensor(x_arr,device=DEVICE,dtype=torch.float32).unsqueeze(0)
549
  with torch.no_grad():
550
  return float(self.tensor_energy(X_t, step_ratio=1.0, is_optimizing=False).item())
 
1640
  }
1641
 
1642
  # ══════════════════════════════════════════════════════════════════════
1643
+ # SECTION 7: MASKED DEDUCTION β€” ORIGINAL SPACE ADAM
1644
  # ══════════════════════════════════════════════════════════════════════
1645
  @dataclass
1646
  class L9Certificate:
 
1667
  adam_hyps=[hyps[i] for i in solve_indices]
1668
  B=len(adam_hyps); V=len(problem.variables)
1669
 
 
1670
  x_data, mask_data, target_data = [], [], []
1671
  for hyp in adam_hyps:
1672
  xr, mr, tr = [], [], []
1673
  active_vars=problem.get_markov_blanket(set(hyp.pinned_vars.keys()), depth=2)
1674
  for j,v in enumerate(problem.variables):
1675
+ lo,hi=_c15(problem.bounds[v][0]),_c15(problem.bounds[v][1])
1676
  if v in hyp.pinned_vars:
1677
+ val=_c15(hyp.pinned_vars[v])
1678
  xr.append(val); mr.append(0.0); tr.append(val)
1679
  else:
1680
+ val=_c15(hyp.binding.get(v,(lo+hi)/2))
1681
  is_active=(v in active_vars) or (len(hyp.pinned_vars)==0)
1682
  xr.append(val); mr.append(1.0 if is_active else 0.0); tr.append(0.0)
1683
  x_data.append(xr); mask_data.append(mr); target_data.append(tr)
 
1703
  optimizer.step()
1704
  X.data = torch.where(mask == 0.0, target, X.data)
1705
  for j, v in enumerate(problem.variables):
1706
+ lo, hi = _c15(problem.bounds[v][0]), _c15(problem.bounds[v][1])
1707
  margin = (hi - lo) * 0.1 * (1.0 - step_ratio)
1708
  X.data[:, j] = torch.clamp(X.data[:, j], lo - margin, hi + margin)
1709
 
 
1729
 
1730
  def _mprt_sample(problem, work_box, N):
1731
  var_list=problem.variables; V=len(var_list)
1732
+ lo_t=torch.tensor([_c15(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)
1733
+ hi_t=torch.tensor([_c15(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)
1734
  for i in range(V):
1735
  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
1736
  X=lo_t.unsqueeze(0)+(hi_t-lo_t).unsqueeze(0)*torch.rand((N,V), device=DEVICE)
 
2185
  best_ce=final_ce; best_binding=dict(final_b)
2186
  model.best_ray=ray.name; best_ray_name=ray.name
2187
 
 
2188
  if g1_pass and g2_pass and final_ce<SOLVE_THRESHOLD: solved=True
2189
 
2190
  if (passed_pruning or improved or ray.depth < 1) and ray.depth < MAX_CHAIN_DEPTH:
 
2245
  RULES: USE ** FOR EXPONENTS. NEVER USE ^. No =, >=, <= inside expressions.
2246
  EQ/GEQ/LEQ are expression's relation to zero. Output ONLY the JSON object."""
2247
 
2248
+ COLLAPSER_SYSTEM_PROMPT = """You are the Grounded Hypothesis Engine for Practicality 27.4.
2249
 
2250
  Check infeasibility_report first. If non-empty: the system proved infeasibility via
2251
  algebraic propagation before firing any rays. Output:
 
2651
  return a_cache
2652
 
2653
  # ── Gradio App ────────────────────────────────────────────────────────
2654
+ with gr.Blocks(css=CSS, title="Practicality 27.4") as demo:
2655
  gr.Markdown(
2656
+ "## βš— Practicality 27.4 β€” The Fail-Fast Core\n"
2657
  "`[Direct Parser / LLM] -> [INT Grid] -> [Orig Space Adam] -> [No Retry Loops β€” Manual Recalibration]`"
2658
  )
2659
 
 
2701
  value=(f"Compute: {DEVICE.type.upper()}\n"
2702
  f"Axioms: {len(ALL_AXIOMS)}\n"
2703
  f"Templates: {len(STRUCTURAL_HYPOTHESIS_TEMPLATES)}\n"
2704
+ f"\n27.4 UPDATES (Fail-Fast Paradigm):\n"
2705
+ f" βœ“ L2 LOSS SHIELD: _c15 safely bounds PyTorch MSE\n"
2706
+ f" to prevent 1e76 Infinity explosions.\n"
2707
  f" βœ“ REMOVED auto-retry loop entirely.\n"
2708
  f" βœ“ Stops 'looping from the beginning'.\n"
 
 
2709
  f" βœ“ All 17 templates fully restored.\n"
2710
  f"\n27.2 FEATURES RETAINED:\n"
2711
  f" ray.depth < 1 unconditional branching.\n"
2712
  f" MINIMIZE Soft Objectives (isolated)\n"
 
2713
  f" Range-normalized Adam reverted to orig space.\n"
2714
  f"\n MAX_RAYS={MAX_RAYS_PER_ATTEMPT:,}\n"
2715
  f" MAX_CHAIN_DEPTH={MAX_CHAIN_DEPTH}"),
 
2739
  outputs=[live_html,dash_cache,ans_cache],
2740
  js="""
2741
  function() {
2742
+ if (!window._p274_dash) {
2743
+ window._p274_dash = setInterval(() => {
2744
  const el = document.getElementById('dash_poll_btn');
2745
  if (!el) return;
2746
  (el.tagName === 'BUTTON' ? el : el.querySelector('button'))?.click();
2747
  }, 1000);
2748
  }
2749
+ if (!window._p274_ans) {
2750
+ window._p274_ans = setInterval(() => {
2751
  const el = document.getElementById('ans_poll_btn');
2752
  if (!el) return;
2753
  (el.tagName === 'BUTTON' ? el : el.querySelector('button'))?.click();
 
2785
  outputs=[ans_cache])
2786
 
2787
  gr.Markdown(
2788
+ f"Practicality 27.4 Β· Strict One-Shot Paradigm Β· 1e15 Shield",
2789
  elem_classes=["status-bar"])
2790
 
2791
  if __name__ == "__main__":
2792
+ print(f"[SYSTEM 27.4] Compute: {DEVICE.type.upper()} | Quantum={HAS_QUANTUM}")
2793
+ print(f"[SYSTEM 27.4] Templates: {len(STRUCTURAL_HYPOTHESIS_TEMPLATES)}")
2794
+ print(f"[SYSTEM 27.4] Fixes: 1e15 L2 loss overflow shield active.")
2795
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)