B3 B4 approved learning-panel gates and synthetic acceptance
This commit is contained in:
1 parent
ef7fe68833
commit
4d19c03080
12 files changed
+13106
No files matched your search
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"tests": 5,
|
||||
"cpu_seconds": 0.32417799999999997,
|
||||
"scope": "new synthetic B3 quantization/birth and B4 projection checks only",
|
||||
"code_sha256": {
|
||||
"tools/phase2_gate_math.py": "2befde586757268efed0b6173cc5ff778e1be0d74eefabbde68c3e5a6669f40c",
|
||||
"tools/test_phase2_gate_math.py": "dcb07cf9be1475c4285c23c043dbf4d1c2104f970f2b0177803d22a09869eeca",
|
||||
"tools/phase2_gates_34.py": "d3b6aed73faec855568ad407b04fe07f264750717b3b91e0aeee90b1d0d3a418",
|
||||
"tools/phase2_h1_topology.py": "f8c9b5d68d04b65a2f7015c2af79a303d4d1b0146899bac0ee229ce1381bbf2d"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"cpu_seconds_charged": 0.32417799999999997,
|
||||
"attempts": [
|
||||
{
|
||||
"name": "worker",
|
||||
"status": "PASS",
|
||||
"cpu_seconds": 0.32417799999999997
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
test_all_ties_are_within_group_error (__main__.GateMathTests) ... ok
|
||||
test_births_preserve_disconnected_equal_maxima (__main__.GateMathTests) ... ok
|
||||
test_midpoint_rounds_lower_including_shifted_origin (__main__.GateMathTests) ... ok
|
||||
test_perfect_order (__main__.GateMathTests) ... ok
|
||||
test_two_point_reversal (__main__.GateMathTests) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 5 tests in 0.033s
|
||||
|
||||
OK
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"command": [
|
||||
"/home/frank14f/optane/MeltMind/artifacts/gre24-reproduction-2026-11-15/environment/venv/bin/python",
|
||||
"tools/test_phase2_gate_math.py",
|
||||
"-v"
|
||||
],
|
||||
"returncode": 0,
|
||||
"stop_reason": null,
|
||||
"cpu_seconds": 0.32417799999999997,
|
||||
"wall_seconds": 0.35663707996718585,
|
||||
"peak_tree_rss_bytes": 53977088,
|
||||
"peak_process_count": 1,
|
||||
"output_disk_bytes_before_receipt": 8192,
|
||||
"max_poll_gap_seconds": 0.05106381402583793,
|
||||
"poll_target_seconds": 0.05,
|
||||
"reaped_orphan_cpu_seconds": 0.0,
|
||||
"supervision": "sampled process-tree monitoring; wait4 final CPU/HWM; overshoot retained as failure",
|
||||
"gpu_visible": false,
|
||||
"cuda_device": "",
|
||||
"numerical_threads": 1,
|
||||
"retry": false,
|
||||
"monitor_errors": 0,
|
||||
"last_monitor_error": null
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"command": [
|
||||
"/home/frank14f/optane/MeltMind/artifacts/gre24-reproduction-2026-11-15/environment/venv/bin/python",
|
||||
"tools/test_phase2_gate_math.py",
|
||||
"-v"
|
||||
],
|
||||
"limits": {
|
||||
"job_wall_seconds": 30,
|
||||
"job_cpu_seconds": 30,
|
||||
"total_cpu_seconds": 30,
|
||||
"tree_rss_bytes": 1073741824,
|
||||
"max_processes": 4,
|
||||
"disk_bytes": 104857600
|
||||
},
|
||||
"started_unix": 1794889990.1594443
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# B3/B4 已批小门执行定义
|
||||
|
||||
沿Claude1794887072已批Mold原规格及1794888554接续。完整纸面规格保存`references/2026-11-17/phase2-design/mold-b3-b4-b5-gates.md`。H1唯一队列已经启动;本两门使用CPU16/18,与H1的8–15及30–31分开,不改其来源或参数,不再请求用户go。B5另按同纸面规格接续,不混为本次已运行结果。
|
||||
|
||||
两门固定同一50件:原grouped fold0、100% learning角色;组件ID的UTF8 SHA256升序,取前50个不同组件,各取完整case字典序最小件。名单在各自contract.json于读真场前冻结,不以事件数、预测好坏或后见值挑件。一件一组件,组件等权与面板件等权一致。代码逐件复核角色及原缓存hash。每门总≤7200 worker/guard CPU秒,单worker≤7080秒、8GiB RSS、5GiB输出;分别CPU16/18,无GPU/新fit/新解码/重试。60秒保守setup计费并保留guard余量,实际worker、guard及保守费分列。
|
||||
|
||||
B3使用原tet图、原质量/Rg/ID及H1同一事件/匹配实现。原真场以秒为单位;T/t_set分别舍入到0.001格及偏半格,严格中点取较低值,再还原秒匹配。保留真事件、两扰动事件和所有局部极大出生平台。精确率/召回按面板事件TP/FP/FN汇总,并列四种空事件类别;任一扰动precision或recall<0.80、未定义,或原真事件件数<10,均暂停指标作普遍判优。缺件/异常也不宣布稳定。真场门通过后才执行同域EIK比较,否则明确not attempted。无独立出生位置配对实验;保存出生平台供复核,不把无限类当有限事件。该门仅检验时间记录精度扰动,不证明网格收敛或工业焊线。
|
||||
|
||||
B4用同50件全retained-tet、A单位节点权、冻结Df及T/t_set;完全相同Df聚组,以加权PAVA计算同势组内SSE和有序组均值SSE,核两者和与直接残差平方和一致。两项除以同一真值平方和,最后开根得到相对L2;同时保存组势值/权重/均值/最优单调映射。旧fold0/pool100 A只无标签推理,不重训;其与oracle在同节点域的学习面板结果按组件等权比较。oracle≥A则剪“只换此势时钟就能超A”;更低只保留可能性,非可部署效果、非排序因果份额。面板缺失或分母未定义则PARK(coverage),不以可计算子集代替完整门。
|
||||
|
||||
新增数学验收5项PASS,CPU0.324178秒:保序、全并列、两点逆序、含偏移零点的中点取低、断开且同高极大平台。没有重复旧纯数学或H1集成测试。运行根`artifacts/phase2-b3-gate-2026-11-17`与`artifacts/phase2-b4-gate-2026-11-17`。实际运行与完成以随后actual-start/guard/complete回执为准;本文件不将纸面规格写成执行结果。
|
||||
@@ -0,0 +1,15 @@
|
||||
# B3–B5 的便宜判别实验
|
||||
|
||||
2026-11-17,MoldAstra 给 Claude 和 MeltAstra 的纸面规格。每枝建议至多 2 worker CPU-h,运行和树状态由各自负责人登记。以下数值是待冻结的决策门槛,尚无本轮外测结果。[Claude 维护的研究树](https://gitea.frank14f.online/Frank14f/MeltMind/src/commit/bf0a6c0f/docs/claude/research-tree.md)
|
||||
|
||||
**B3 干域分裂能否稳定定位。** 在学习池按组件 ID 固定哈希顺序取不同组件的一件,至多 50 件;保存节点、边、体积和网格版本。先对真场和全域 EIK 用 H1 规格算干区合并。稳定性只测记录精度的扰动:把无量纲真 T 分别舍入至 0.001 的最近格点和偏移半格的最近格点(恰居中就取较低值),分别与原值的事件一对一匹配。对每件另记极大出生平台;可独立比较与有限且通过持续性门槛的消亡类相配的出生位置,使用同一距离门、把阶段门换成出生分位;无限类对应的末填另列。若两种扰动任一的合并 precision 或 recall <0.80,或原真场在至少 10 件有事件的条件未满足,就暂停把合并指标用作普遍模型判优。真场自身稳定时再报 EIK 对真场的同口径精确率、召回和定位误差;EIK 差可表明这个指标揭示基线缺陷,不能单独否决指标。保留空事件和异常网格。重开条件是取得独立时间分辨率或重剖参考。此门不评实际焊线,也不验证网格收敛。
|
||||
|
||||
**B4 固定 EIK 顺序允许多大时间误差。** 同一件、同一评价域及同一 A 的正权 w 上,取 y=T/t_set、s 为冻结 EIK 距离(若使用冻结 F,先核实同序同并列)。把完全相同的 s 聚成序组 j,记 Wⱼ=Σwᵢ、ȳⱼ=Σwᵢyᵢ/Wⱼ。离线用加权 PAVA 求使 ΣWⱼ(zⱼ−ȳⱼ)² 最小的非递减 z。精确恒等式为
|
||||
|
||||
min Σwᵢ(yᵢ−g(sᵢ))² = ΣⱼΣᵢ∈j wᵢ(yᵢ−ȳⱼ)² + min_{z 非递减} Σⱼ Wⱼ(ȳⱼ−zⱼ)²。
|
||||
|
||||
第一项是同势值无法区分的时间差,第二项是不同势值组的均值不能按序拟合而付出的代价。二者除以相同的 Σwᵢyᵢ² 后可相加;相对 L2 最后才开根。用该件全部评价真值拟合且在同域评价,这是给固定标量势的**事后误差下界**。残差可能包含并列、离散、标签误差、几何缺信息;最好映射的平段还会制造新的并列。该数既非可部署精度,也不能唯一识别压力机制或排序颠倒数。数学自检用完全保序、全势并列及两点逆序三例。与同件同域 A 比:若按正式分组规则汇总的 oracle 相对 L2 已 ≥ A,就剪掉“只给此势换时钟即可超 A”这枝;若低于 A,只保留可能性,同时给件级差异、并列项占比。新势、不同控制域或补充支路信息可构成重开条件。
|
||||
|
||||
**B5 局部双壁片的可审核充分条件。** 准许在一般四面体域里只认证一块有双壁代表的子域。候选两壁片可各自三角化;在共同二维三角参考片上取对应细分。用同一规则把参考片×[0,1] 的柱体分成共享面相容的四面体,按两壁对应顶点做分片仿射映射。核三项:(i) 所有像四面体有一致正定向且离退化有余量;(ii) 任意两个像四面体的交恰为其公共参考面、边、点的像,参考不邻接者内外均不得相交;(iii) 像区域完全包含于原模腔体,两端面落在指定不同实体壁面片。有限复形上 (i)+(ii) 给连续单射,由紧致性得同胚到其像。(iii) 排除穿过外部空气的假连接。局部正体积或仅验几根壁间弦都不足以推出三项。证明担保所构造的子片;薄隙精度仍取决于厚长比、坡度、曲率及流动物理。网格边界容差或相交检测无法判清时记未知;浮点通过只有数值支持。相邻认证片的接口另须逐面核实,未知区沿用原三维邻接。
|
||||
|
||||
先在合成板、折返和筋根负对照复核;之后最多 10 个由学习侧无标签预选的 Greif 件,只尝试少量候选子片。按原件体积报告已认证子片并集覆盖、穿空隙的接受数、无候选数和核验成本。真配对无独立标注则不报“零误判率”。若有一个确认的跨空隙假连接,立即剪掉该实现;若至少 6/10 件认证体积分数不到 0.20,将全件片层化暂存,只保留高可信局部附加输入;不足十件时单列成本停止及实际分母。重开条件是可核验的相对壁标注、较稳健的几何谓词或新候选生成法。已有合成件数据只验证此前的壁对实现。
|
||||
@@ -0,0 +1,53 @@
|
||||
"""B3 quantization/birth records and B4 weighted monotone projection."""
|
||||
import numpy as np
|
||||
from scipy.sparse import csr_matrix
|
||||
from scipy.sparse.csgraph import connected_components
|
||||
|
||||
|
||||
def quantize_lower_tie(values,step=.001,offset=0.):
|
||||
y=np.asarray(values,dtype=np.float64)
|
||||
if not np.isfinite(y).all() or not np.isfinite([step,offset]).all() or step<=0:raise ValueError('Invalid quantization input')
|
||||
q=(y-offset)/step;lo=np.floor(q)
|
||||
return (lo+((q-lo)>.5))*step+offset
|
||||
|
||||
|
||||
def monotone_projection(potential,target,weights):
|
||||
s=np.asarray(potential,dtype=np.float64);y=np.asarray(target,dtype=np.float64);w=np.asarray(weights,dtype=np.float64)
|
||||
if s.ndim!=1 or not len(s) or s.shape!=y.shape or s.shape!=w.shape or not np.isfinite([s,y,w]).all() or np.any(w<=0):raise ValueError('Projection domain mismatch')
|
||||
distinct,inverse=np.unique(s,return_inverse=True);W=np.bincount(inverse,weights=w);means=np.bincount(inverse,weights=w*y)/W
|
||||
block_means=[];block_weight=[];block_length=[]
|
||||
for mean,weight in zip(means,W):
|
||||
block_means.append(float(mean));block_weight.append(float(weight));block_length.append(1)
|
||||
while len(block_means)>1 and block_means[-2]>block_means[-1]:
|
||||
weight=block_weight[-2]+block_weight[-1]
|
||||
mean=(block_weight[-2]*block_means[-2]+block_weight[-1]*block_means[-1])/weight
|
||||
length=block_length[-2]+block_length[-1]
|
||||
block_means[-2:]=[mean];block_weight[-2:]=[weight];block_length[-2:]=[length]
|
||||
fitted=np.repeat(block_means,block_length);prediction=fitted[inverse]
|
||||
within=float(np.sum(w*(y-means[inverse])**2));between=float(np.sum(W*(means-fitted)**2))
|
||||
direct=float(np.sum(w*(y-prediction)**2));denom=float(np.sum(w*y*y))
|
||||
if not np.isclose(within+between,direct,rtol=1e-10,atol=1e-12*max(denom,1.)):raise ValueError('PAVA decomposition identity failed')
|
||||
info=dict(nodes=len(y),potential_groups=len(distinct),fitted_blocks=len(block_means),within_tie_SSE=within,
|
||||
between_order_SSE=between,total_SSE=direct,denominator=denom,
|
||||
normalized_tie=within/denom if denom>0 else None,normalized_order=between/denom if denom>0 else None,
|
||||
relative_l2=float(np.sqrt(direct/denom)) if denom>0 else None,
|
||||
tie_share=within/direct if direct>0 else None,deployable=False)
|
||||
return info,dict(potential=distinct,group_weights=W,group_mean=means,fitted=fitted)
|
||||
|
||||
|
||||
def birth_platforms(field,mass,raw,points,adjacency):
|
||||
s=np.asarray(field,dtype=np.float64);m=np.asarray(mass,dtype=np.float64);n=len(s)
|
||||
src=np.repeat(np.arange(n),np.diff(adjacency.indptr));dst=adjacency.indices
|
||||
equal=s[src]==s[dst]
|
||||
ties=csr_matrix((np.ones(np.count_nonzero(equal)),(src[equal],dst[equal])),shape=(n,n))
|
||||
count,labels=connected_components(ties,directed=False)
|
||||
rejected=np.zeros(count,bool);rejected[labels[src[s[dst]>s[src]]]]=True
|
||||
order=np.argsort(labels,kind='stable');bounds=np.r_[0,np.flatnonzero(np.diff(labels[order]))+1,n];out=[]
|
||||
for lo,hi in zip(bounds[:-1],bounds[1:]):
|
||||
ids=order[lo:hi];g=labels[ids[0]]
|
||||
if rejected[g]:continue
|
||||
center=np.sum(points[ids]*m[ids,None],axis=0)/m[ids].sum();d=np.linalg.norm(points[ids]-center,axis=1)
|
||||
rep=int(ids[np.lexsort((raw[ids],d))[0]])
|
||||
out.append(dict(birth_min_raw_id=int(raw[ids].min()),representative_raw_id=int(raw[rep]),nodes=len(ids),
|
||||
volume_mass=float(m[ids].sum()),scalar=float(s[rep]),position=list(map(float,points[rep]))))
|
||||
return sorted(out,key=lambda r:r['birth_min_raw_id'])
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Approved B3/B4 learning-only gates, distinct components, no new models."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import numpy as np
|
||||
import joblib
|
||||
from scipy.sparse import csr_matrix
|
||||
from threadpoolctl import threadpool_limits
|
||||
from phase2_h1_worker_v2 import sha,checked,save
|
||||
from phase2_h1_topology import graph,events,match
|
||||
from phase2_gate_math import monotone_projection,quantize_lower_tie,birth_platforms
|
||||
from r4bc_guard import supervise
|
||||
|
||||
BASE=Path('/home/frank14f/optane/MeltMind')
|
||||
|
||||
|
||||
def read(p):return json.loads(Path(p).read_text())
|
||||
|
||||
|
||||
def prepare(acceptance):
|
||||
a=read(acceptance)
|
||||
if a['status']!='PASS':raise ValueError('Gate synthetic acceptance missing')
|
||||
old=BASE/'artifacts/r4bc-execution-2026-11-16/contract.json';c=read(old)
|
||||
candidates={}
|
||||
for r in c['parts']:
|
||||
role=next(x for x in r['assignments'] if x['fold']==0)
|
||||
if role['role']=='learning' and '100' in role['learning_pools']:candidates.setdefault(r['component_id'],[]).append(r)
|
||||
components=sorted(candidates,key=lambda x:(hashlib.sha256(x.encode()).hexdigest(),x))[:50]
|
||||
rows=[min(candidates[g],key=lambda r:r['case']) for g in components]
|
||||
if len(rows)!=50 or len({r['component_id'] for r in rows})!=50:raise ValueError('Expected 50 distinct learning components')
|
||||
modelpath=BASE/'artifacts/r4bc-execution-2026-11-16/models-terminal.json'
|
||||
model=next(m for m in read(modelpath)['models'] if m['arm']=='A' and m['fold']==0 and m['pool']==100)
|
||||
source={str(old):sha(old),str(modelpath):sha(modelpath),str(acceptance):sha(acceptance)}
|
||||
for p,h in a['code_sha256'].items():checked(p,h)
|
||||
code={f'tools/{n}.py':sha(BASE/f'tools/{n}.py') for n in ['phase2_gates_34','phase2_gate_math','phase2_h1_topology','phase2_h1_worker_v2','phase2_residual_math','r4bc_guard','s2_recovery_supervisor','s2_recovery_monitoring']}
|
||||
for name,cpu in [('B3',16),('B4',18)]:
|
||||
root=BASE/f'artifacts/phase2-{name.lower()}-gate-2026-11-17';root.mkdir(exist_ok=False)
|
||||
save(root/'contract.json',dict(version='phase2-'+name+'-gate-v1',gate=name,authorizing_ruling='1794887072.921849',
|
||||
b1_main_review='1794888554.440209',parts=rows,code_sha256=code,source_sha256=source,baseline_model=model,
|
||||
selection='fold0/pool100 learning; SHA256(component_id UTF8) ascending; lexicographically first case in each; first50',
|
||||
worker_cpu=cpu,cpu_cap_seconds=7200,worker_cap_seconds=7080,reserved_setup_guard_seconds=120,
|
||||
rss_bytes=8*1024**3,disk_bytes=5*1024**3,new_models=0,new_decodes=0,gpu=False,retry=False,
|
||||
thresholds=dict(grid_step=.001,half_grid_offset=.0005,min_precision=.80,min_recall=.80,min_eventful_parts=10),
|
||||
B4_domain='full retained tet nodes; unit positive weights exactly as A training; existing fold0/pool100 A inference on the same learning parts',
|
||||
failure_policy='retain each exception; missing panel parts prevent PASS/pruning conclusions; no replacement',
|
||||
scope='diagnostic learning-side gate; no test targets, no deployable calibration'))
|
||||
print(root,flush=True)
|
||||
|
||||
|
||||
def config(root):
|
||||
c=read(root/'contract.json')
|
||||
for p,h in {**c['source_sha256'],**c['code_sha256']}.items():checked(p,h)
|
||||
for r in c['parts']:
|
||||
role=next(a for a in r['assignments'] if a['fold']==0)
|
||||
if role['role']!='learning' or '100' not in role['learning_pools']:raise PermissionError('Gate attempted held-out part')
|
||||
return c
|
||||
|
||||
|
||||
def array(row,name):
|
||||
c=row['v5_cache'];return np.load(checked(Path(c['output'])/(name+'.npy'),c['output_sha256'][name+'.npy']),allow_pickle=False)
|
||||
|
||||
|
||||
def geometry(row):
|
||||
p=row['preparation'];d=Path(p['preparation_root']);meta=read(checked(d/'result.json',p['result_sha256']))
|
||||
with np.load(checked(d/'geometry.npz',p['output_sha256']['geometry.npz']),allow_pickle=False) as z:
|
||||
x=z['points_raw'].copy();tet=z['tetra'].copy();raw=z['raw_node_ids'].copy()
|
||||
if not np.array_equal(raw,array(row,'raw_ids')):raise ValueError('Gate raw IDs differ')
|
||||
return x,raw,array(row,'mass'),graph(x,tet),float(meta['scales']['Rg'])
|
||||
|
||||
|
||||
def totals(rows,key):
|
||||
items=[r[key] for r in rows];tp=sum(x['TP'] for x in items);fp=sum(x['FP'] for x in items);fn=sum(x['FN'] for x in items)
|
||||
distances=[d for x in items for d in x['matched_distance_over_Rg']];empty={}
|
||||
for item in items:empty[item['empty_class']]=empty.get(item['empty_class'],0)+1
|
||||
return dict(TP=tp,FP=fp,FN=fn,precision=tp/(tp+fp) if tp+fp else None,recall=tp/(tp+fn) if tp+fn else None,
|
||||
median_distance_over_Rg=float(np.median(distances)) if distances else None,matched=len(distances),empty_classes=empty)
|
||||
|
||||
|
||||
def run_b3(root,c):
|
||||
rows=[];failures=[];start=time.process_time();dest=root/'parts';dest.mkdir(exist_ok=False)
|
||||
for r in c['parts']:
|
||||
out=dest/r['case'];out.mkdir()
|
||||
save(out/'access.json',dict(role='fold0_learning100',seconds_sha256=r['v5_cache']['output_sha256']['seconds.npy']))
|
||||
try:
|
||||
x,raw,m,a,rg=geometry(r);truth=array(r,'seconds');scale=r['preparation']['t_set'];ref=events(truth,m,raw,x,a)
|
||||
save(out/'truth-events.json',ref);save(out/'birth-platforms.json',birth_platforms(truth,m,raw,x,a))
|
||||
info=dict(case=r['case'],component_id=r['component_id'],nodes=len(raw),edges=a.nnz//2,volume=float(m.sum()),Rg=rg,true_events=len(ref['events']))
|
||||
for label,offset in [('grid',0.),('half_grid',.0005)]:
|
||||
field=quantize_lower_tie(truth/scale,.001,offset)*scale;pred=events(field,m,raw,x,a)
|
||||
info[label]=match(ref,pred,a,rg);save(out/(label+'-events.json'),pred)
|
||||
np.savez_compressed(out/'geometry.npz',points=x,raw_ids=raw,mass=m,indices=a.indices,indptr=a.indptr,data=a.data,rg=rg)
|
||||
save(out/'result.json',info);rows.append(info)
|
||||
except Exception as exc:
|
||||
failure=dict(case=r['case'],type=type(exc).__name__,message=str(exc));failures.append(failure);save(out/'failure.json',failure)
|
||||
save(root/'progress.json',dict(phase='TRUE_FIELD_STABILITY',complete=len(rows),failures=len(failures),cpu_seconds=time.process_time()-start))
|
||||
stability={key:totals(rows,key) for key in ('grid','half_grid')};eventful=sum(r['true_events']>0 for r in rows)
|
||||
good=not failures and len(rows)==50 and eventful>=10 and all(t[k] is not None and t[k]>=.8 for t in stability.values() for k in ('precision','recall'))
|
||||
save(root/'stability-gate.json',dict(pass_gate=good,eventful_parts=eventful,planned=50,complete=len(rows),failures=failures,metrics=stability))
|
||||
eik=[]
|
||||
if good:
|
||||
for r in c['parts']:
|
||||
out=dest/r['case']
|
||||
with np.load(out/'geometry.npz',allow_pickle=False) as z:
|
||||
raw=z['raw_ids'];x=z['points'];m=z['mass'];rg=float(z['rg']);a=csr_matrix((z['data'],z['indices'],z['indptr']),shape=(len(raw),len(raw)))
|
||||
pred=events(array(r,'Vf')*r['preparation']['t_set'],m,raw,x,a)
|
||||
score=match(read(out/'truth-events.json'),pred,a,rg)
|
||||
save(out/'eik-events.json',dict(events=pred,match=score));eik.append(dict(case=r['case'],eik=score))
|
||||
save(root/'result.json',dict(status='COMPLETE',gate='B3',decision='METRIC_STABLE_ON_THIS_PANEL' if good else 'PARK_UNIVERSAL_MODEL_JUDGEMENT',
|
||||
eventful_parts=eventful,stability=stability,rows=rows,failures=failures,EIK=totals(eik,'eik') if eik else None,
|
||||
EIK_attempted=good,reopen='independent temporal resolution or remesh reference',cpu_seconds=time.process_time()-start,
|
||||
limitations=['learning panel only','precision perturbation not remesh convergence','no weld/airtrap truth']))
|
||||
|
||||
|
||||
def run_b4(root,c):
|
||||
model=c['baseline_model'];baseline=joblib.load(checked(model['model_path'],model['model_sha256']))
|
||||
rows=[];failures=[];start=time.process_time();dest=root/'parts';dest.mkdir(exist_ok=False)
|
||||
with threadpool_limits(1):
|
||||
for r in c['parts']:
|
||||
out=dest/r['case'];out.mkdir();save(out/'access.json',dict(role='fold0_learning100',target_sha256=r['v5_cache']['output_sha256']['target.npy']))
|
||||
try:
|
||||
y=array(r,'target');s=array(r,'Df');x=np.asarray(array(r,'features'),dtype=np.float32)
|
||||
if len(y)!=r['nodes'] or x.shape!=(len(y),19):raise ValueError('A full node domain mismatch')
|
||||
info,curve=monotone_projection(s,y,np.ones(len(y)));pred=np.asarray(baseline.predict(x),dtype=np.float64)
|
||||
denominator=float(np.sum(y*y));ae=float(np.sqrt(np.sum((pred-y)**2)/denominator)) if denominator>0 else None
|
||||
result=dict(case=r['case'],component_id=r['component_id'],A_relative_l2=ae,**info)
|
||||
np.savez_compressed(out/'monotone-map.npz',**curve);save(out/'result.json',result);rows.append(result)
|
||||
except Exception as exc:
|
||||
failure=dict(case=r['case'],type=type(exc).__name__,message=str(exc));failures.append(failure);save(out/'failure.json',failure)
|
||||
save(root/'progress.json',dict(complete=len(rows),failures=len(failures),cpu_seconds=time.process_time()-start))
|
||||
defined=[r for r in rows if r['relative_l2'] is not None and r['A_relative_l2'] is not None]
|
||||
oracle=float(np.mean([r['relative_l2'] for r in defined])) if defined else None;aa=float(np.mean([r['A_relative_l2'] for r in defined])) if defined else None
|
||||
decision='PARK_COVERAGE' if len(defined)!=50 or failures else 'PRUNE_ONLY_CLOCK_CAN_BEAT_A' if oracle>=aa else 'RETAIN_POSSIBILITY_ONLY'
|
||||
save(root/'result.json',dict(status='COMPLETE',gate='B4',decision=decision,component_equal_oracle_l2=oracle,
|
||||
component_equal_A_l2=aa,rows=rows,failures=failures,cpu_seconds=time.process_time()-start,
|
||||
interpretation='posthoc lower bound for this fixed potential/domain/positive weights/monotone map class; not causal ordering share or deployable calibration',
|
||||
reopen='new potential, different control domain, or additional branch information'))
|
||||
|
||||
|
||||
def supervise_gate(root):
|
||||
c=config(root);os.sched_setaffinity(0,[c['worker_cpu']]);start=time.process_time()
|
||||
if (root/'actual-start.json').exists():raise FileExistsError('No duplicate gate')
|
||||
save(root/'actual-start.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),main_review=c['authorizing_ruling']))
|
||||
result=supervise([sys.executable,'tools/phase2_gates_34.py','worker',str(root)],root/'guard',
|
||||
dict(cpu_seconds=c['worker_cap_seconds'],wall_seconds=c['worker_cap_seconds'],rss_bytes=c['rss_bytes'],disk_bytes=c['disk_bytes']))
|
||||
guard_cpu=time.process_time()-start;total=result['cpu_seconds']+guard_cpu
|
||||
status='PASS' if result['status']=='PASS' and total+60<=7200 and (root/'result.json').exists() else 'STOPPED'
|
||||
save(root/'complete.json',dict(status=status,worker=result,guard_cpu_seconds=guard_cpu,setup_charge_seconds=60,
|
||||
cumulative_charge_seconds=total+60,scientific_gate_pass=None if status!='PASS' else read(root/'result.json')['decision'],retry=False))
|
||||
return 0 if status=='PASS' else 1
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('mode',choices=['prepare','supervise','worker']);p.add_argument('path',type=Path);a=p.parse_args()
|
||||
if a.mode=='prepare':prepare(a.path)
|
||||
elif a.mode=='supervise':raise SystemExit(supervise_gate(a.path))
|
||||
else:
|
||||
c=config(a.path);(run_b3 if c['gate']=='B3' else run_b4)(a.path,c)
|
||||
@@ -0,0 +1,25 @@
|
||||
import unittest
|
||||
import numpy as np
|
||||
from scipy.sparse import csr_matrix
|
||||
from phase2_gate_math import monotone_projection,quantize_lower_tie,birth_platforms
|
||||
|
||||
|
||||
class GateMathTests(unittest.TestCase):
|
||||
def test_perfect_order(self):
|
||||
r,_=monotone_projection([1,2,3],[2,4,7],[1,1,1]);self.assertEqual(r['total_SSE'],0)
|
||||
def test_all_ties_are_within_group_error(self):
|
||||
r,z=monotone_projection([1,1,1],[1,2,5],[1,2,1]);self.assertEqual(r['between_order_SSE'],0)
|
||||
self.assertAlmostEqual(r['within_tie_SSE'],9.);self.assertAlmostEqual(z['fitted'][0],2.5)
|
||||
def test_two_point_reversal(self):
|
||||
r,z=monotone_projection([0,1],[3,1],[1,3]);self.assertEqual(r['within_tie_SSE'],0)
|
||||
self.assertAlmostEqual(r['between_order_SSE'],3.);np.testing.assert_array_equal(z['fitted'],[1.5,1.5])
|
||||
def test_midpoint_rounds_lower_including_shifted_origin(self):
|
||||
np.testing.assert_array_equal(quantize_lower_tie(np.array([.0005,.0015]),.001,0),[0.,.001])
|
||||
self.assertEqual(float(quantize_lower_tie(np.array([0.]),.001,.0005)[0]),-.0005)
|
||||
def test_births_preserve_disconnected_equal_maxima(self):
|
||||
a=csr_matrix((np.ones(4),([0,1,1,2],[1,0,2,1])),shape=(3,3));x=np.c_[np.arange(3),np.zeros((3,2))]
|
||||
r=birth_platforms(np.array([2,1,2]),np.ones(3),np.arange(10,13),x,a)
|
||||
self.assertEqual([v['birth_min_raw_id'] for v in r],[10,12])
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user