everydaytok commited on
Commit
192a7aa
Β·
verified Β·
1 Parent(s): 157c441

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -74
app.py CHANGED
@@ -1,6 +1,6 @@
1
  #!/usr/bin/env python3
2
  """
3
- PRACTICALITY SYSTEM 15.5 β€” PARALLEL BEAM SEARCH (IMAGINARY LINES)
4
  ═══════════════════════════════════════════════════════════════════
5
  SYSTEM SUMMARY:
6
  This is a set-based axiomatic ray tracer designed to deduce the
@@ -21,12 +21,17 @@ through four distinct layers:
21
  manifold tangents, asymmetric splits).
22
  4. VERIFY LAYER: A rigid binary oracle testing the true Base problem.
23
 
24
- NEW IN 15.5 (Parallel Beam Search / Imaginary Lines):
25
- Β· The Hypothesis Generator now evaluates multiple competing
26
- techniques spawned by an axiom simultaneously across parallel
27
- threads. The best trajectory survives and updates the chain,
28
- instantly despawning the rest, drastically increasing the speed
29
- and efficiency of the microscopic search.
 
 
 
 
 
30
  """
31
 
32
  import time, random, math, threading, asyncio, warnings
@@ -34,7 +39,6 @@ from functools import reduce
34
  from typing import Optional, Callable, List, Dict, Tuple, Any, Set
35
  from dataclasses import dataclass, field
36
  from collections import defaultdict
37
- import concurrent.futures
38
  from concurrent.futures import ThreadPoolExecutor
39
  from contextlib import asynccontextmanager
40
 
@@ -49,7 +53,7 @@ import uvicorn
49
  warnings.filterwarnings("ignore")
50
  USE_GPU = torch.cuda.is_available()
51
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
52
- print(f"[SYSTEM 15.5] Compute: {'GPU' if USE_GPU else 'CPU'} | Algorithm: Parallel A* Search")
53
 
54
  # ══════════════════════════════════════════════════════════════════════
55
  # SECTION 1: CONSTANTS
@@ -512,7 +516,8 @@ class VerifyLayer:
512
  elif inv.mode=="geq": passed=val>=-inv.tolerance
513
  elif inv.mode=="leq": passed=val<=inv.tolerance
514
  else: passed=err<inv.tolerance
515
- g2[inv.name]=(round(val,6),passed)
 
516
  except: g2[inv.name]=(999.0,False)
517
  g2_pass=all(v[1] for v in g2.values()) if g2 else True
518
  failed=(["Gate1"] if not g1_pass else [])+[k for k,v in g2.items() if not v[1]]
@@ -1225,42 +1230,27 @@ def _hyp_composite(problem,baton,all_batons,model):
1225
  except: pass
1226
  return hyps
1227
 
1228
- def _hyp_holism(problem,baton,all_batons,model):
1229
- b=dict(baton.binding); grad=problem.evaluate_gradient(b)
1230
- gms=sum(g**2 for g in grad.values())
1231
- if gms<1e-12: return []
1232
- lr=min(0.5,baton.ce/(gms+1e-8))
1233
- nb={v:max(problem.bounds[v][0],min(problem.bounds[v][1],b[v]-lr*grad[v])) for v in problem.variables}
1234
- return [_make_hyp(f"hol_{hash(str(nb))%9999}",nb,"holism",
1235
- f"Global(lr={lr:.4f})",["holism"],{},list(problem.variables),0.73)]
1236
-
1237
  def _hyp_parsimony(problem,baton,all_batons,model):
1238
- b=dict(baton.binding); nb={}
 
 
 
 
 
 
1239
  for v in problem.variables:
1240
- lo,hi=problem.bounds[v]; candidates=[]
1241
- for mult in [1,2,4]:
1242
- r=round(b[v]*mult)/mult
1243
- if lo<=r<=hi: candidates.append(r)
1244
- nb[v]=min(candidates,key=lambda c:abs(c-b[v])) if candidates else b[v]
1245
- return [_make_hyp(f"par_{hash(str(nb))%9999}",nb,"parsimony","Occam",["parsimony"],{},list(problem.variables),0.58)]
1246
-
1247
- def _hyp_duality(problem,baton,all_batons,model):
1248
- hyps=[]; b=dict(baton.binding)
1249
- for mc in problem.compiled_constraints:
1250
- if mc.kind!="inequality" or not mc.projections: continue
1251
- for v,projs in mc.projections.items():
1252
- lo,hi=problem.bounds.get(v,(-1e18,1e18))
1253
- for proj in projs:
1254
- try:
1255
- val=float(proj["func"](*[b.get(s,0.0) for s in proj["syms"]]))
1256
- if not(lo<=val<=hi) or not math.isfinite(val): continue
1257
- nb=dict(b); nb[v]=val
1258
- hyps.append(_make_hyp(f"dua_{hash(mc.expr_str)%9999}_{v}",nb,"duality",
1259
- f"Tight({v})",["duality",mc.expr_str],{v:val},
1260
- [u for u in problem.variables if u!=v],0.68))
1261
- break
1262
- except: pass
1263
- return hyps
1264
 
