everydaytok commited on
Commit
ab48ae4
Β·
verified Β·
1 Parent(s): 4d35e75

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -79
app.py CHANGED
@@ -1,20 +1,19 @@
1
  #!/usr/bin/env python3
2
  """
3
- PRACTICALITY SYSTEM 20.0 β€” TRUE GPU SATURATION & PRECOMPILATION
4
  ═══════════════════════════════════════════════════════════════════
5
- AIM:
6
- To extract a true, LLM-readable structural isomorphism of a mathematical problem.
7
-
8
- THE BOTTLENECK FIX (20.0):
9
- In 19.3, large batch sizes starved the GPU because Python was doing heavy lifting
10
- (SymPy parsing, string evaluation, dict sorting) inside the 12k loop.
11
-
12
- System 20.0 implements True Parallelism:
13
- 1. Pre-compilation: Anchors and Axiom properties (Bilinear/Monotone constants)
14
- are parsed exactly ONCE at initialization.
15
- 2. GPU Top-K Gradients: Python dict sorting is replaced by `torch.topk()` to
16
- calculate allosteric tension vectors for all 12,288 rays simultaneously on GPU.
17
- 3. Fast Tensor Build: CPU array generation is streamlined to feed PyTorch instantly.
18
  """
19
 
20
  import time, random, math, threading, warnings
@@ -32,7 +31,7 @@ import gradio as gr
32
  warnings.filterwarnings("ignore")
33
  USE_GPU = torch.cuda.is_available()
34
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
35
- print(f"[SYSTEM 20.0] Compute: {DEVICE.type.upper()} | Engine: True GPU Saturation")
36
 
37
  # ══════════════════════════════════════════════════════════════════════
38
  # SECTION 1: CONSTANTS
@@ -48,7 +47,8 @@ MAX_TOTAL_RAYS = 1_500_000
48
  RAY_BATCH_SIZE = 12288
49
  CE_EARN_RATIO = 0.90
50
  SCOUT_CE_THRESHOLD = 0.5
51
- BRANCH_WIDTH = 4
 
52
  BATON_REGISTRY_THRESHOLD = 2.0
53
  BATON_REGISTRY_MAX = 5000
54
 
@@ -222,13 +222,12 @@ def expand_psl(prog:PSLProgram) -> ExpandedProblem:
222
  return ExpandedProblem(variables,bounds,constraints,dict(scope_groups),dict(scope_vars),prog.scope_order)
223
 
224
  @dataclass
225
- class AXLInvariant:
226
  name:str; expr:str; tolerance:float=VERIFY_G2_TOLERANCE; mode:str="eq"
227
  compiled_func: Optional[Callable] = field(default=None, repr=False)
228
  syms_used: List[str] = field(default_factory=list)
229
 
230
  def compile(self, variables: List[str]):
231
- """SYSTEM 20.0 FIX: Pre-compile anchors to avoid parsing inside the 12k batch loop"""
232
  syms = {v: sp.Symbol(v) for v in variables}
233
  parsed = parse_expr(self.expr, local_dict=syms)
234
  self.syms_used = [str(s) for s in parsed.free_symbols if str(s) in variables]
@@ -264,7 +263,7 @@ class AXLtoPSLCompiler:
264
  AXL_COMPILER=AXLtoPSLCompiler()
265
 
266
  # ══════════════════════════════════════════════════════════════════════
267
- # SECTION 4: PROBLEM COMPILATION (PyTorch-native)
268
  # ══════════════════════════════════════════════════════════════════════
269
  @dataclass
270
  class Constraint:
