Files
MeltMind/tools/track_b_h2_pressure_prepare.py
T

103 lines
5.2 KiB
Python

"""Prepare the H2-P ShapeNet611 comparison without opening the pressure archive."""
import argparse
import math
from pathlib import Path
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
import torch
from torch import nn
import track_b_gino_formal as reference
from phase2_h2_model import H2Geo, edge_attributes
from track_b_gino_shapenet_entry import BASE, save, sha
ROOT = BASE / 'artifacts/track-b-h2-pressure-preparation-2026-11-19'
STATUS = 'PREPARED_PENDING_INPUT_REVIEW_AND_MEASURED_COST'
class PressureH2(H2Geo):
"""Use the shared H2 blocks with a three-coordinate input and direct pressure output."""
def __init__(self):
super().__init__()
self.encoder[0] = nn.Linear(3, 64)
self.head[0] = nn.Linear(67, 64)
def surface(points, triangles, lower, upper):
points = np.asarray(points, dtype=np.float64)
faces = np.asarray(triangles)
if (points.ndim != 2 or points.shape[1] != 3 or not np.isfinite(points).all()
or faces.ndim != 2 or faces.shape[1] != 3 or len(faces) == 0
or faces.dtype.kind not in 'iu' or np.any(faces < 0) or np.any(faces >= len(points))):
raise ValueError('Original ordered triangle mesh required')
lo, hi = np.asarray(lower, dtype=np.float64), np.asarray(upper, dtype=np.float64)
if (lo.shape != (3,) or hi.shape != (3,) or not np.isfinite(lo).all()
or not np.isfinite(hi).all() or not np.all(hi > lo)):
raise ValueError('Fixed ShapeNet normalization bounds required')
xyz = points[faces]
area = np.linalg.norm(np.cross(xyz[:, 1] - xyz[:, 0], xyz[:, 2] - xyz[:, 0]), axis=1) / 2
mass = np.bincount(faces.ravel(), weights=np.repeat(area / 3, 3), minlength=len(points))
if not np.isfinite(area).all() or np.any(area <= 0) or np.any(mass <= 0):
raise ValueError('Every original vertex needs positive incident triangle area')
edges = np.concatenate((faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]]))
edges = np.unique(np.concatenate((edges, edges[:, ::-1])), axis=0)
receiver, sender = edges.T
graph = csr_matrix((np.ones(len(receiver)), (receiver, sender)), shape=(len(points), len(points)))
_, components = connected_components(graph, directed=False)
attributes, _ = edge_attributes(points, mass, receiver, sender)
# CFDSDFDataModule's original affine coordinate map to [-1, 1].
x = 2 * (points - lo) / (hi - lo) - 1
return tuple(torch.from_numpy(value) for value in (
x.astype(np.float32), mass.astype(np.float32), receiver.astype(np.int64),
sender.astype(np.int64), attributes, components.astype(np.int64)))
def project(epoch_seconds, overhead_gpu_seconds, cap=40000):
if (not math.isfinite(epoch_seconds) or epoch_seconds <= 0
or not math.isfinite(overhead_gpu_seconds) or overhead_gpu_seconds < 0):
raise ValueError('Measured full H2-P epoch and a declared overhead reserve required')
gpu = math.ceil(1.25 * 3 * 100 * epoch_seconds + overhead_gpu_seconds)
return dict(train_plus_margin_gpu_seconds=1.25 * 3 * 100 * epoch_seconds,
overhead_gpu_seconds=overhead_gpu_seconds, projected_gpu_seconds=gpu,
matched_maximum_gpu_seconds=cap, within_matched_cap=gpu <= cap)
def binding():
gino = reference.contract()
return dict(status=STATUS, handoff='h-539a65e1', identity='H2-P',
working_entry='preparation_only', seeds=[0, 1, 2], candidate_epochs_per_seed=100,
raw_paper_data=gino['paper_data'], source_mapping=gino['mapping_audit'], split_receipt=gino['split_receipt'],
split=gino['split'], reference_comparison=dict(path=gino['comparison_contract'], sha256=gino['comparison_contract_sha256']),
same_case_metric=gino['protocol']['metric'],
candidate_geometry=dict(vertex_order='exact source PLY', node_inputs=['x', 'y', 'z'],
edges='original triangle edges both directions', nodal_mass='one-third incident triangle area',
message_components='connected components of original edges', pressure_readout='direct scalar per original node',
molding_inputs=[], scientific_model='four shared 64-wide H2 graph/token blocks'),
custody=dict(prepared_target_reads=0, fit_target_reads=0, final_unique_target_reads=111,
all_three_checkpoints_before_final_score=True),
timing=dict(complete_learning_cases=500, formal_cap_max_gpu_seconds=40000, factor=1.25,
measurement_result=None, status='BLOCKED_NO_H2_P_GUARD_CERTIFIED_EPOCH'),
production_guard_limits=gino['limits'],
launch_authorized=False,
code_sha256={str(path): sha(path) for path in (
Path(__file__).resolve(), reference.SOURCES/'phase2_h2_model.py',
reference.SOURCES/'track_b_gino_formal_guard.py')})
if __name__ == '__main__':
import json
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--write-binding', action='store_true')
args = parser.parse_args()
c = binding()
if args.write_binding:
ROOT.mkdir(exist_ok=False)
save(ROOT/'preparation-binding.json', c)
print(json.dumps({key: c[key] for key in ('status', 'identity', 'timing', 'launch_authorized')}, indent=2))