1265
  AXIOM_CONSTRUCTORS:Dict[str,Callable]={
1266
  Axiom.CONTINUOUS:_hyp_continuous, Axiom.DISCRETE:_hyp_discrete,
@@ -1280,7 +1270,7 @@ AXIOM_CONSTRUCTORS:Dict[str,Callable]={
1280
  }
1281
 
1282
  # ══════════════════════════════════════════════════════════════════════
1283
- # SECTION 12: SEQUENCE HYPOTHESIS GENERATOR (Parallel Beam Search)
1284
  # ══════════════════════════════════════════════════════════════════════
1285
  class SequenceHypothesisGenerator:
1286
  def generate(self, sequence:List[str], problem:Problem,
@@ -1305,21 +1295,18 @@ class SequenceHypothesisGenerator:
1305
 
1306
  best_ce=current.ce; best_b=current.binding
1307
 
1308
- # 15.5: PARALLEL BEAM SEARCH (IMAGINARY LINES)
 
 
 
1309
  valid_hyps = [h for h in sorted(new_hyps, key=lambda h: -h.confidence)[:MAX_HYPS_PER_AXIOM]
1310
  if h.hid not in model.failure_patterns]
1311
 
1312
- if valid_hyps:
1313
- with ThreadPoolExecutor(max_workers=len(valid_hyps)) as hyp_pool:
1314
- futures = [hyp_pool.submit(_test_hypothesis, problem, hyp) for hyp in valid_hyps]
1315
- for future in concurrent.futures.as_completed(futures):
1316
- try:
1317
- tb, tce = future.result()
1318
- if tce < best_ce:
1319
- best_ce = tce
1320
- best_b = tb
1321
- except Exception:
1322
- pass
1323
 
1324
  if best_ce<current.ce:
1325
  if prev_axiom and best_ce < prev_ce * RESONANCE_THRESHOLD:
@@ -1409,7 +1396,7 @@ class CreativeSeeder:
1409
  CREATIVE_SEEDER=CreativeSeeder()
1410
 
1411
  # ══════════════════════════════════════════════════════════════════════
1412
- # SECTION 14: SEQUENCE RAY TRACER
1413
  # ══════════════════════════════════════════════════════════════════════
1414
  class SequenceRayTracer:
1415
  MAX_TOTAL_RAYS = 3000
@@ -1440,13 +1427,18 @@ class SequenceRayTracer:
1440
  scout_rays = CREATIVE_SEEDER.random_scouts(n=500)
1441
  for r in scout_rays: r.ce_prior = init_ce
1442
 
1443
- active:List[AxiomRay]=[]
1444
- buckets=[seed_rays, tension_rays, scout_rays]
1445
- random.shuffle(seed_rays); random.shuffle(tension_rays); random.shuffle(scout_rays)
1446
- max_len=max(len(b) for b in buckets)
1447
- for i in range(max_len):
1448
- for bucket in buckets:
1449
- if i<len(bucket): active.append(bucket[i])
 
 
 
 
 
1450
 
1451
  all_batons:List[Baton]=[]; best_ce=float('inf'); best_binding:Dict={}
1452
  history:List[Dict]=[]; total_fired=0
@@ -1455,10 +1447,25 @@ class SequenceRayTracer:
1455
  shared_model=StructuralModel(best_binding=init_b,best_ce=init_ce)
1456
  self._last_traces=all_traces
1457
 
1458
- print(f"\n{'═'*65}\nCREATIVE RAY TRACE 15.5 (Parallel): {axl_def.name}\n{'═'*65}")
 
 
 
1459
 
1460
- while active and total_fired<self.MAX_TOTAL_RAYS:
1461
- ray=active.pop(0); total_fired+=1
 
 
 
 
 
 
 
 
 
 
 
 
1462
  parent_baton=ray.baton or seed_baton
1463
 
1464
  shared_model.best_binding=best_binding if best_binding else parent_baton.binding
@@ -1524,8 +1531,15 @@ class SequenceRayTracer:
1524
  CREATIVE_SEEDER.resonance_extensions(
1525
  ray, output_baton.ce, shared_model.resonant_pairs))
1526
 
1527
- active.extend(new_children)
1528
- active.sort(key=lambda r: r.ce_prior + (r.depth * 0.0001))
 
 
 
 
 
 
 
1529
 
1530
  survived=[t for t in all_traces if t.survived]
1531
  best_t=min(survived,key=lambda t:t.ce_after,default=None)
@@ -1975,7 +1989,7 @@ async def lifespan(app):
1975
  # ══════════════════════════════════════════════════════════════════════
1976
  # SECTION 17: FASTAPI + DASHBOARD
1977
  # ══════════════════════════════════════════════════════════════════════
1978
- app=FastAPI(title="Practicality 15.5",lifespan=lifespan)
1979
 
1980
  def _type_badge(rt:str, count:int, survived:int) -> str:
1981
  icon=RAY_ICONS.get(rt,"Β·")
@@ -2123,7 +2137,7 @@ async def dashboard():
2123
  collapses="".join(_render_collapse(r) for r in log) if log else \
2124
  "<div style='color:#222;padding:16px'>Cycling through 14 problems…</div>"
2125
 
2126
- return f"""<!DOCTYPE html><html><head><title>Practicality 15.5</title>
2127
  <meta http-equiv="refresh" content="5">
2128
  <style>
2129
  body{{background:#090909;color:#e0e0e0;font-family:monospace;padding:18px;max-width:1700px}}
@@ -2134,9 +2148,9 @@ async def dashboard():
2134
  th{{color:#252525;font-size:0.70em}}
2135
  .badge{{display:inline-block;padding:2px 9px;border-radius:3px;background:#0e0e0e;margin:2px;font-size:0.75em;border:1px solid #1a1a1a}}
2136
  </style></head><body>
2137
- <h1>βš— Practicality 15.5 β€” Parallel Beam Search (Imaginary Lines)</h1>
2138
  <div style='color:#2a2a2a;font-size:0.72em;margin-bottom:10px'>
2139
- 🌱 Seeds + ⚑ Tension + πŸ”­ Scouts β†’ 🧬 Recombine + πŸ”„ Invert β†’ 🌿 Branch (Parallel A* Eval) β†’ Verify
2140
  </div>
2141
  <div style='margin-bottom:14px'>
2142
  <span class='badge' style='color:#aaa'>Total Runs: {total_runs}</span>
 
1
  #!/usr/bin/env python3
2
  """
3
+ PRACTICALITY SYSTEM 15.6 β€” HYPER-OPTIMIZED BEAM SEARCH & ROUND-ROBIN QUEUE
4
  ═══════════════════════════════════════════════════════════════════
5
  SYSTEM SUMMARY:
6
  This is a set-based axiomatic ray tracer designed to deduce the
 
21
  manifold tangents, asymmetric splits).
