Freeze approved B15 fixed tet-speed supervised solver gate
This commit is contained in:
1 parent
47c85a8a14
commit
7a91633244
7 files changed
+108854
No files matched your search
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"tests": 7,
|
||||
"test_sha256": "46240d32fdf5b811ecfb55748a24f16355ccbd5929ffcefd1eb7f20a678eeddd",
|
||||
"code_sha256": {
|
||||
"tools/phase2_b15_math.py": "4549f1139fd90689f50c9156a80b9a4c173a49c741678efb66a14240f13dbc5d",
|
||||
"tools/phase2_b15_gate.py": "1419e209fb7422ee13cfc58d429bcba1945e4504d3ba7a5d52bebabecef36e0b",
|
||||
"tools/r4bc_common.py": "27543fff987975ece767167f9771e6621c825035a053805604e4a696794dfcbd",
|
||||
"tools/s2_recovery_supervisor.py": "f563ca3c2665f5baf0c04f296616e4640423a59b815fbb00479af0f29e57a919",
|
||||
"tools/s2_recovery_monitoring.py": "442c2a9c75e8c00b30a8f2e91cb52d87c466b19a80aea9128b10c021e61b922e",
|
||||
"tools/s2_models/features.py": "3b34ae61cf8012ebd58b7505a73d7aa43d8ee1890ac54f98d7917b67887a45a4",
|
||||
"tools/s2_custody_statistics.py": "188565801f6901d0192f79aec0889e632501e672a4149d76d1835efbb9b45447",
|
||||
"tools/s2_models/objectives.py": "5b6527a45f08690055d572335470ce5979e8bb86e1cab00de594f79ae21316b1",
|
||||
"tools/r4bc_guard.py": "437a756ddf10b125dce450f463e76e28df52724f8c5766e0a989dfa536805628",
|
||||
"tools/s2_custody_common.py": "588c646101be0d50f505f9a12a1c98361aa3437c8c594eecb7321831f717a741",
|
||||
"tools/freeze_g1_components.py": "d0cee60d95243ac2c59ef3f2244ba818315718c4e3d1895f2f9f064f1f7f5ecd",
|
||||
"tools/gre24_models.py": "53b6fee8b700b9b982b06d29908ce2ce23e0c57512c46dbf74b2aade79e3ac3a",
|
||||
"tools/gre24_features_v2.py": "7dcd5ac218ffdc1ca149edcd87e8658fb3c59e18c0fb9ce47985c7f1357d2cdf",
|
||||
"tools/boundary_distance.py": "a45c1cbce92521a96eb814913b4f465b926c0b3883932ab0b7c37d11db113ed7",
|
||||
"tools/phase2_h1_worker_v2.py": "1543df85b615bb69b79bacd572074a7c77ae19dab110197601573a7e5805ed20",
|
||||
"tools/phase2_residual_math.py": "ffbd9624dec79bdaabf95244fe87209055908f31a977e73ea4377045d6f8fe62",
|
||||
"tools/phase2_fixed_io.py": "ea17fdfc7508f3f980e3cdf69534b1eb8ceb8a8e469c32451b2d5e16d0ada575",
|
||||
"tools/phase2_b1213_features.py": "d8e975b0a5362be7ff00fbf554f2b438b54af1b6b95f8993e7c2beae77f2c8f2",
|
||||
"tools/phase2_b12_math.py": "5465b34be5578cc62a7afc67e3cee3cd489ebb75ce6622a3fa320d1b81196c57",
|
||||
"tools/o1_v2.py": "7bfc81d820a1be7d40b97b2c0b65a616812cb7615b99d80c4ac589788282c291",
|
||||
"tools/o1_partition.py": "5e7dbf97604b9ea9646113a9847e7232020e5f9248fad388177c32ae2a7117da",
|
||||
"tools/o1_prepare.py": "1a695477ee6605d75e7e991205e3e6a49a0907a7733491af8d2771c7bc6a5c23",
|
||||
"tools/gre24_features.py": "92bca4d348f31246c2e931949e2ca38103881b1b784a621a42044db56a460026",
|
||||
"tools/audit_samples.py": "a3daf70ec3bcb77bf46d9dc4887d552cf7c422117880a169969780012278cd70",
|
||||
"tools/phase2_b1213_gate.py": "d5a023749e9d8bb6e04a2a2cbdbb8f0d9568924c534f36102d06707859853e10"
|
||||
},
|
||||
"real_parts_executed": false,
|
||||
"gpu": false,
|
||||
"setup_cpu_in60second_reserve": true
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,11 @@
|
||||
# B15 approved fixed one-fold execution
|
||||
|
||||
Claude1794901850 approves Mold specification6c33da33 as written, after B14, <=7200 workerCPU-seconds/single launch/no retry. B14 is terminal at its fixed-ten cost gate; it did not fit or score. This does not authorize B13-E1/E2 or another B14 attempt.
|
||||
|
||||
Independent CPU28 queue; original learning320/validation111, original A baseline, one XGB100/depth8/.1/seed0. Learning target is negative log norm of FP64 P1 gradient of u=T/t_set in xi=(x−mass centre)/Rg. Geometry kappa2<=1e8; source-containing tet, invalid arrival, numerical plateau and invalid gradient masks preserved separately. Recording resolution unknown:delta0/numerical ties only. SHA256 length-prefixed caseID+original uint64 tetID fixes at most4096 samples per learning part before target access; no resampling. Weights physicalV/pi, global mean1. No clipping, epsilon speed, target infill or validation supervision mask.
|
||||
|
||||
Exactly columns4:19 of original A19, dropping F plus its three gradient columns. Frozen gre24_features_v2.COLUMNS and spatial_moment(g,di) establish original column identity and Di-filtered moment neighborhoods; average four vertices per tet. No original F/Df-dependent feature is introduced to the15-column fit.
|
||||
|
||||
Predict exp(logspeed) on every original validation tet, require positive finite speed and representable square; use original R4(a) tetFIM on normalized xi, original gates and100000 iteration limit, unchanged coordinate/speed scaling rule and convergence tests. Strict full-node volume CDF preserves ties; original fold0 learning c gives normalized T, no validation time calibration. All original tets retained; failed/incomplete predictions park the gate without dropping hard parts.
|
||||
|
||||
Preparation subcap1500CPU-s, first10 cost projection1.25 times node-scaled measured cost, perpart30CPU/60wall. Fit1500, prediction3600, score180, all including guards/setup constrained by7200 total with120 drain reserve; RSS8GiB/output5GiB. All geometry/sampling fixed then Git barrier before learning targets; model frozen before prediction; predictions+scorer fixed before validation scores. Original B12 strict OR gate unchanged; additional Kendall diagnostic does not select model. No test labels or GPU. Seven CPU synthetic checks PASS; no execution claim until real receipts.
|
||||
@@ -0,0 +1,24 @@
|
||||
# B15 · 学习局部传播代价,保留四面体求解器
|
||||
|
||||
MoldAstra,2026-11-17,供 Claude 与 MeltAstra。纸面规格,执行在 B14 之后。一折检验的问题是:从学习件到达时间提取的局部传播速度,能否仅由新件几何预测,并通过相同的数值求解器改善填充顺序和时间?[Claude 分工](https://arcticnimbus.slack.com/archives/C0C78UFKGRM/p1794901060901129) · [R4(a) 求解口径](https://drive.google.com/file/d/16do4F5lLl2ct2NXm2nAfUd1rWKmNOVeq/view)
|
||||
|
||||
### 速度监督只来自学习角色
|
||||
|
||||
令 ξ=(x−x̄)/Rg、u=T/t_set。对原 retained tet K 的四顶点取 E 三行为 (ξⱼ−ξ₀)ᵀ,解 Eg=(u₁−u₀,u₂−u₀,u₃−u₀)ᵀ。g 是 P1 单元梯度;无量纲速度标签为 a*=1/‖g‖₂=(t_set/Rg)/‖∇ₓT‖₂。物理速度单位为长度/时间,若需还原乘 Rg/t_set。用 FP64 求解并以 y=−log‖g‖₂ 作回归目标。单位从毫米换成米时 ξ 和 y 应不变。仿射 u=2ξ₁ 给 a*=1/2。
|
||||
|
||||
显式存两个掩码。**几何掩码**核原网格 ID、正体积、有限输入、正 Rg 与 t_set,及 FP64 的 κ₂(E)≤10⁸(建议的数值质量门)。**监督掩码**仅在学习侧生成:四顶点须有有效首次到达记录,排除含任何浇口源点的单元以避开点源奇性;若四点时间跨度 ≤max(δ,64ε₆₄·max(1,maxⱼ|uⱼ|)),记平台或不可分辨。δ 是有独立元数据时的无量纲时间记录分辨率,未知取 0 并记录“仅检查数值并列”。求解后另核 ‖g‖ 有限且严格正。时刻并列的部分顶点不必使整单元无效。逐因统计样本及其体积,区分记录精度、源邻域和几何问题。禁止裁剪目标、给梯度加 ε、把平台当零速或拿相邻真值补标签。斜率很小但通过门的样本按原值入模。监督掩码绝不作为几何预测特征。
|
||||
|
||||
### 从几何预测到整件解码
|
||||
|
||||
1. **只用 A 中不依赖旧 Df 的 15 列。** 去掉全件旧分位 F 和由它生成的三列梯度方向,留下浇口距 Di* 及方向 4 列、物理 Dw/Dw* 及方向 5 列、空间矩 6 列。空间矩邻域按 Di 筛选,须以缓存源码核实列来源。每列取四顶点算术均值作为单元输入,记录原单位、列序与哈希。本选择使新介质在部署时不必先算旧 Df;A 的原 19 列基线沿用。两者的差同时包括输入、监督目标、空间求解和解码的变化。
|
||||
2. **一套固定回归器。** fold0/100% learning,拟合一次平方损失 XGBoost 回归 y,100 棵、深 8、学习率 0.1、seed 0,其他参数沿 A。为使标签产生与拟合可在 2 CPU-h 内预估成本,建议每件按稳定哈希 SHA-256(case ID 和原 tet ID,定长或长度前缀编码)排序,在读标签前固定最多 4096 个 tet,再施加监督掩码,不补抽。训练权重取 |K|/π,π=min(1,4096/N_tet),在有效行整体归一至均值 1;这是对有效域体积加权目标的抽样近似。每件报抽样覆盖与有效分母。没有监督标签的源邻单元同样需要在推理时得到预测。
|
||||
3. **只凭几何对整个验证件预测。** 对每个单元算 â_K=exp(ŷ_K);源邻区和可能的平台也走同一回归器。无验证/测试真 T、梯度、掩码或真实结束时间可供预测。有限正值、平方张量及转成实际求解精度后均须可表示;溢出、下溢、无效几何或不可达分量记整件失败,不剪值、不删 tet 后冒充原域。复用 R4(a) 相同源集、tetFIM 版本、更新、收敛和停止条件。新速度已是**单元常数**,在 ξ 坐标上传 D_K=â_K²I,不再从顶点平均或复用原 Dw 的全壁回退。若库在物理 x 上运行,同一无量纲势应传 (Rg·â_K)²I;任何内部坐标变换按 R4(a) 同比例变换速度,防止重复缩放。保留求解收敛与耗时收据。
|
||||
4. **先求顺序,再标秒。** 得到所有节点的数值传播势 s,源值为零。由整件节点集总体积算严格分位 Uᵢ=Σmⱼ1[sⱼ<sᵢ]/Σmⱼ,保留并列;最终 T̂ᵢ=t_set·c·Uᵢ。c 只用该学习池 retained-tet 结束时间比,沿 H1 的组件内件均值、组件间等权规则,与速度标签抽样无关。若已有相同输入及学习名单的 c、旧 EIK 分数可作对照,直接复用。用于评价的是完整预测冻结后的固定查询。禁止用验证标签定尺度、速度上下界或调求解器。
|
||||
|
||||
### 能保证什么,怎样判
|
||||
|
||||
正且有界的静态各向同性速度、源与查询连通、合适的边界和首达解选择,给出按域内正行程代价取最小值的 Eikonal 首达模型;离散 tetFIM 对应其数值近似,需核收敛和误差。严格体积分位保留 s 的节点顺序与并列,**最终的秒值一般已不满足原速度的 Eikonal 方程**。在理想首达模型中全件 â 同乘正数只会反向缩放 s,故解码后 U 不变;末端指标不能识别速度的全件绝对尺度。实际离散容差可能影响近并列。这些性质均不足以证明真实熔体质量守恒、支路流量、压力因果关系或前沿正常速度在下一工况仍相同。
|
||||
|
||||
一个反例说明梯度监督的边界。一维区间顶点 x=(0,1,2),唯一源在 0,给 T=(0,1,0.5)。两段斜率绝对值分别为 1、0.5,速度标签均为正且可精确得到;按该速度从源传播的末点时间却是 1+0.5=1.5。梯度模丢失方向,局部满足方程的给定场也可能不是从指定源出发的首达解。对注塑,前沿会合、时间量化、热和压力历史都可能留下这种局部速度无法单独解释的信息。在文献中,EikoNet 从已知介质学习到达场,Eikonal DeepONet 以速度场及源为输入学习跨介质算子;B15 反过来从学习侧到达标签估计介质,推理时保留数值求解器。[EikoNet §2–3](https://arxiv.org/html/2004.00361v3) · [Eikonal DeepONet §II](https://arxiv.org/html/2306.05754v1)
|
||||
|
||||
沿 Claude 已冻结的 B12 门:fold0/100% learning 拟合、原 validation 与 A 同查询评分,场 relative L2、末点距离/Rg 及 Kendall τ-b(含未定义件)。按亲缘组件配对 bootstrap,Δ=新臂−A;场 Δ 的 95% 上界<0,或末点 Δ 上界<0 且场 Δ 上界<0.001,才 EXPAND。否则在数据完整、费用允许的条件下剪此配方。τ 解释排序,不参与挑臂。预测失败或不完整保留原分母并单列,不能靠删困难件过门。≤2 worker CPU-h 包括标签准备、拟合、全件验证 tetFIM、解码与评分;若求解成本使门不可评价则 PARKED(resource),不把没算完写成科学否定。本文无运行结果。
|
||||
@@ -0,0 +1,122 @@
|
||||
"""B15 single fixed fit after B14 terminal; independent7200CPU-second ledger."""
|
||||
import argparse,fcntl,json,os,resource,sys,time,traceback
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import xgboost as xgb
|
||||
import joblib
|
||||
from phase2_b1213_gate import config,read,score as base_score
|
||||
from phase2_b1213_features import input_geometry,cached,flow_mesh,source_geometry,InputViolation
|
||||
from phase2_b15_math import sample,geometry_mask,supervision,positive_speed
|
||||
from phase2_fixed_io import BASE,freeze,verify
|
||||
from phase2_h1_worker_v2 import checked,sha,save
|
||||
from gre24_features_v2 import COLUMNS,solve_eikonal,strict_volume_cdf
|
||||
from gre24_models import xgb_model
|
||||
from s2_custody_common import prediction_inputs
|
||||
from r4bc_guard import supervise
|
||||
from s2_recovery_monitoring import disk_usage
|
||||
|
||||
def prep(root,c,index):
|
||||
row=c['parts'][index];dest=root/'parts'/f'{index:04d}';start=time.process_time()
|
||||
x,t0,raw,old=input_geometry(row);mesh,decoded=source_geometry(c['archive'],row['case']);t=mesh['tets'];cells=mesh['raw_cells']
|
||||
if not np.array_equal(mesh['raw_nodes'],raw) or not np.array_equal(mesh['points'],x):raise InputViolation('Original geometry/node identity')
|
||||
key=lambda a:np.lexsort(tuple(a[:,i] for i in [3,2,1,0]))
|
||||
a=np.sort(t0,axis=1);b=np.sort(t,axis=1)
|
||||
if not np.array_equal(a[key(a)],b[key(b)]):raise InputViolation('Original tetra membership')
|
||||
g=flow_mesh(x,t);center=np.sum(x*g['mass'][:,None],axis=0)/g['mass'].sum();rg=float(np.sqrt(np.sum(g['mass']*np.sum((x-center)**2,axis=1))/g['mass'].sum()))
|
||||
E,valid,condition=geometry_mask(x,t,rg);features=cached(row,'features');X=features[:,4:19][t].mean(1).astype(np.float32)
|
||||
if X.shape!=(len(t),15) or not np.isfinite(X).all():raise ValueError('Geometry feature shape/precision')
|
||||
sources=np.searchsorted(raw,old['features']['gate_raw_ids'])
|
||||
if np.any(sources>=len(raw)) or not np.array_equal(raw[sources],old['features']['gate_raw_ids']):raise ValueError('Original gate identity')
|
||||
selected=sample(row['case'],cells);pi=min(1.,4096/len(t));p=dest/'geometry.npz'
|
||||
np.savez_compressed(p,points=x,tets=t,raw_cells=cells,raw_ids=raw,volume=g['volume'],mass=g['mass'],E=E,X=X,geometry_valid=valid,condition=condition,sources=sources,selected=selected,center=center,Rg=rg)
|
||||
save(dest/'result.json',dict(status='GEOMETRY_COMPLETE',case=row['case'],index=index,tetrahedra=len(t),sampled=len(selected),sampling_pi=pi,geometry_valid=int(valid.sum()),geometry_invalid_volume=float(g['volume'][~valid].sum()),geometry_sha256=sha(p),sampled_raw_tet_ids=cells[selected].tolist(),columns=list(COLUMNS[4:]),sample_fixed_before_labels=True,labels_read=False,decoded_geometry_arrays=decoded,cpu_seconds=time.process_time()-start))
|
||||
|
||||
def entries(root):return {e['case']:e for e in read(root/'features-manifest.json')['entries']}
|
||||
def load(root,e):
|
||||
d=root/'parts'/f"{e['index']:04d}";r=read(checked(d/'result.json',e['result_sha256']));z=np.load(checked(d/'geometry.npz',r['geometry_sha256']),allow_pickle=False);return z,r
|
||||
|
||||
def train(root,c):
|
||||
verify(root,'features');dest=root/'phases/train';by=entries(root);Xs=[];Ys=[];Ws=[];reports=[]
|
||||
for row in c['rows']['learning']:
|
||||
with load(root,by[row['case']])[0] as z:
|
||||
ix=z['selected'];tet=z['tets'][ix];E=z['E'][ix];validgeom=z['geometry_valid'][ix];volume=z['volume'][ix]
|
||||
save(dest/'target-access.json',dict(case=row['case'],role='learning',sample_fixed_sha256=by[row['case']]['result_sha256'],target_sha256=row['v5_cache']['output_sha256']['target.npy']))
|
||||
u=cached(row,'target');y,valid,reasons,gradient=supervision(E,tet,u,z['sources'],validgeom)
|
||||
pi=min(1.,4096/len(z['tets']));w=volume/pi
|
||||
np.savez_compressed(dest/(row['case']+'-supervision.npz'),sampled_raw_cells=z['raw_cells'][ix],geometry_mask=validgeom,supervision_mask=valid,y=y,gradient=gradient,volume=volume,weights_before_normalization=w,**reasons)
|
||||
reports.append(dict(case=row['case'],sampled=len(ix),valid=int(valid.sum()),sampled_volume=float(volume.sum()),valid_sampled_volume=float(volume[valid].sum()),pi=pi,reasons={k:dict(count=int(v.sum()),sampled_volume=float(volume[v].sum())) for k,v in reasons.items()},record_resolution_delta=0,precision_interpretation='numerical ties only; no recording resolution metadata'))
|
||||
Xs.append(z['X'][ix][valid]);Ys.append(y[valid]);Ws.append(w[valid])
|
||||
save(dest/'progress.json',dict(stage='LEARNING_SUPERVISION',parts=len(reports),valid_samples=sum(r['valid'] for r in reports)))
|
||||
X=np.concatenate(Xs);Y=np.concatenate(Ys);W=np.concatenate(Ws);W/=W.mean();model=xgb_model(0,1);model.fit(X,Y,sample_weight=W);model.save_model(dest/'model.ubj')
|
||||
save(dest/'xgboost-config.json',json.loads(model.get_booster().save_config()));save(dest/'result.json',dict(status='FIT_COMPLETE',checkpoint_sha256=sha(dest/'model.ubj'),parts=len(reports),samples=len(Y),columns=list(COLUMNS[4:]),sample_reports=reports,target='negative log P1 normalized gradient norm',validation_labels_read=False))
|
||||
|
||||
def predict(root,c):
|
||||
verify(root,'model');dest=root/'phases/predict';by=entries(root);model=xgb.XGBRegressor();model.load_model(root/'phases/train/model.ubj');baseline=joblib.load(checked(c['baseline']['model_path'],c['baseline']['model_sha256']));manifest=[]
|
||||
for row in c['rows']['validation']:
|
||||
begin=time.process_time()
|
||||
with load(root,by[row['case']])[0] as z:
|
||||
if not np.all(z['geometry_valid']):raise ValueError('Validation contains invalid geometry; no tet deletion')
|
||||
a=positive_speed(model.predict(z['X']));g=flow_mesh((z['points']-z['center'])/float(z['Rg']),z['tets'])
|
||||
begin_solver=time.process_time();phi=solve_eikonal(g,z['sources'],a);solver_cpu=time.process_time()-begin_solver;U=strict_volume_cdf(phi,z['mass']);pred_all=c['clock_c']*U
|
||||
np.savez_compressed(dest/(row['case']+'-field.npz'),raw_ids=z['raw_ids'],raw_cells=z['raw_cells'],speed=a,phi=phi,U=U,pred_normalized=pred_all)
|
||||
q=prediction_inputs(row);ix=np.searchsorted(z['raw_ids'],q['raw_ids'])
|
||||
if np.any(ix>=len(z['raw_ids'])) or not np.array_equal(z['raw_ids'][ix],q['raw_ids']):raise ValueError('Query identity')
|
||||
f=cached(row,'features');A=np.asarray(baseline.predict(f[ix].astype(np.float32)),np.float64);p=dest/(row['case']+'.npz')
|
||||
np.savez_compressed(p,pred=pred_all[ix],A=A,raw_ids=q['raw_ids'],counts=q['counts'],coordinates_over_Rg=q['coordinates_over_Rg'])
|
||||
manifest.append(dict(case=row['case'],component_id=row['component_id'],path=str(p),sha256=sha(p),full_field_sha256=sha(dest/(row['case']+'-field.npz')),geometry_valid=True,solver_cpu_seconds=solver_cpu,cpu_seconds=time.process_time()-begin,clock_learning_only=c['clock_c']))
|
||||
save(dest/'progress.json',dict(parts=len(manifest),last=manifest[-1],validation_targets_read=False))
|
||||
save(dest/'manifest.json',dict(entries=manifest,validation_labels_read=False,all_validation_complete=True))
|
||||
|
||||
def score(root,c):
|
||||
base_score(root,c)
|
||||
from s2_custody_statistics import kendall_pairs
|
||||
from r4bc_common import paired_difference
|
||||
by={r['case']:r for r in c['rows']['validation']};rows=[];groups={}
|
||||
for e in read(root/'phases/predict/manifest.json')['entries']:
|
||||
row=by[e['case']];raw=cached(row,'raw_ids');target=cached(row,'target')
|
||||
with np.load(checked(e['path'],e['sha256']),allow_pickle=False) as z:
|
||||
ix=np.searchsorted(raw,z['raw_ids']);record=dict(case=row['case'],component=row['component_id'])
|
||||
for arm,key in [('new','pred'),('A','A')]:record[arm]=kendall_pairs(target[ix],z[key],int(row['case'].split('_')[0]))
|
||||
rows.append(record);groups.setdefault(row['component_id'],[]).append(record)
|
||||
values={arm:{g:float(np.mean([r[arm]['value'] for r in rs])) for g,rs in groups.items() if all(r[arm]['value'] is not None for r in rs)} for arm in ['new','A']}
|
||||
save(root/'phases/score/kendall-diagnostic.json',dict(rows=rows,new_minus_A=paired_difference(values['new'],values['A']),descriptive_only=True,gate_unchanged=True))
|
||||
|
||||
|
||||
def run(root):
|
||||
c=config(root);os.sched_setaffinity(0,[28]);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
if (root/'started.json').exists():raise FileExistsError('Single B15 launch')
|
||||
b14=BASE/'artifacts/phase2-b14-gate-2026-11-17/complete.json'
|
||||
if not b14.exists():raise RuntimeError('B14 not terminal')
|
||||
start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);charged=0.;records=[];out=[]
|
||||
def total():
|
||||
u=resource.getrusage(resource.RUSAGE_CHILDREN);return 60+max(charged,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)+time.process_time()-start
|
||||
def call(mode,dest,cap,wall,index=None):
|
||||
nonlocal charged
|
||||
cap=min(cap,7200-total()-120);disk=c['disk_bytes']-disk_usage(root)
|
||||
if cap<=0 or disk<=0:raise RuntimeError('RESOURCE_RESERVE_EXHAUSTED')
|
||||
cmd=[sys.executable,'tools/phase2_b15_gate.py',mode,str(root)]+([] if index is None else [str(index)])
|
||||
g=supervise(cmd,dest,dict(cpu_seconds=cap,wall_seconds=wall,rss_bytes=c['rss_bytes'],disk_bytes=disk));charged+=g['cpu_seconds'];records.append(dict(mode=mode,index=index,guard=g));save(root/'phase-ledger.json',dict(records=records,cumulative_cpu_seconds=total()))
|
||||
if g['status']!='PASS' or total()>7200 or disk_usage(root)>c['disk_bytes']:raise RuntimeError('ENGINEERING_OR_RESOURCE_STOP')
|
||||
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),B14_terminal_sha256=sha(b14)))
|
||||
try:
|
||||
for index,row in enumerate(c['parts']):
|
||||
if total()>c['geometry_cpu_cap']-60:raise RuntimeError('PARK_GEOMETRY_RESOURCE')
|
||||
dest=root/'parts'/f'{index:04d}';dest.mkdir(parents=True,exist_ok=False);call('prep',dest,30,60,index);out.append(dict(case=row['case'],index=index,result_sha256=sha(dest/'result.json')))
|
||||
save(root/'live-progress.json',dict(stage='GEOMETRY',parts=len(out),cumulative_cpu_seconds=total()))
|
||||
if len(out)==10:
|
||||
projection=1.25*(total()-60)*sum(r['nodes'] for r in c['parts'])/sum(r['nodes'] for r in c['parts'][:10]);save(root/'first-ten-cost-check.json',dict(projected_cpu_seconds=projection,cap=c['geometry_cpu_cap'],passed=projection<=c['geometry_cpu_cap']))
|
||||
if projection>c['geometry_cpu_cap']:raise RuntimeError('PARK_GEOMETRY_COST_PROJECTION')
|
||||
save(root/'features-manifest.json',dict(entries=out,all431_terminal=True,labels_read=False))
|
||||
freeze(root,'features',[root/'contract.json',root/'features-manifest.json',*[BASE/p for p in c['code_sha256']]])
|
||||
for mode,cap in [('train',1500),('predict',3600),('score',180)]:
|
||||
if mode=='predict':freeze(root,'model',[root/'contract.json',root/'phases/train/model.ubj',root/'phases/train/result.json',*[BASE/p for p in c['code_sha256']]])
|
||||
if mode=='score':freeze(root,'predictions',[root/'contract.json',root/'phases/predict/manifest.json',*[BASE/p for p in c['code_sha256']]])
|
||||
dest=root/'phases'/mode;dest.mkdir(parents=True,exist_ok=False);save(root/'live-progress.json',dict(stage=mode,cumulative_cpu_seconds=total()));call(mode,dest,cap,cap+60)
|
||||
save(root/'complete.json',dict(status='COMPLETE',scientific_gate=read(root/'phases/score/result.json')['decision'],records=records,cumulative_cpu_seconds=total(),models_fit=1,retry=False))
|
||||
except BaseException as exc:
|
||||
save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),records=records,cumulative_cpu_seconds=total(),completed_geometry=len(out),retry=False));raise
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('mode',choices=['run','prep','train','predict','score']);p.add_argument('root',type=Path);p.add_argument('index',nargs='?',type=int);a=p.parse_args()
|
||||
if a.mode=='run':run(a.root)
|
||||
elif a.mode=='prep':prep(a.root,config(a.root),a.index)
|
||||
else:dict(train=train,predict=predict,score=score)[a.mode](a.root,config(a.root))
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Fixed tet speed supervision and hash sampling; no clipping/in-filling."""
|
||||
import hashlib
|
||||
import numpy as np
|
||||
|
||||
def sample(case,raw_cells,limit=4096):
|
||||
prefix=case.encode();prefix=len(prefix).to_bytes(8,'big')+prefix
|
||||
keys=[hashlib.sha256(prefix+int(i).to_bytes(8,'big',signed=False)).digest() for i in raw_cells]
|
||||
return np.asarray(sorted(range(len(keys)),key=lambda i:(keys[i],int(raw_cells[i])))[:limit],np.int64)
|
||||
|
||||
def geometry_mask(x,t,rg):
|
||||
if not np.isfinite(x).all() or not np.isfinite(rg) or rg<=0:raise ValueError('Invalid physical geometry scale')
|
||||
E=(x[t[:,1:]]-x[t[:,:1]])/rg;volume=np.abs(np.linalg.det(E))/6;condition=np.linalg.cond(E)
|
||||
valid=np.isfinite(condition)&(condition<=1e8)&np.isfinite(volume)&(volume>0)
|
||||
return E,valid,condition
|
||||
|
||||
def supervision(E,t,u,sources,geometry):
|
||||
value=u[t];source=np.isin(t,sources).any(1);arrival=np.isfinite(value).all(1)&(value>=0).all(1)
|
||||
tolerance=64*np.finfo(np.float64).eps*np.maximum(1,np.max(np.abs(value),axis=1));plateau=np.ptp(value,axis=1)<=tolerance
|
||||
eligible=geometry&arrival&~source&~plateau;gradient=np.full((len(t),3),np.nan)
|
||||
gradient[eligible]=np.linalg.solve(E[eligible],(value[eligible,1:]-value[eligible,:1])[...,None])[...,0]
|
||||
norm=np.linalg.norm(gradient,axis=1);valid=eligible&np.isfinite(norm)&(norm>0);y=np.full(len(t),np.nan);y[valid]=-np.log(norm[valid])
|
||||
return y,valid,dict(geometry_invalid=~geometry,source_neighbour=source,invalid_arrival=~arrival,plateau=plateau,invalid_gradient=eligible&~valid),gradient
|
||||
|
||||
def positive_speed(y):
|
||||
with np.errstate(over='ignore',under='ignore',invalid='ignore'):a=np.exp(np.asarray(y,np.float64));sq=a*a
|
||||
if not np.isfinite(a).all() or np.any(a<=0) or not np.isfinite(sq).all() or np.any(sq<=0):raise ValueError('Speed/tensor not representable, no clipping')
|
||||
return a
|
||||
@@ -0,0 +1,27 @@
|
||||
import unittest
|
||||
import numpy as np
|
||||
from phase2_b15_math import sample,geometry_mask,supervision,positive_speed
|
||||
from gre24_features_v2 import strict_volume_cdf
|
||||
class SpeedTests(unittest.TestCase):
|
||||
def setUp(self):self.x=np.vstack([np.zeros(3),np.eye(3)]);self.t=np.array([[0,1,2,3]])
|
||||
def test_affine_speed_and_units(self):
|
||||
for scale in [1,.001]:
|
||||
E,valid,cond=geometry_mask(self.x*scale,self.t,scale);y,good,_,g=supervision(E,self.t,2*self.x[:,0],[],valid)
|
||||
self.assertTrue(good[0]);self.assertAlmostEqual(positive_speed(y)[0],.5);np.testing.assert_allclose(g,[ [2,0,0] ])
|
||||
def test_source_plateau_masks_and_partial_ties(self):
|
||||
E,v,_=geometry_mask(self.x,self.t,1)
|
||||
_,a,r,_=supervision(E,self.t,np.ones(4),[],v);self.assertFalse(a[0]);self.assertTrue(r['plateau'][0])
|
||||
_,a,r,_=supervision(E,self.t,np.array([0,1,0,0.]),[0],v);self.assertFalse(a[0]);self.assertTrue(r['source_neighbour'][0])
|
||||
_,a,r,_=supervision(E,self.t,np.array([0,1,0,0.]),[],v);self.assertTrue(a[0])
|
||||
def test_condition_boundary(self):
|
||||
x=self.x.copy();x[3,2]=1e-9;_,v,c=geometry_mask(x,self.t,1);self.assertFalse(v[0])
|
||||
def test_sample_id_order_invariant(self):
|
||||
ids=np.arange(6000);a=ids[sample('case',ids)];rev=ids[::-1];b=rev[sample('case',rev)];np.testing.assert_array_equal(a,b);self.assertEqual(len(a),4096)
|
||||
def test_no_clipping(self):
|
||||
for y in [1000,-1000,float('nan'),float('inf')]:
|
||||
with self.assertRaises(ValueError):positive_speed([y])
|
||||
def test_clock_scale_invariance_ties(self):
|
||||
f=np.array([0,1,1,2.]);m=np.array([1,2,3,4.]);np.testing.assert_array_equal(strict_volume_cdf(f,m),strict_volume_cdf(f/7,m));self.assertEqual(strict_volume_cdf(f,m)[2],.1)
|
||||
def test_direction_loss_counterexample(self):
|
||||
T=np.array([0,1,.5]);speed=1/np.abs(np.diff(T));self.assertEqual(np.sum(1/speed),1.5);self.assertNotEqual(np.sum(1/speed),T[-1])
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user