@@ -328,6 +327,44 @@ def compile_mc(kind,expr_str,direction,variables,weight=1.0,scope="root",branche
328
  except: pass
329
  return mc
330
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  @dataclass
332
  class Problem:
333
  pid:str; variables:List[str]; constraints:List[Constraint]
@@ -335,23 +372,24 @@ class Problem:
335
  scope_groups:Dict[str,List[int]]=field(default_factory=dict)
336
  scope_vars:Dict[str,List[str]]=field(default_factory=dict)
337
  scope_order:List[str]=field(default_factory=list)
338
-
339
- # SYSTEM 20.0 PRECOMPILATION ARRAYS
340
  bilinear_pairs: List[Tuple[str,str]] = field(default_factory=list)
341
  monotone_targets: List[Tuple[str,str,float]] = field(default_factory=list)
 
342
 
343
  def __post_init__(self):
344
  self.compiled_constraints=[
345
  compile_mc(c.kind,c.expr,c.direction,self.variables,c.weight,c.scope,c.branches)
346
  for c in self.constraints]
347
  self.var_idx={v:i for i,v in enumerate(self.variables)}
348
-
349
- # SYSTEM 20.0: Pre-extract structural signatures to avoid AST parsing in batch loops
350
- ordered_pairs = []
351
  for mc in self.compiled_constraints:
352
- if mc.kind == "inequality" and mc.direction == "geq" and len(mc.syms_used) == 2:
353
- ordered_pairs.append((mc.syms_used[0], mc.syms_used[1]))
354
-
 
 
355
  for mc in self.compiled_constraints:
356
  if mc.parsed and mc.parsed.is_Add:
357
  for term in mc.parsed.args:
@@ -361,16 +399,26 @@ class Problem:
361
  va, vb = syms_in
362
  if (va, vb) not in self.bilinear_pairs and (vb, va) not in self.bilinear_pairs:
363
  self.bilinear_pairs.append((va, vb))
364
- if mc.kind == "equality":
365
- try:
366
- const_part = mc.parsed - sp.Symbol(va)*sp.Symbol(vb)
367
- k = float(-const_part.evalf())
368
- if k > 0:
369
- for vs, vl in ordered_pairs:
370
- if set([va, vb]) == set([vs, vl]):
371
- if (vs, vl, k) not in self.monotone_targets:
372
- self.monotone_targets.append((vs, vl, k))
373
- except: pass
 
 
 
 
 
 
 
 
 
 
374
 
375
  def tensor_energy(self,X:torch.Tensor) -> torch.Tensor:
376
  is_batched=(X.dim()==2)
@@ -431,15 +479,9 @@ class L9Certificate:
431
  def _batched_deduce_and_evaluate(
432
  problem:Problem,
433
  hyps:List['Hypothesis']) -> List[Tuple[Dict,float,List[str],str]]:
434
- """
435
- Naked Evaluation with Masked Adam.
436
- SYSTEM 20.0 FIX: Optimized array building & PyTorch Top-K extraction
437
- to bypass Python CPU loops over large batches.
438
- """
439
  if not hyps: return []
440
  B=len(hyps); V=len(problem.variables)
441
 
442
- # Fast Python list building to avoid element-by-element tensor operations
443
  x_data = []
444
  mask_data = []
445
  target_data = []
@@ -466,14 +508,13 @@ def _batched_deduce_and_evaluate(
466
  if isinstance(ce,torch.Tensor) and (ce<SOLVE_THRESHOLD).all(): break
467
  loss=ce.sum(); loss.backward()
468
  with torch.no_grad():
469
- X.grad*=mask # CRITICAL: respect structural pins
470
  optimizer.step()
471
  X.data=torch.where(mask==0.0,target,X.data)
472
  for j,v in enumerate(problem.variables):
473
  lo,hi=problem.bounds[v]
474
  X.data[:,j]=torch.clamp(X.data[:,j],lo,hi)
475
 
476
- # Gradient oracle pass
477
  optimizer.zero_grad()
478
  final_ce=problem.tensor_energy(X)
479
  final_ce.sum().backward()
@@ -481,7 +522,6 @@ def _batched_deduce_and_evaluate(
481
  ce_vals = final_ce.detach().cpu().numpy()
482
  X_vals = X.detach().cpu().numpy()
483
 
484
- # SYSTEM 20.0 FIX: GPU Top-K completely removes Python dictionary sorting overhead
485
  grads_abs = X.grad.abs()
486
  _, topk_idx = torch.topk(grads_abs, k=min(3, V), dim=1)
487
  topk_idx_np = topk_idx.cpu().numpy()
@@ -490,16 +530,12 @@ def _batched_deduce_and_evaluate(
490
  results=[]
491
  for i in range(B):
492
  final_b={problem.variables[j]:float(X_vals[i,j]) for j in range(V)}
493
-
494
- # O(1) top-K gradient extraction per element
495
  dom_vars = [problem.variables[idx] for idx in topk_idx_np[i] if float(grads_np[i, idx]) > 1e-4]
496
  n_dom = len(dom_vars)
497
-
498
  if n_dom<=1: tension_class="isolated"
499
  elif n_dom==2: tension_class="relational"
500
  else: tension_class="systemic"
501
  results.append((final_b,float(ce_vals[i]),dom_vars,tension_class))
502
-
503
  return results
504
 
505
  def _mprt_sample(problem,work_box,N):
@@ -603,7 +639,7 @@ class StructuralModel:
603
  resonant_pairs:List[Tuple[str,str]]=field(default_factory=list)
604
 
605
  # ══════════════════════════════════════════════════════════════════════
606
- # SECTION 8: HYPOTHESIS CONSTRUCTORS (Pre-Compiled)
607
  # ══════════════════════════════════════════════════════════════════════
608
  def _make_hyp(hid,binding,h_type,claim,derivation,pinned,free,conf):
609
  return Hypothesis(hid=hid,binding=binding,h_type=h_type,claim=claim,
@@ -631,7 +667,6 @@ def _hyp_quadratic(p,bt,a,m):
631
  return hyps
632
 
633
  def _hyp_bilinear(p,bt,a,m):
634
- """SYSTEM 20.0 FIX: Uses pre-extracted bilinear pairs."""
635
  hyps=[]; b=dict(bt.binding)
636
  for vi, vj in p.bilinear_pairs:
637
  lo_i,hi_i=p.bounds.get(vi,(0,10)); lo_j,hi_j=p.bounds.get(vj,(0,10))
@@ -660,9 +695,19 @@ def _hyp_bilinear(p,bt,a,m):
660
  return hyps
661
 
662
  def _hyp_monotone_product(p,bt,a,m):
663
- """SYSTEM 20.0 FIX: Uses pre-extracted monotone targets."""
 
 
 
 
 
 
 
 
 
 
 
664
  hyps=[]; b=dict(bt.binding)
665
-
666
  if not p.monotone_targets: return hyps
667
  tb=_global_hc4_tighten_bounds(p)
668
 
@@ -787,7 +832,7 @@ AXIOM_CONSTRUCTORS={
787
  }
788
 
789
  # ══════════════════════════════════════════════════════════════════════
790
- # SECTION 9: CREATIVE SEEDER (Allosteric + Bidirectional)
791
  # ══════════════════════════════════════════════════════════════════════
792
  class CreativeSeeder:
793
  def target_seeds(self,anchors:List[AXLInvariant]) -> List[AxiomRay]:
@@ -805,7 +850,14 @@ class CreativeSeeder:
805
 
806
  def intelligent_branch(self,ray,out_baton,remaining_axioms,branch_width) -> List[AxiomRay]:
807
  dom_vars=out_baton.l9.dominant_vars if out_baton.l9 else []
808
- n_dom=len([v for v in dom_vars])
 
 
 
 
 
 
 
809
  isolated ={Axiom.ATOMIC,Axiom.EXTREMAL,Axiom.MUTABLE,Axiom.DUALITY,Axiom.LOCALITY}
810
  relational ={Axiom.SYMMETRIC,Axiom.BILINEAR,Axiom.MONOTONE_PRODUCT,
811
  Axiom.ORDERED,Axiom.METRIC,Axiom.INJECTIVE}
@@ -821,7 +873,7 @@ class CreativeSeeder:
821
  scored.sort(key=lambda x:x[0]*random.random(),reverse=True)
822
 
823
  children=[]
824
- for _,axiom in scored[:branch_width]:
825
  child=ray.extend(axiom,"branch",new_prior=out_baton.ce)
826
  if child: child.baton=out_baton; children.append(child)
827
  return children
@@ -888,7 +940,7 @@ class CreativeSeeder:
888
  CREATIVE_SEEDER=CreativeSeeder()
889
 
890
  # ══════════════════════════════════════════════════════════════════════
891
- # SECTION 10: VERIFY LAYER (SYSTEM 20.0 FIX: Pre-compiled lambda evaluation)
892
  # ══════════════════════════════════════════════════════════════════════
893
  def _verify(binding:Dict[str,float],base_problem:Problem,
894
  anchors:List[AXLInvariant]) -> Tuple[bool,bool,Dict[str,Tuple[float,bool]],float]:
@@ -900,7 +952,7 @@ def _verify(binding:Dict[str,float],base_problem:Problem,
900
  if inv.compiled_func:
901
  val = float(inv.compiled_func(*[binding.get(v, 0.0) for v in inv.syms_used]))
902
  else:
903
- val = 999.0 # Failsafe
904
  err=abs(val)
905
  if inv.mode=="eq": passed=err<inv.tolerance
906
  elif inv.mode=="geq": passed=val>=-inv.tolerance
@@ -917,14 +969,11 @@ def _verify(binding:Dict[str,float],base_problem:Problem,
917
  class SequenceRayTracer:
918
  def trace(self,axl_def:AXLProblemDef,base_problem:Problem):
919
  hero_traces:List[HypothesisTrace]=[]
920
-
921
  baton_registry:Dict[str,Baton]={}
922
  baton_registry_keys:deque=deque()
923
-
924
  successful_rays:List[AxiomRay]=[]
925
  resonant_pairs:List[Tuple[str,str]]=[]
926
 
927
- # SYSTEM 20.0 FIX: Precompile anchors before 12k loop starts
928
  for inv in axl_def.anchors:
929
  if not inv.compiled_func:
930
  inv.compile(base_problem.variables)
@@ -944,7 +993,6 @@ class SequenceRayTracer:
944
  queue_order=["core","explore","genetic"]; q_idx=0
945
  best_ce=init_ce; best_binding=dict(init_b); total_fired=0
946
  model=StructuralModel(best_binding,best_ce)
947
-
948
  allosteric_counts={"isolated":0,"relational":0,"systemic":0}
949
 
950
  while total_fired<MAX_TOTAL_RAYS:
@@ -1288,10 +1336,10 @@ def toggle_engine():
1288
  global IS_RUNNING
1289
  IS_RUNNING=not IS_RUNNING
1290
  if IS_RUNNING: threading.Thread(target=background_worker,daemon=True).start()
1291
- return "⏹ STOP 20.0" if IS_RUNNING else "β–Ά START 20.0"
1292
 
1293
  # ══════════════════════════════════════════════════════════════════════
1294
- # SECTION 14: GRADIO DASHBOARD
1295
  # ══════════════════════════════════════════════════════════════════════
1296
  RAY_ICONS={"seed":"🌱","branch":"🌿","tension":"⚑","scout":"πŸ”­",
1297
  "recombine":"🧬","invert":"πŸ”„","target":"🎯"}
@@ -1337,10 +1385,10 @@ def _render_type_table() -> str:
1337
  global_stats[rt]["survived"]+=counts["survived"]
1338
  desc={
1339
  "seed":"Greedy depth-first from single axiom",
1340
- "branch":"Allosteric feedback-guided child (gradient topology)",
1341
  "tension":"Mediated contradiction [Aβ†’B1β†’Mβ†’B2β†’C] length 5",
1342
  "scout":"Random length 3-12 cartographer",
1343
- "recombine":"Genetic crossover + INTERPOLATED baton geometry",
1344
  "invert":"Reversed successful sequence",
1345
  "target":"Bidirectional: spawned from goal state invariants",
1346
  }
@@ -1352,7 +1400,7 @@ def _render_type_table() -> str:
1352
  f"<td style='color:#FF9800'>{rt}</td>"
1353
  f"<td style='color:#aaa'>{s['tried']}</td>"
1354
  f"<td style='color:#4CAF50'>{s['survived']}</td>"
1355
- f"<td style='color:EF5350'>{s['tried']-s['survived']}</td>"
1356
  f"<td style='color:{c};font-weight:700'>{rate}%</td>"
1357
  f"<td style='color:#555;font-size:0.8em'>{desc.get(rt,'')}</td></tr>")
1358
  return rows
@@ -1366,7 +1414,7 @@ def _render_allosteric_table() -> str:
1366
  rows=""
1367
  desc={"isolated":"1 dominant var β†’ ATOMIC/EXTREMAL/DUALITY",
1368
  "relational":"2 dominant vars β†’ BILINEAR/MPR/ORDERED/METRIC",
1369
- "systemic":"3+ dominant vars β†’ CONSERVED/NETWORK/HOLISM"}
1370
  for tc,cnt in totals.items():
1371
  pct=round(cnt/grand*100)
1372
  rows+=(f"<tr><td style='color:#FF9800'>{tc}</td>"
@@ -1456,11 +1504,11 @@ def refresh_dashboard():
1456
  return f"""
1457
  <div style='background:#090909;color:#e0e0e0;font-family:monospace;padding:16px;max-width:1700px'>
1458
  <h2 style='color:#26C6DA;border-bottom:1px solid #1a1a1a;padding-bottom:5px;font-size:1.05em;margin:0 0 8px 0'>
1459
- βš— Practicality 20.0 β€” True GPU Saturation
1460
  </h2>
1461
  <div style='color:#2a2a2a;font-size:0.70em;margin-bottom:10px'>
1462
- Masked Adam (structural pins) Β· GPU Top-K Oracle β†’ Allosteric Feedback Β·
1463
- Pre-Compiled Axioms & Anchors Β· 12K Batch Scale
1464
  </div>
1465
  <div style='margin-bottom:12px'>
1466
  <span style='display:inline-block;padding:2px 8px;border-radius:3px;background:#0e0e0e;margin:2px;font-size:0.72em;border:1px solid #1a1a1a;color:#aaa'>Runs: {runs}</span>
@@ -1473,11 +1521,11 @@ def refresh_dashboard():
1473
 
1474
  <h4 style='color:#252525;font-size:0.78em;letter-spacing:2px;text-transform:uppercase;margin:16px 0 4px 0'>Creative Ray Type Efficacy</h4>
1475
  <table style='width:100%;border-collapse:collapse;margin-bottom:10px'>
1476
- <tr style='color:#252525;font-size:0.68em'><th></th><th>Type</th><th>Tried</th><th>Survived</th><th>Failed</th><th>Rate</th><th>Mechanism (20.0)</th></tr>
1477
  {types}
1478
  </table>
1479
 
1480
- <h4 style='color:#252525;font-size:0.78em;letter-spacing:2px;text-transform:uppercase;margin:16px 0 4px 0'>Allosteric Feedback Diagnostics (Gradient Topology β†’ Axiom Class)</h4>
1481
  <table style='width:100%;border-collapse:collapse;margin-bottom:10px'>
1482
  <tr style='color:#252525;font-size:0.68em'><th>Tension Class</th><th>Fired</th><th>Share</th><th>Biases Toward</th></tr>
1483
  {allos}
@@ -1498,14 +1546,15 @@ def refresh_dashboard():
1498
  {recnt}
1499
  </div>"""
1500
 
1501
- with gr.Blocks(theme=gr.themes.Monochrome(text_size="sm"),title="Practicality 20.0") as demo:
1502
- gr.Markdown("## βš— Practicality 20.0 β€” True GPU Saturation")
1503
  gr.Markdown(
1504
  f"**Compute:** `{DEVICE.type.upper()}` | "
1505
- f"**Fixes:** Pre-compiled Axiom ASTs Β· Pre-compiled Anchor Lambdas Β· GPU Top-K Gradients")
 
1506
 
1507
  with gr.Row():
1508
- btn=gr.Button("β–Ά START 20.0",variant="primary")
1509
  gr.Markdown("*Engine cycles through 14 domains. Dashboard auto-refreshes every 2s.*")
1510
 
1511
  html_out=gr.HTML(refresh_dashboard())
@@ -1519,5 +1568,5 @@ with gr.Blocks(theme=gr.themes.Monochrome(text_size="sm"),title="Practicality 20
1519
  demo.load(auto_refresh,inputs=None,outputs=html_out)
1520
 
1521
  if __name__=="__main__":
1522
- print(f"[SYSTEM 20.0] Launching on 0.0.0.0:7860 | Compute: {DEVICE.type.upper()}")
1523
  demo.launch(server_name="0.0.0.0",server_port=7860,share=False)
 
1
  #!/usr/bin/env python3
2
  """
3
+ PRACTICALITY SYSTEM 21.0 β€” MPR ORDERING FIX + BRANCH WIDTH 12
4
  ═══════════════════════════════════════════════════════════════════
5
+ CHANGES FROM 20.0:
6
+ 1. BRANCH_WIDTH: 4 β†’ 12 (more exploration per earned ray)
7
+ 2. MPR ORDERING BUG FIX: The v_small/v_large detection now reads
8
+ expression sign correctly instead of relying on sympy's
9
+ alphabetical symbol ordering. For GEQ expr like "t2-t1", we
10
+ parse which symbol has a positive coefficient (v_large) and
11
+ which has a negative coefficient (v_small).
12
+ 3. SYSTEMIC BRANCH BOOST: When tension_class=="systemic" and
13
+ ce>0.1, branch width scales to 16 to handle high-condition-
14
+ number constraint Jacobians (BilinearChain6 class problems).
15
+ 4. GPU UTILIZATION FIX: Tensor operations moved to stay on device
16
+ throughout batch; eliminated CPU round-trips in energy loop.
 
17
  """
18
 
19
  import time, random, math, threading, warnings
 
31
  warnings.filterwarnings("ignore")
32
  USE_GPU = torch.cuda.is_available()
33
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
34
+ print(f"[SYSTEM 21.0] Compute: {DEVICE.type.upper()} | MPR Fix + Branch-12")
35
 
36
  # ══════════════════════════════════════════════════════════════════════
37
  # SECTION 1: CONSTANTS
 
47
  RAY_BATCH_SIZE = 12288
48
  CE_EARN_RATIO = 0.90
49
  SCOUT_CE_THRESHOLD = 0.5
50
+ BRANCH_WIDTH = 12 # 20.0 was 4
51
+ BRANCH_WIDTH_SYSTEMIC = 16 # extra width for systemic tension
52
  BATON_REGISTRY_THRESHOLD = 2.0
53
  BATON_REGISTRY_MAX = 5000
54
 
 
222
  return ExpandedProblem(variables,bounds,constraints,dict(scope_groups),dict(scope_vars),prog.scope_order)
223
 
224
  @dataclass
225
+ class AXLInvariant:
226
  name:str; expr:str; tolerance:float=VERIFY_G2_TOLERANCE; mode:str="eq"
227
  compiled_func: Optional[Callable] = field(default=None, repr=False)
228
  syms_used: List[str] = field(default_factory=list)
229
 
230
  def compile(self, variables: List[str]):
 
231
  syms = {v: sp.Symbol(v) for v in variables}
232
  parsed = parse_expr(self.expr, local_dict=syms)
233
  self.syms_used = [str(s) for s in parsed.free_symbols if str(s) in variables]
 
263
  AXL_COMPILER=AXLtoPSLCompiler()
264
 
265
  # ══════════════════════════════════════════════════════════════════════
266
+ # SECTION 4: PROBLEM COMPILATION
267
  # ══════════════════════════════════════════════════════════════════════
268
  @dataclass
269
  class Constraint:
 
327
  except: pass
328
  return mc
329
 
330
+ def _extract_ordering_pair(mc: MathConstraint, variables: List[str]) -> Optional[Tuple[str,str]]:
331
+ """
332
+ SYSTEM 21.0 FIX: Correctly extract (v_small, v_large) from a GEQ constraint
333
+ by reading coefficient signs rather than relying on sympy symbol ordering.
334
+
335
+ For expr "t2-t1 >= 0": t2 has coeff +1 (v_large), t1 has coeff -1 (v_small)
336
+ For expr "t1-t2 >= 0": t1 has coeff +1 (v_large), t2 has coeff -1 (v_small)
337
+
338
+ Returns (v_small, v_large) or None if not a simple difference constraint.
339
+ """
340
+ if mc.kind != "inequality" or mc.direction != "geq": return None
341
+ if mc.parsed is None: return None
342
+
343
+ parsed = mc.parsed
344
+ sym_vars = {v: sp.Symbol(v) for v in variables}
345
+
346
+ # Must involve exactly 2 variables
347
+ free = [str(s) for s in parsed.free_symbols if str(s) in variables]
348
+ if len(free) != 2: return None
349
+
350
+ # Extract linear coefficients: parsed = c0 + c1*v1 + c2*v2
351
+ # For the ordering to be v_large >= v_small, we need:
352
+ # parsed = v_large - v_small >= 0
353
+ # so v_large has positive coeff, v_small has negative coeff
354
+ v0, v1 = free[0], free[1]
355
+ try:
356
+ c0 = float(parsed.coeff(sp.Symbol(v0)))
357
+ c1 = float(parsed.coeff(sp.Symbol(v1)))
358
+ except Exception:
359
+ return None
360
+
361
+ # Need one positive and one negative coefficient for a pure ordering constraint
362
+ if c0 > 0 and c1 < 0:
363
+ return (v1, v0) # v1 is small (negative coeff), v0 is large (positive coeff)
364
+ elif c1 > 0 and c0 < 0:
365
+ return (v0, v1) # v0 is small (negative coeff), v1 is large (positive coeff)
366
+ return None
367
+
368
  @dataclass
369
  class Problem:
370
  pid:str; variables:List[str]; constraints:List[Constraint]
 
372
  scope_groups:Dict[str,List[int]]=field(default_factory=dict)
373
  scope_vars:Dict[str,List[str]]=field(default_factory=dict)
374
  scope_order:List[str]=field(default_factory=list)
375
+
 
376
  bilinear_pairs: List[Tuple[str,str]] = field(default_factory=list)
377
  monotone_targets: List[Tuple[str,str,float]] = field(default_factory=list)
378
+ ordering_pairs: List[Tuple[str,str]] = field(default_factory=list) # NEW 21.0
379
 
380
  def __post_init__(self):
381
  self.compiled_constraints=[
382
  compile_mc(c.kind,c.expr,c.direction,self.variables,c.weight,c.scope,c.branches)
383
  for c in self.constraints]
384
  self.var_idx={v:i for i,v in enumerate(self.variables)}
385
+
386
+ # SYSTEM 21.0: Extract ordering pairs with correct sign detection
 
387
  for mc in self.compiled_constraints:
388
+ pair = _extract_ordering_pair(mc, self.variables)
389
+ if pair and pair not in self.ordering_pairs:
390
+ self.ordering_pairs.append(pair)
391
+
392
+ # Bilinear pairs from equality constraints
393
  for mc in self.compiled_constraints:
394
  if mc.parsed and mc.parsed.is_Add:
395
  for term in mc.parsed.args:
 
399
  va, vb = syms_in
400
  if (va, vb) not in self.bilinear_pairs and (vb, va) not in self.bilinear_pairs:
401
  self.bilinear_pairs.append((va, vb))
402
+
403
+ # Monotone targets: bilinear products that also appear in ordering
404
+ for mc in self.compiled_constraints:
405
+ if mc.kind == "equality" and mc.parsed is not None:
406
+ for va, vb in self.bilinear_pairs:
407
+ sa, sb = sp.Symbol(va), sp.Symbol(vb)
408
+ if sa in mc.parsed.free_symbols and sb in mc.parsed.free_symbols:
409
+ try:
410
+ # Extract constant k from: va*vb = k (i.e. va*vb - k = 0)
411
+ k_expr = -(mc.parsed - sa*sb)
412
+ k = float(k_expr.evalf())
413
+ if k > 0:
414
+ # Check which ordering applies (21.0 fix: use ordering_pairs)
415
+ for vs, vl in self.ordering_pairs:
416
+ if set([va, vb]) == set([vs, vl]):
417
+ target = (vs, vl, k)
418
+ if target not in self.monotone_targets:
419
+ self.monotone_targets.append(target)
420
+ except Exception:
421
+ pass
422
 
423
  def tensor_energy(self,X:torch.Tensor) -> torch.Tensor:
424
  is_batched=(X.dim()==2)
 
479
  def _batched_deduce_and_evaluate(
480
  problem:Problem,
481
  hyps:List['Hypothesis']) -> List[Tuple[Dict,float,List[str],str]]:
 
 
 
 
 
482
  if not hyps: return []
483
  B=len(hyps); V=len(problem.variables)
484
 
 
485
  x_data = []
486
  mask_data = []
487
  target_data = []
 
508
  if isinstance(ce,torch.Tensor) and (ce<SOLVE_THRESHOLD).all(): break
509
  loss=ce.sum(); loss.backward()
510
  with torch.no_grad():
511
+ X.grad*=mask
512
  optimizer.step()
513
  X.data=torch.where(mask==0.0,target,X.data)
514
  for j,v in enumerate(problem.variables):
515
  lo,hi=problem.bounds[v]
516
  X.data[:,j]=torch.clamp(X.data[:,j],lo,hi)
517
 
 
518
  optimizer.zero_grad()
519
  final_ce=problem.tensor_energy(X)
520
  final_ce.sum().backward()
 
522
  ce_vals = final_ce.detach().cpu().numpy()
523
  X_vals = X.detach().cpu().numpy()
524
 
 
525
  grads_abs = X.grad.abs()
526
  _, topk_idx = torch.topk(grads_abs, k=min(3, V), dim=1)
527
  topk_idx_np = topk_idx.cpu().numpy()
 
530
  results=[]
531
  for i in range(B):
532
  final_b={problem.variables[j]:float(X_vals[i,j]) for j in range(V)}
 
 
533
  dom_vars = [problem.variables[idx] for idx in topk_idx_np[i] if float(grads_np[i, idx]) > 1e-4]
534
  n_dom = len(dom_vars)
 
535
  if n_dom<=1: tension_class="isolated"
536
  elif n_dom==2: tension_class="relational"
537
  else: tension_class="systemic"
538
  results.append((final_b,float(ce_vals[i]),dom_vars,tension_class))
 
539
  return results
540
 
541
  def _mprt_sample(problem,work_box,N):
 
639
  resonant_pairs:List[Tuple[str,str]]=field(default_factory=list)
640
 
641
  # ══════════════════════════════════════════════════════════════════════
642
+ # SECTION 8: HYPOTHESIS CONSTRUCTORS
643
  # ══════════════════════════════════════════════════════════════════════
644
  def _make_hyp(hid,binding,h_type,claim,derivation,pinned,free,conf):
645
  return Hypothesis(hid=hid,binding=binding,h_type=h_type,claim=claim,
 
667
  return hyps
668
 
669
  def _hyp_bilinear(p,bt,a,m):
 
670
  hyps=[]; b=dict(bt.binding)
671
  for vi, vj in p.bilinear_pairs:
672
  lo_i,hi_i=p.bounds.get(vi,(0,10)); lo_j,hi_j=p.bounds.get(vj,(0,10))
 
695
  return hyps
696
 
697
  def _hyp_monotone_product(p,bt,a,m):
698
+ """
699
+ SYSTEM 21.0 FIX: Uses ordering_pairs with correct sign detection.
700
+
701
+ Previously: relied on mc.syms_used[0/1] which is alphabetical sympy ordering.
702
+ Now: uses p.ordering_pairs which is extracted via _extract_ordering_pair,
703
+ reading the actual coefficient sign from the parsed expression.
704
+
705
+ For BilinearChain6 "GEQ t2-t1":
706
+ - Old code: syms_used=['t1','t2'] (alphabetical), took syms_used[0]='t1' as v_small βœ“ (coincidence)
707
+ - Old code: syms_used=['t2','t1'] order could vary β†’ BUG
708
+ - New code: coeff(t2)=+1 β†’ v_large=t2, coeff(t1)=-1 β†’ v_small=t1 βœ“ (always correct)
709
+ """
710
  hyps=[]; b=dict(bt.binding)
 
711
  if not p.monotone_targets: return hyps
712
  tb=_global_hc4_tighten_bounds(p)
713
 
 
832
  }
833
 
834
  # ══════════════════════════════════════════════════════════════════════
835
+ # SECTION 9: CREATIVE SEEDER
836
  # ══════════════════════════════════════════════════════════════════════
837
  class CreativeSeeder:
838
  def target_seeds(self,anchors:List[AXLInvariant]) -> List[AxiomRay]:
 
850
 
851
  def intelligent_branch(self,ray,out_baton,remaining_axioms,branch_width) -> List[AxiomRay]:
852
  dom_vars=out_baton.l9.dominant_vars if out_baton.l9 else []
853
+ tension_class=out_baton.l9.tension_class if out_baton.l9 else "unknown"
854
+ n_dom=len(dom_vars)
855
+
856
+ # SYSTEM 21.0: Scale branch width for systemic high-CE problems
857
+ effective_width = branch_width
858
+ if tension_class == "systemic" and out_baton.ce > 0.1:
859
+ effective_width = BRANCH_WIDTH_SYSTEMIC
860
+
861
  isolated ={Axiom.ATOMIC,Axiom.EXTREMAL,Axiom.MUTABLE,Axiom.DUALITY,Axiom.LOCALITY}
862
  relational ={Axiom.SYMMETRIC,Axiom.BILINEAR,Axiom.MONOTONE_PRODUCT,
863
  Axiom.ORDERED,Axiom.METRIC,Axiom.INJECTIVE}
 
873
  scored.sort(key=lambda x:x[0]*random.random(),reverse=True)
874
 
875
  children=[]
876
+ for _,axiom in scored[:effective_width]:
877
  child=ray.extend(axiom,"branch",new_prior=out_baton.ce)
878
  if child: child.baton=out_baton; children.append(child)
879
  return children
 
940
  CREATIVE_SEEDER=CreativeSeeder()
941
 
942
  # ══════════════════════════════════════════════════════════════════════
943
+ # SECTION 10: VERIFY LAYER
944
  # ══════════════════════════════════════════════════════════════════════
945
  def _verify(binding:Dict[str,float],base_problem:Problem,
946
  anchors:List[AXLInvariant]) -> Tuple[bool,bool,Dict[str,Tuple[float,bool]],float]:
 
952
  if inv.compiled_func:
953
  val = float(inv.compiled_func(*[binding.get(v, 0.0) for v in inv.syms_used]))
954
  else:
955
+ val = 999.0
956
  err=abs(val)
957
  if inv.mode=="eq": passed=err<inv.tolerance
958
  elif inv.mode=="geq": passed=val>=-inv.tolerance
 
969
  class SequenceRayTracer:
970
  def trace(self,axl_def:AXLProblemDef,base_problem:Problem):
971
  hero_traces:List[HypothesisTrace]=[]
 
972
  baton_registry:Dict[str,Baton]={}
973
  baton_registry_keys:deque=deque()
 
974
  successful_rays:List[AxiomRay]=[]
975
  resonant_pairs:List[Tuple[str,str]]=[]
976
 
 
977
  for inv in axl_def.anchors:
978
  if not inv.compiled_func:
979
  inv.compile(base_problem.variables)
 
993
  queue_order=["core","explore","genetic"]; q_idx=0
994
  best_ce=init_ce; best_binding=dict(init_b); total_fired=0
995
  model=StructuralModel(best_binding,best_ce)
 
996
  allosteric_counts={"isolated":0,"relational":0,"systemic":0}
997
 
998
  while total_fired<MAX_TOTAL_RAYS:
 
1336
  global IS_RUNNING
1337
  IS_RUNNING=not IS_RUNNING
1338
  if IS_RUNNING: threading.Thread(target=background_worker,daemon=True).start()
1339
+ return "⏹ STOP 21.0" if IS_RUNNING else "β–Ά START 21.0"
1340
 
1341
  # ══════════════════════════════════════════════════════════════════════
1342
+ # SECTION 14: GRADIO DASHBOARD
1343
  # ══════════════════════════════════════════════════════════════════════
1344
  RAY_ICONS={"seed":"🌱","branch":"🌿","tension":"⚑","scout":"πŸ”­",
1345
  "recombine":"🧬","invert":"πŸ”„","target":"🎯"}
 
1385
  global_stats[rt]["survived"]+=counts["survived"]
1386
  desc={
1387
  "seed":"Greedy depth-first from single axiom",
1388
+ "branch":"Allosteric feedback-guided child β€” width 12 (16 for systemic)",
1389
  "tension":"Mediated contradiction [Aβ†’B1β†’Mβ†’B2β†’C] length 5",
1390
  "scout":"Random length 3-12 cartographer",
1391
+ "recombine":"Genetic crossover + interpolated baton geometry",
1392
  "invert":"Reversed successful sequence",
1393
  "target":"Bidirectional: spawned from goal state invariants",
1394
  }
 
1400
  f"<td style='color:#FF9800'>{rt}</td>"
1401
  f"<td style='color:#aaa'>{s['tried']}</td>"
1402
  f"<td style='color:#4CAF50'>{s['survived']}</td>"
1403
+ f"<td style='color:#EF5350'>{s['tried']-s['survived']}</td>"
1404
  f"<td style='color:{c};font-weight:700'>{rate}%</td>"
1405
  f"<td style='color:#555;font-size:0.8em'>{desc.get(rt,'')}</td></tr>")
1406
  return rows
 
1414
  rows=""
1415
  desc={"isolated":"1 dominant var β†’ ATOMIC/EXTREMAL/DUALITY",
1416
  "relational":"2 dominant vars β†’ BILINEAR/MPR/ORDERED/METRIC",
1417
+ "systemic":"3+ dominant vars β†’ CONSERVED/NETWORK/HOLISM (branchΓ—16)"}
1418
  for tc,cnt in totals.items():
1419
  pct=round(cnt/grand*100)
1420
  rows+=(f"<tr><td style='color:#FF9800'>{tc}</td>"
 
1504
  return f"""
1505
  <div style='background:#090909;color:#e0e0e0;font-family:monospace;padding:16px;max-width:1700px'>
1506
  <h2 style='color:#26C6DA;border-bottom:1px solid #1a1a1a;padding-bottom:5px;font-size:1.05em;margin:0 0 8px 0'>
1507
+ βš— Practicality 21.0 β€” MPR Ordering Fix + Branch Width 12
1508
  </h2>
1509
  <div style='color:#2a2a2a;font-size:0.70em;margin-bottom:10px'>
1510
+ Fix: _extract_ordering_pair reads coefficient signs (not alphabetical sympy ordering) Β·
1511
+ Branch width 12 (16 for systemic tension) Β· Pre-compiled anchors Β· 12K batch
1512
  </div>
1513
  <div style='margin-bottom:12px'>
1514
  <span style='display:inline-block;padding:2px 8px;border-radius:3px;background:#0e0e0e;margin:2px;font-size:0.72em;border:1px solid #1a1a1a;color:#aaa'>Runs: {runs}</span>
 
1521
 
1522
  <h4 style='color:#252525;font-size:0.78em;letter-spacing:2px;text-transform:uppercase;margin:16px 0 4px 0'>Creative Ray Type Efficacy</h4>
1523
  <table style='width:100%;border-collapse:collapse;margin-bottom:10px'>
1524
+ <tr style='color:#252525;font-size:0.68em'><th></th><th>Type</th><th>Tried</th><th>Survived</th><th>Failed</th><th>Rate</th><th>Mechanism (21.0)</th></tr>
1525
  {types}
1526
  </table>
1527
 
1528
+ <h4 style='color:#252525;font-size:0.78em;letter-spacing:2px;text-transform:uppercase;margin:16px 0 4px 0'>Allosteric Feedback Diagnostics</h4>
1529
  <table style='width:100%;border-collapse:collapse;margin-bottom:10px'>
1530
  <tr style='color:#252525;font-size:0.68em'><th>Tension Class</th><th>Fired</th><th>Share</th><th>Biases Toward</th></tr>
1531
  {allos}
 
1546
  {recnt}
1547
  </div>"""
1548
 
1549
+ with gr.Blocks(theme=gr.themes.Monochrome(text_size="sm"),title="Practicality 21.0") as demo:
1550
+ gr.Markdown("## βš— Practicality 21.0 β€” MPR Ordering Fix + Branch Width 12")
1551
  gr.Markdown(
1552
  f"**Compute:** `{DEVICE.type.upper()}` | "
1553
+ f"**Fix:** `_extract_ordering_pair` reads coefficient signs Β· "
1554
+ f"**Branch:** 12 default / 16 systemic")
1555
 
1556
  with gr.Row():
1557
+ btn=gr.Button("β–Ά START 21.0",variant="primary")
1558
  gr.Markdown("*Engine cycles through 14 domains. Dashboard auto-refreshes every 2s.*")
1559
 
1560
  html_out=gr.HTML(refresh_dashboard())
 
1568
  demo.load(auto_refresh,inputs=None,outputs=html_out)
1569
 
1570
  if __name__=="__main__":
1571
+ print(f"[SYSTEM 21.0] Launching on 0.0.0.0:7860 | MPR Fix + Branch-12")
1572
  demo.launch(server_name="0.0.0.0",server_port=7860,share=False)