22
  4. VERIFY LAYER: A rigid binary oracle testing the true Base problem.
23
 
24
+ NEW IN 15.6:
25
+ Β· Removed GIL Bottleneck: "Imaginary Lines" (Beam Search) are now
26
+ evaluated sequentially in a tight, fast loop. Python threading
27
+ overhead was choking the CPU and dropping valid solutions.
28
+ Β· Round-Robin Queue: Destroys the "Genetic Inbreeding" trap. The
29
+ queue is split into Core, Explore, and Genetic buckets. The engine
30
+ pulls from them equally, ensuring Scouts are never starved by thousands
31
+ of greedy Recombinations.
32
+ Β· Sparsity (Parsimony) Upgrade: The PARSIMONY axiom now forces L0-norm
33
+ sparsity (zeroing small variables) and rounds the rest, directly
34
+ targeting Compressed Sensing / Signal Recovery geometries.
35
  """
36
 
37
  import time, random, math, threading, asyncio, warnings
 
39
  from typing import Optional, Callable, List, Dict, Tuple, Any, Set
40
  from dataclasses import dataclass, field
41
  from collections import defaultdict
 
42
  from concurrent.futures import ThreadPoolExecutor
43
  from contextlib import asynccontextmanager
44
 
 
53
  warnings.filterwarnings("ignore")
54
  USE_GPU = torch.cuda.is_available()
55
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
56
+ print(f"[SYSTEM 15.6] Compute: {'GPU' if USE_GPU else 'CPU'} | Algorithm: Round-Robin Beam Search")
57
 
58
  # ══════════════════════════════════════════════════════════════════════
59
  # SECTION 1: CONSTANTS
 
516
  elif inv.mode=="geq": passed=val>=-inv.tolerance
517
  elif inv.mode=="leq": passed=val<=inv.tolerance
518
  else: passed=err<inv.tolerance
519
+ # UI Adjustment: if it's an inequality, return the raw value, not absolute error.
520
+ g2[inv.name]=(round(val if inv.mode in ("geq","leq") else err,6),passed)
521
  except: g2[inv.name]=(999.0,False)
522
  g2_pass=all(v[1] for v in g2.values()) if g2 else True
523
  failed=(["Gate1"] if not g1_pass else [])+[k for k,v in g2.items() if not v[1]]
 
1230
  except: pass
1231
  return hyps
1232
 
 
 
 
 
 
 
 
 
 
1233
  def _hyp_parsimony(problem,baton,all_batons,model):
1234
+ """
1235
+ 15.6 FIX: Explicit L0-norm sparsity for SignalRecovery/Compressed Sensing.
1236
+ Zeros out variables that are significantly smaller than the max magnitude.
1237
+ """
1238
+ b = dict(baton.binding)
1239
+ nb = {}
1240
+ max_val = max((abs(v) for v in b.values()), default=1.0)
1241
  for v in problem.variables:
1242
+ val = b[v]
1243
+ lo, hi = problem.bounds[v]
1244
+ # Sparsity enforcement: if it's < 10% of the max signal, try snapping to exactly 0.0
1245
+ if abs(val) < 0.1 * max_val and lo <= 0.0 <= hi:
1246
+ nb[v] = 0.0
1247
+ else:
1248
+ candidates = []
1249
+ for mult in [1, 2, 4]:
1250
+ r = round(val * mult) / mult
1251
+ if lo <= r <= hi: candidates.append(r)
1252
+ nb[v] = min(candidates, key=lambda c: abs(c - val)) if candidates else val
1253
+ return [_make_hyp(f"par_{hash(str(nb))%9999}", nb, "parsimony", "OccamSparsity", ["parsimony"], {}, list(problem.variables), 0.58)]
 
 
 
 
 
 
 
 
 
 
 
 
1254
 
1255
  AXIOM_CONSTRUCTORS:Dict[str,Callable]={
1256
  Axiom.CONTINUOUS:_hyp_continuous, Axiom.DISCRETE:_hyp_discrete,
 
1270
  }
1271
 
1272
  # ══════════════════════════════════════════════════════════════════════
1273
+ # SECTION 12: SEQUENCE HYPOTHESIS GENERATOR (Fast Sequential Beam Search)
1274
  # ══════════════════════════════════════════════════════════════════════
1275
  class SequenceHypothesisGenerator:
1276
  def generate(self, sequence:List[str], problem:Problem,
 
1295
 
1296
  best_ce=current.ce; best_b=current.binding
1297
 
1298
+ # 15.6 FIX: Removed ThreadPoolExecutor.
1299
+ # Sequential evaluation is vastly faster here because Python's GIL
1300
+ # prevents true parallelism for SymPy CPU math anyway, and context
1301
+ # switching was causing timeouts/dropped hypotheses.
1302
  valid_hyps = [h for h in sorted(new_hyps, key=lambda h: -h.confidence)[:MAX_HYPS_PER_AXIOM]
1303
  if h.hid not in model.failure_patterns]
1304
 
1305
+ for hyp in valid_hyps:
1306
+ tb, tce = _test_hypothesis(problem, hyp)
1307
+ if tce < best_ce:
1308
+ best_ce = tce
1309
+ best_b = tb
 
 
 
 
 
 
1310
 
1311
  if best_ce<current.ce:
1312
  if prev_axiom and best_ce < prev_ce * RESONANCE_THRESHOLD:
 
1396
  CREATIVE_SEEDER=CreativeSeeder()
1397
 
1398
  # ══════════════════════════════════════════════════════════════════════
1399
+ # SECTION 14: SEQUENCE RAY TRACER (Round-Robin Queue)
1400
  # ══════════════════════════════════════════════════════════════════════
1401
  class SequenceRayTracer:
1402
  MAX_TOTAL_RAYS = 3000
 
1427
  scout_rays = CREATIVE_SEEDER.random_scouts(n=500)
1428
  for r in scout_rays: r.ce_prior = init_ce
1429
 
1430
+ # 15.6 FIX: Round-Robin Queue setup
1431
+ queues = {
1432
+ "core": [], # Seeds, Branches
1433
+ "explore": [], # Scouts, Tensions
1434
+ "genetic": [] # Recombine, Invert
1435
+ }
1436
+
1437
+ for r in seed_rays: queues["core"].append(r)
1438
+ for r in tension_rays: queues["explore"].append(r)
1439
+ for r in scout_rays: queues["explore"].append(r)
1440
+
1441
+ for q in queues.values(): random.shuffle(q)
1442
 
1443
  all_batons:List[Baton]=[]; best_ce=float('inf'); best_binding:Dict={}
1444
  history:List[Dict]=[]; total_fired=0
 
1447
  shared_model=StructuralModel(best_binding=init_b,best_ce=init_ce)
1448
  self._last_traces=all_traces
1449
 
1450
+ print(f"\n{'═'*65}\nCREATIVE RAY TRACE 15.6 (RR): {axl_def.name}\n{'═'*65}")
1451
+
1452
+ queue_order = ["core", "explore", "genetic"]
1453
+ q_idx = 0
1454
 
1455
+ while total_fired < self.MAX_TOTAL_RAYS:
1456
+ # Round-Robin Pop
1457
+ start_idx = q_idx
1458
+ while not queues[queue_order[q_idx]]:
1459
+ q_idx = (q_idx + 1) % 3
1460
+ if q_idx == start_idx: break
1461
+
1462
+ if not queues[queue_order[q_idx]]:
1463
+ break # All queues empty
1464
+
1465
+ ray = queues[queue_order[q_idx]].pop(0)
1466
+ q_idx = (q_idx + 1) % 3
1467
+
1468
+ total_fired+=1
1469
  parent_baton=ray.baton or seed_baton
1470
 
1471
  shared_model.best_binding=best_binding if best_binding else parent_baton.binding
 
1531
  CREATIVE_SEEDER.resonance_extensions(
1532
  ray, output_baton.ce, shared_model.resonant_pairs))
1533
 
1534
+ # Push children into appropriate buckets
1535
+ for child in new_children:
1536
+ if child.ray_type in (RAY_SEED, RAY_BRANCH): queues["core"].append(child)
1537
+ elif child.ray_type in (RAY_SCOUT, RAY_TENSION): queues["explore"].append(child)
1538
+ elif child.ray_type in (RAY_RECOMBINE, RAY_INVERT): queues["genetic"].append(child)
1539
+
1540
+ # Keep A* priority within buckets (optional, keeps best stuff at front of its bucket)
1541
+ queues["core"].sort(key=lambda r: r.ce_prior + (r.depth * 0.0001))
1542
+ queues["genetic"].sort(key=lambda r: r.ce_prior + (r.depth * 0.0001))
1543
 
1544
  survived=[t for t in all_traces if t.survived]
1545
  best_t=min(survived,key=lambda t:t.ce_after,default=None)
 
1989
  # ══════════════════════════════════════════════════════════════════════
1990
  # SECTION 17: FASTAPI + DASHBOARD
1991
  # ══════════════════════════════════════════════════════════════════════
1992
+ app=FastAPI(title="Practicality 15.6",lifespan=lifespan)
1993
 
1994
  def _type_badge(rt:str, count:int, survived:int) -> str:
1995
  icon=RAY_ICONS.get(rt,"Β·")
 
2137
  collapses="".join(_render_collapse(r) for r in log) if log else \
2138
  "<div style='color:#222;padding:16px'>Cycling through 14 problems…</div>"
2139
 
2140
+ return f"""<!DOCTYPE html><html><head><title>Practicality 15.6</title>
2141
  <meta http-equiv="refresh" content="5">
2142
  <style>
2143
  body{{background:#090909;color:#e0e0e0;font-family:monospace;padding:18px;max-width:1700px}}
 
2148
  th{{color:#252525;font-size:0.70em}}
2149
  .badge{{display:inline-block;padding:2px 9px;border-radius:3px;background:#0e0e0e;margin:2px;font-size:0.75em;border:1px solid #1a1a1a}}
2150
  </style></head><body>
2151
+ <h1>βš— Practicality 15.6 β€” Hyper-Optimized Beam Search & Round-Robin Queue</h1>
2152
  <div style='color:#2a2a2a;font-size:0.72em;margin-bottom:10px'>
2153
+ 🌱 Seeds + ⚑ Tension + πŸ”­ Scouts β†’ 🧬 Recombine + πŸ”„ Invert β†’ 🌿 Branch (Round-Robin) β†’ Verify
2154
  </div>
2155
  <div style='margin-bottom:14px'>
2156
  <span class='badge' style='color:#aaa'>Total Runs: {total_runs}</span>