Compare commits

..
6 changed files with 389 additions and 633 deletions

No files matched your search

-19
View File
@@ -1,19 +0,0 @@
# Multi-Gate Feature Builder (`MULTIGATE-FEATURES-1122`)
Extends the frozen 19-column `tools/gre24_features_v2.py` builder to $K \ge 1$ gates without modifying `gre24_features_v2.py`. Code and synthetic CPU tests only; no real data, no GPU, no push to `main`.
## Files
- `tools/multigate_features.py`: multi-gate feature builder (`features`, `pack_multigate_features`) plus pure-NumPy geometry/gradient/moment helpers for minimal CPU test environments.
- `tools/test_multigate_features.py`: CPU synthetic tet-mesh tests (K=1 byte-identity, two-gate mirror symmetry, single-gate perturbation locality, K=3 packing, fail-closed guards).
## Semantics & Compatibility
- **Production default (`backend='production'`):** delegates directly to `gre24_features_v2.{mesh, exterior_faces, gate_nodes, solve_eikonal, cell_flow_speed, strict_volume_cdf, nodal_gradient, spatial_moment}` in the exact same call order (fails closed if `fimpy`/`sklearn`/`scipy` are unavailable). For `K=1`, `features`, `Dw`, `Di`, `Df`, `Vf`, `mass`, and `all_wall_tet_ids` are **byte-identical** to `gre24_features_v2.features`.
- **Multi-gate outputs:**
- `Di_per_gate`, `Df_per_gate`: `(N, K)` raw geometric and wall-weighted flow arrival distances per gate.
- `Di_per_gate_star = Di_per_gate / Di.max()`, `Df_per_gate_star = Df_per_gate / Df.max()`: common-scale normalized per-gate channels preserving cross-gate ordering and symmetry.
- `Di = min_k Di_per_gate`, `Df = min_k Df_per_gate`, `Vf = strict_volume_cdf(Df, mass)`: base 19 columns computed from `(Df, Di, Dw)`.
- `nearest_gate_di`, `nearest_gate_df` (`nearest_gate` alias): `int64` in `0..K-1` (smallest-index tie-break), plus `gate_tie_mask_di` / `gate_tie_mask_df` for exact symmetry/weld-front ties.
- **Perturbation locality:** moving gate $k$ leaves `Dw`, other gates' `Di_per_gate[:, j]` / `Df_per_gate[:, j]` ($j \ne k$), and `Di` / `Df` / `nearest_gate` outside gate $k$'s old/new arrival basin byte-identical. (`Vf` is a global volume CDF over `Df` and therefore updates globally wherever the sorted volume rank shifts.)
## Verification on Horsea
Run `python -B tools/test_multigate_features.py` in the Horsea `fimpy`/`sklearn`/`scipy` environment: `test_single_gate_byte_identical_production_when_deps_available` automatically runs live against `gre24_features_v2.features` and asserts exact `.tobytes()` equality.
+30
View File
@@ -0,0 +1,30 @@
# Transolver-Greif Adapter (`TRANSOLVER-ADAPTER-1122`)
Code-only Transolver (Wu et al., ICML 2024) adapter aligned with the frozen grouped Greif v5 comparison protocol (`18e0e729`). No real data read, no GPU run, no push to `main`.
## Files
- `tools/track_b_transolver_greif_adapter.py`: `GreifTransolver`, `TransolverBlock`, `PhysicsAttention`, `make_greif_transolver`, and pure-array input helpers.
- `tools/test_track_b_transolver_greif.py`: CPU-only synthetic tet-mesh unit tests.
## Protocol Alignment
- **Inputs:** Exact 19 `COLUMNS` from `track_b_gino_greif_adapter.py` (no extra `xyz` channels), standardized in FP64 on each fold's learning split only (`phase2_h2_data.standardization`), cast to FP32, plus strictly positive FP32 nodal `mass` and optional `component_ids`.
- **Target & Decode:** Exact `phase2_residual_math` FP64 volume-clock prior `c * Vf`, signed unclamped FP32 `residual_target`, and `decode_seconds`. Readout head final layer is zero-initialized so epoch 0 starts at `c * Vf`.
- **Loss & Schedule:** Reuses `phase2_h2_model.{weighted_loss, optimizer, lr_epoch}` (node-equal FP32 MSE, AdamW `wd=1e-4` on >=2D non-bias, 10-epoch warmup + 190-epoch cosine, grad clip 1.0, TF32 off).
- **Folds:** Unchanged grouped folds 0/1 (`((0,0),(0,1),(1,0),(1,1))`, family isolation, `no_validation_selection=True`).
## Parameter Counts
| Model | Config | Parameters |
| --- | --- | ---: |
| `H2Geo` (reference) | `C=64, 4 GeoBlocks` | 195,077 |
| `GreifTransolver` (`default`) | `C=64, L=6, H=4, G=64, mlp_ratio=2` | 197,913 |
| `GreifTransolver` (`wide` flag) | `C=96, L=4, H=4, G=64, mlp_ratio=2` | 293,937 |
## Design Assumptions
1. **Mass-weighted slice pooling (`mass_weighted=True`, default):** Nodal mass is normalized per connected component (`m / sum(m)`) before slice pooling so attention tokens are invariant to global mass units and reflect tet volume measure. `mass_weighted=False` reproduces unweighted Transolver.
2. **Per-component isolation & chunking:** Slices are pooled per physical connected component (matching `H2Geo.global_message`) in `NODE_CHUNK=8192` chunks with optional block gradient checkpointing to bound VRAM on 30K–100K+ node tet meshes.
3. **Slice denominator & temperature stability:** Per-head temperature is clamped to `[0.1, 5.0]` and normalized slice denominators add `1e-6` (`1e-5` unweighted) to prevent FP32 division instability.
## Open Items for MeltSol / MeltAssist
1. **Execution binding & worker:** This branch provides only the model adapter and CPU synthetic tests; MeltSol should wire `GreifTransolver` into a guarded fold-0/1 worker/entry (same `first`-epoch cost gate and <= 40,000 GPU-s GPU3 cap as planned) for MeltAssist review.
2. **Checkpoint / VRAM profiling on real meshes:** Verify `NODE_CHUNK=8192` and `checkpoint_blocks=True` peak VRAM on the largest Greif learning part during the first measured epoch.
3. **Optional ablation:** Confirm whether only `default` (197.9K, `mass_weighted=True`) runs in the primary <= 40,000 GPU-s slot, leaving `wide` and `mass_weighted=False` out of scope.
-356
View File
@@ -1,356 +0,0 @@
"""Multi-gate extension of the frozen 19-column Gre24 feature builder.
Preserves exact byte-for-byte identity with tools/gre24_features_v2.py when K=1
under the production fimpy/BallTree/SurfaceDistance backend. Code only: no real
data reads, no GPU launches, and never modifies tools/gre24_features_v2.py.
"""
from itertools import combinations
import time
import numpy as np
COLUMNS = (
'Vf', 'grad_Vf_x', 'grad_Vf_y', 'grad_Vf_z', 'Di_star',
'grad_Di_x', 'grad_Di_y', 'grad_Di_z', 'Dw', 'Dw_star',
'grad_Dw_x', 'grad_Dw_y', 'grad_Dw_z',
'Sxx', 'Sxy', 'Sxz', 'Syy', 'Syz', 'Szz',
)
def _load_production_module():
import gre24_features_v2 as g24
return g24
def mesh_numpy(points, tetra):
x = np.asarray(points, dtype=np.float64)
t = np.asarray(tetra)
if x.ndim != 2 or x.shape[1] != 3 or not np.isfinite(x).all():
raise ValueError('Invalid points')
if t.ndim != 2 or t.shape[1] != 4 or t.dtype.kind not in 'iu' or not len(t):
raise ValueError('Invalid tetrahedra')
if t.min() < 0 or t.max() >= len(x) or not np.array_equal(np.unique(t), np.arange(len(x))):
raise ValueError('Tet domain must explicitly contain every supplied node')
t = np.asarray(t, dtype=np.int32)
cells = x[t]
matrix = cells[:, 1:] - cells[:, :1]
volume = np.abs(np.linalg.det(matrix)) / 6
if not np.isfinite(volume).all() or np.any(volume <= 0):
raise ValueError('Nonpositive tetrahedron volume')
mass = np.bincount(t.ravel(), weights=np.repeat(volume / 4, 4), minlength=len(x))
hmax = max(float(np.linalg.norm(cells[:, i] - cells[:, j], axis=1).max())
for i, j in combinations(range(4), 2))
return dict(x=x, t=t, matrix=matrix, volume=volume, mass=mass,
centers=cells.mean(1), hmax=hmax)
def exterior_faces_numpy(tetra):
faces = np.sort(tetra[:, np.array([[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]])].reshape(-1, 3), axis=1)
faces, counts = np.unique(faces, axis=0, return_counts=True)
if np.any(counts > 2):
raise ValueError('Nonmanifold tetrahedron faces')
return faces[counts == 1]
def gate_nodes_numpy(x, raw_ids, gate, marked=None):
raw_ids = np.asarray(raw_ids)
if len(raw_ids) != len(x) or len(np.unique(raw_ids)) != len(x):
raise ValueError('Invalid original node IDs')
if marked is not None:
marked = np.asarray(marked, dtype=np.int64)
if not len(marked) or marked.min() < 0 or marked.max() >= len(x):
raise ValueError('Invalid explicit inlet node set')
return np.unique(marked), 'explicit_marked_nodes'
gate = np.asarray(gate, dtype=float)
if gate.shape != (3,) or not np.isfinite(gate).all():
raise ValueError('Invalid inlet location')
d2 = np.sum((x - gate) ** 2, axis=1)
tied = np.flatnonzero(d2 == d2.min())
return np.array([tied[np.argmin(raw_ids[tied])]]), 'nearest_tet_node_min_original_id_tie'
def _triangle_distance_squared(point, triangles):
a, b, c = triangles[:, 0], triangles[:, 1], triangles[:, 2]
ab, ac = b - a, c - a
q = point - a
normal = np.cross(ab, ac)
n2 = np.einsum('ij,ij->i', normal, normal)
good = n2 > 0
denom = np.where(good, n2, 1.0)
u = np.einsum('ij,ij->i', np.cross(q, ac), normal) / denom
v = np.einsum('ij,ij->i', np.cross(ab, q), normal) / denom
inside = good & (u >= 0) & (v >= 0) & (u + v <= 1)
plane = np.einsum('ij,ij->i', q, normal) ** 2 / denom
result = np.where(inside, plane, np.inf)
for first, second in [(a, b), (b, c), (c, a)]:
edge = second - first
length2 = np.einsum('ij,ij->i', edge, edge)
alpha = np.clip(np.einsum('ij,ij->i', point - first, edge) / np.where(length2 > 0, length2, 1.0), 0.0, 1.0)
residual = point - (first + alpha[:, None] * edge)
result = np.minimum(result, np.einsum('ij,ij->i', residual, residual))
return np.maximum(result, 0.0)
def cell_flow_speed_numpy(g, dw, wall_faces):
if not np.isfinite(dw).all() or np.any(dw < 0):
raise ValueError('Invalid wall field')
speed = dw[g['t']].mean(1)
zero = np.flatnonzero(np.all(dw[g['t']] == 0, axis=1))
if len(zero):
triangles = g['x'][wall_faces]
speed[zero] = np.array([
float(np.sqrt(_triangle_distance_squared(p, triangles).min()))
for p in g['centers'][zero]
], dtype=np.float64)
if not np.isfinite(speed).all() or np.any(speed <= 0):
raise ValueError('Nonpositive flow speed after declared all-wall supplement')
return speed, zero
def strict_volume_cdf_numpy(field, mass):
d = np.asarray(field, dtype=float)
w = np.asarray(mass, dtype=float)
if d.ndim != 1 or w.shape != d.shape or not len(d) or not np.isfinite(d).all() or not np.isfinite(w).all() or np.any(w <= 0):
raise ValueError('Invalid lumped-volume CDF')
order = np.argsort(d, kind='stable')
prefix = np.r_[0., np.cumsum(w[order], dtype=np.float64)]
return prefix[np.searchsorted(d[order], d, side='left')] / w.sum()
def nodal_gradient_numpy(g, values, normalize=True):
v = np.asarray(values, dtype=float)
if v.shape != (len(g['x']),) or not np.isfinite(v).all():
raise ValueError('Invalid nodal scalar')
t = g['t']
cell_grad = np.linalg.solve(g['matrix'], (v[t[:, 1:]] - v[t[:, :1]])[..., None])[..., 0]
grad = np.zeros((len(v), 3))
for k in range(4):
np.add.at(grad, t[:, k], cell_grad * g['volume'][:, None])
grad /= 4 * g['mass'][:, None]
if normalize:
norm = np.linalg.norm(grad, axis=1)
np.divide(grad, norm[:, None], out=grad, where=norm[:, None] > 0)
return grad
def spatial_moment_numpy(g, di, progress=lambda *a, **kw: None):
radius = 3 * g['hmax']
centers = g['centers']
cell_di = di[g['t']].mean(1)
result = np.empty((len(di), 6))
coincident = 0
for i, p in enumerate(g['x']):
delta = centers - p
dist = np.linalg.norm(delta, axis=1)
selected = (dist < radius) & (np.abs(cell_di - di[i]) < radius)
coincident += int(np.sum(selected & (dist == 0)))
selected &= dist > 0
ids = np.flatnonzero(selected)
if not len(ids):
raise ValueError(f'Empty moment neighbourhood at node {i}')
direction = delta[ids] / dist[ids, None]
weight = g['volume'][ids]
weight = weight / weight.sum()
tensor = np.einsum('n,ni,nj->ij', weight, direction, direction)
result[i] = tensor[[0, 0, 0, 1, 1, 2], [0, 1, 2, 1, 2, 2]]
if i % 4096 == 0:
progress('SPATIAL_MOMENT', completed=i, total=len(di))
return result, dict(radius=radius, coincident_centers_excluded=coincident,
component_order=list(COLUMNS[13:]))
def _normalize_gates(gates, marked_gates):
if gates is None:
if marked_gates is None:
raise ValueError('Either gates or marked_gates is required')
marked_list = list(marked_gates)
if not marked_list:
raise ValueError('At least one gate is required')
return [None] * len(marked_list), marked_list
arr = np.asarray(gates, dtype=np.float64)
if arr.ndim == 1:
if arr.shape != (3,):
raise ValueError('Single gate coordinate must have shape (3,)')
arr = arr[None, :]
elif arr.ndim != 2 or arr.shape[1] != 3 or len(arr) == 0:
raise ValueError('gates must have shape (K, 3) with K >= 1')
if not np.isfinite(arr).all():
raise ValueError('Nonfinite gate coordinates')
gate_list = [arr[k] for k in range(len(arr))]
if marked_gates is None:
marked_list = [None] * len(gate_list)
else:
marked_list = list(marked_gates)
if len(marked_list) != len(gate_list):
raise ValueError('marked_gates length must match gates')
return gate_list, marked_list
def _nearest_and_ties(per_gate, tie_rtol=1e-12):
# np.argmin breaks exact ties by smallest gate index (deterministic).
nearest = np.argmin(per_gate, axis=1).astype(np.int64)
if per_gate.shape[1] == 1:
return nearest, np.zeros(len(per_gate), dtype=bool)
min_vals = per_gate[np.arange(len(per_gate)), nearest]
tol = tie_rtol * max(float(min_vals.max()), 1.0)
close_count = np.sum(per_gate <= min_vals[:, None] + tol, axis=1)
return nearest, close_count > 1
def features(points, tetra, raw_ids, gates, wall_faces=None, marked_gates=None,
progress=lambda *a, **kw: None, *, backend='production', eikonal_solver=None):
"""Compute 19 base columns + multi-gate arrival channels for K >= 1 gates.
When backend='production' (default) and K=1, delegates directly to
gre24_features_v2 primitives in identical order for byte-identical output.
"""
if backend == 'production':
g24 = _load_production_module()
mesh_fn = g24.mesh
ext_fn = g24.exterior_faces
gate_fn = g24.gate_nodes
speed_fn = g24.cell_flow_speed
cdf_fn = g24.strict_volume_cdf
grad_fn = g24.nodal_gradient
moment_fn = g24.spatial_moment
solver_fn = g24.solve_eikonal if eikonal_solver is None else eikonal_solver
elif backend == 'numpy':
if eikonal_solver is None:
raise ValueError("backend='numpy' requires an explicit eikonal_solver callable")
mesh_fn = mesh_numpy
ext_fn = exterior_faces_numpy
gate_fn = gate_nodes_numpy
speed_fn = cell_flow_speed_numpy
cdf_fn = strict_volume_cdf_numpy
grad_fn = nodal_gradient_numpy
moment_fn = spatial_moment_numpy
solver_fn = eikonal_solver
else:
raise ValueError(f'Unknown backend: {backend}')
gate_list, marked_list = _normalize_gates(gates, marked_gates)
n_gates = len(gate_list)
start = time.process_time()
g = mesh_fn(points, tetra)
faces = ext_fn(g['t']) if wall_faces is None else np.asarray(wall_faces)
per_gate_sources = []
per_gate_modes = []
for gate_pt, marked in zip(gate_list, marked_list):
src, mode = gate_fn(g['x'], raw_ids, gate_pt, marked)
per_gate_sources.append(src)
per_gate_modes.append(mode)
wall = np.unique(faces)
timings = {}
tick = time.process_time()
def finish(name):
nonlocal tick
now = time.process_time()
timings[name] = now - tick
tick = now
progress('EIKONAL_DW')
dw = solver_fn(g, wall, 1.)
finish('Dw')
progress('EIKONAL_DI')
di_list = [solver_fn(g, src, 1.) for src in per_gate_sources]
finish('Di')
progress('CELL_SPEED')
speed, zero = speed_fn(g, dw, faces)
finish('cell_speed')
progress('EIKONAL_DF')
df_list = [solver_fn(g, src, speed) for src in per_gate_sources]
finish('Df')
di_per_gate = np.column_stack(di_list)
df_per_gate = np.column_stack(df_list)
# Preserve exact array identity for K=1.
di = di_list[0] if n_gates == 1 else di_per_gate.min(axis=1)
df = df_list[0] if n_gates == 1 else df_per_gate.min(axis=1)
if dw.max() <= 0 or di.max() <= 0 or df.max() <= 0:
raise ValueError('Zero feature normalisation scale')
vf = cdf_fn(df, g['mass'])
dis = di / di.max()
dws = dw / dw.max()
grads = [grad_fn(g, a) for a in (vf, dis, dws)]
finish('gradients')
moment, moment_meta = moment_fn(g, di, progress)
finish('moment')
x = np.column_stack([vf, grads[0], dis, grads[1], dw, dws, grads[2], moment])
if x.shape != (len(points), 19) or not np.isfinite(x).all():
raise ValueError('Invalid final 19-column features')
di_per_gate_star = di_per_gate / di.max()
df_per_gate_star = df_per_gate / df.max()
nearest_gate_di, gate_tie_mask_di = _nearest_and_ties(di_per_gate)
nearest_gate_df, gate_tie_mask_df = _nearest_and_ties(df_per_gate)
all_sources = np.unique(np.concatenate(per_gate_sources))
raw_arr = np.asarray(raw_ids)
gate_dists = [
float(np.linalg.norm(g['x'][src] - np.asarray(pt), axis=1).min()) if pt is not None else 0.0
for src, pt in zip(per_gate_sources, gate_list)
]
metadata = dict(
columns=list(COLUMNS),
backend=backend,
num_gates=n_gates,
gate_modes=per_gate_modes,
gate_nodes=[src.tolist() for src in per_gate_sources],
gate_raw_ids=[raw_arr[src].tolist() for src in per_gate_sources],
gate_mapping_distances=gate_dists,
nearest_gate_tie_break='smallest_gate_index',
wall_mode='tet_exterior_proxy' if wall_faces is None else 'explicit_supplied_wall_faces',
all_wall_tetrahedra=len(zero),
all_wall_volume_fraction=float(g['volume'][zero].sum() / g['volume'].sum()),
timings_cpu_seconds=timings,
worker_cpu_seconds=time.process_time() - start,
volume=float(g['volume'].sum()),
hmax=g['hmax'],
moment=moment_meta,
speed_min=float(speed.min()),
speed_max=float(speed.max()),
exterior_proxy_includes_gate=bool(np.any(np.isin(all_sources, wall))),
precision='float64',
)
arrays = dict(
features=x,
Dw=dw,
Di=di,
Df=df,
Vf=vf,
mass=g['mass'],
all_wall_tet_ids=zero,
Di_per_gate=di_per_gate,
Df_per_gate=df_per_gate,
Di_per_gate_star=di_per_gate_star,
Df_per_gate_star=df_per_gate_star,
nearest_gate_di=nearest_gate_di,
nearest_gate_df=nearest_gate_df,
nearest_gate=nearest_gate_df,
gate_tie_mask_di=gate_tie_mask_di,
gate_tie_mask_df=gate_tie_mask_df,
)
return arrays, metadata
def pack_multigate_features(arrays):
"""Stack base 19 columns + per-gate normalized Di/Df + nearest_gate index."""
base = np.asarray(arrays['features'], dtype=np.float64)
di_g = np.asarray(arrays['Di_per_gate_star'], dtype=np.float64)
df_g = np.asarray(arrays['Df_per_gate_star'], dtype=np.float64)
ng = np.asarray(arrays['nearest_gate'], dtype=np.float64)[:, None]
k = di_g.shape[1]
cols = (
COLUMNS
+ tuple(f'Di_gate{i}_star' for i in range(k))
+ tuple(f'Df_gate{i}_star' for i in range(k))
+ ('nearest_gate',)
)
return np.column_stack([base, di_g, df_g, ng]), cols
-258
View File
@@ -1,258 +0,0 @@
"""CPU-only synthetic tet-mesh tests for tools/multigate_features.py (no real data, no GPU)."""
import heapq
import importlib.util
from itertools import permutations
from pathlib import Path
import sys
import unittest
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import multigate_features as mg
def _box_half_tets(nx, ny, nz, x_bounds, y_bounds, z_bounds):
axes = [
np.linspace(x_bounds[0], x_bounds[1], nx),
np.linspace(y_bounds[0], y_bounds[1], ny),
np.linspace(z_bounds[0], z_bounds[1], nz),
]
x = np.stack(np.meshgrid(*axes, indexing='ij'), axis=-1).reshape(-1, 3)
ids = np.arange(len(x)).reshape(nx, ny, nz)
t = []
for i in range(nx - 1):
for j in range(ny - 1):
for k in range(nz - 1):
for perm in permutations(range(3)):
v = np.array([i, j, k])
row = [ids[tuple(v)]]
for a in perm:
v = v.copy()
v[a] += 1
row.append(ids[tuple(v)])
t.append(row)
return x, np.asarray(t, dtype=np.int32)
def symmetric_box_mesh(nx_half=5, ny=3, nz=3, half_len=1.0, half_w=0.5, half_h=0.5):
"""Build a 3D tet mesh that is strictly mirror-symmetric under x -> -x."""
xp, tp = _box_half_tets(nx_half, ny, nz, (0.0, half_len), (-half_w, half_w), (-half_h, half_h))
on_plane = np.isclose(xp[:, 0], 0.0, atol=1e-12)
off_plane = np.flatnonzero(~on_plane)
xm = xp[off_plane].copy()
xm[:, 0] = -xm[:, 0]
points = np.vstack([xp, xm])
# Mirror map on node indices: involution mirror[mirror[i]] == i.
n_pos = len(xp)
mirror = np.arange(len(points), dtype=np.int64)
old_to_mirrored = np.arange(n_pos, dtype=np.int64)
for idx_new, idx_old in enumerate(off_plane):
mapped = n_pos + idx_new
old_to_mirrored[idx_old] = mapped
mirror[idx_old] = mapped
mirror[mapped] = idx_old
tm = old_to_mirrored[tp]
# Swap two vertices so reflected tets keep positive orientation (abs det handles both).
tm[:, [1, 2]] = tm[:, [2, 1]]
tetra = np.vstack([tp, tm]).astype(np.int32)
return points, tetra, mirror
def tet_edge_dijkstra_solver(g, sources, speed):
"""Deterministic mirror-symmetric pure-NumPy tet-edge shortest-path solver for CPU tests."""
x = g['x']
t = g['t']
n = len(x)
spd = np.broadcast_to(np.asarray(speed, dtype=np.float64), (len(t),))
if not np.isfinite(spd).all() or np.any(spd <= 0):
raise ValueError('Nonpositive or nonfinite cell speed')
edge_speed_sum = {}
edge_count = {}
for cell_idx, tet in enumerate(t):
s_val = float(spd[cell_idx])
for a, b in ((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)):
u, v = int(tet[a]), int(tet[b])
key = (u, v) if u < v else (v, u)
edge_speed_sum[key] = edge_speed_sum.get(key, 0.0) + s_val
edge_count[key] = edge_count.get(key, 0) + 1
adj = [[] for _ in range(n)]
for (u, v), s_sum in edge_speed_sum.items():
length = float(np.linalg.norm(x[u] - x[v]))
w = length / (s_sum / edge_count[(u, v)])
adj[u].append((v, w))
adj[v].append((u, w))
dist = np.full(n, np.inf, dtype=np.float64)
heap = []
for src in np.asarray(sources, dtype=np.int64):
dist[src] = 0.0
heapq.heappush(heap, (0.0, int(src)))
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue
for v, w in adj[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd
heapq.heappush(heap, (nd, v))
if not np.isfinite(dist).all():
raise ValueError('Unreached node in synthetic solver')
return dist
def _single_gate_reference_numpy(points, tetra, raw_ids, gate, solver_fn):
"""Exact line-for-line mirror of gre24_features_v2.features using injected solver."""
g = mg.mesh_numpy(points, tetra)
faces = mg.exterior_faces_numpy(g['t'])
sources, _ = mg.gate_nodes_numpy(g['x'], raw_ids, gate, None)
wall = np.unique(faces)
dw = solver_fn(g, wall, 1.)
di = solver_fn(g, sources, 1.)
speed, zero = mg.cell_flow_speed_numpy(g, dw, faces)
df = solver_fn(g, sources, speed)
vf = mg.strict_volume_cdf_numpy(df, g['mass'])
dis = di / di.max()
dws = dw / dw.max()
grads = [mg.nodal_gradient_numpy(g, a) for a in (vf, dis, dws)]
moment, _ = mg.spatial_moment_numpy(g, di)
x = np.column_stack([vf, grads[0], dis, grads[1], dw, dws, grads[2], moment])
return dict(features=x, Dw=dw, Di=di, Df=df, Vf=vf, mass=g['mass'], all_wall_tet_ids=zero)
class TestMultigateFeatures(unittest.TestCase):
def test_single_gate_byte_identical_numpy_backend(self):
pts, tet, _ = symmetric_box_mesh(nx_half=4, ny=3, nz=3)
raw_ids = np.arange(100, 100 + len(pts), dtype=np.int64)
gate = np.array([-1.0, 0.0, 0.0])
ref = _single_gate_reference_numpy(pts, tet, raw_ids, gate, tet_edge_dijkstra_solver)
out, meta = mg.features(pts, tet, raw_ids, [gate], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
self.assertEqual(meta['num_gates'], 1)
self.assertEqual(out['features'].shape, (len(pts), 19))
for key in ('features', 'Dw', 'Di', 'Df', 'Vf', 'mass', 'all_wall_tet_ids'):
self.assertEqual(out[key].dtype, ref[key].dtype, msg=key)
self.assertEqual(out[key].shape, ref[key].shape, msg=key)
self.assertEqual(out[key].tobytes(), ref[key].tobytes(), msg=f'Not byte-identical on {key}')
self.assertEqual(out['Di_per_gate'][:, 0].tobytes(), ref['Di'].tobytes())
self.assertEqual(out['Df_per_gate'][:, 0].tobytes(), ref['Df'].tobytes())
np.testing.assert_array_equal(out['nearest_gate'], np.zeros(len(pts), dtype=np.int64))
self.assertFalse(bool(out['gate_tie_mask_df'].any()))
def test_single_gate_byte_identical_production_when_deps_available(self):
has_prod = all(importlib.util.find_spec(m) is not None for m in ('fimpy', 'sklearn', 'scipy'))
pts, tet, _ = symmetric_box_mesh(nx_half=3, ny=3, nz=3)
raw_ids = np.arange(len(pts), dtype=np.int64)
gate = np.array([-1.0, 0.0, 0.0])
if not has_prod:
# Verify production default fails closed when fimpy/sklearn/scipy are absent.
with self.assertRaises(ModuleNotFoundError):
mg.features(pts, tet, raw_ids, [gate], backend='production')
return
import gre24_features_v2 as g24
ref, _ = g24.features(pts, tet, raw_ids, gate)
out, _ = mg.features(pts, tet, raw_ids, [gate], backend='production')
for key in ('features', 'Dw', 'Di', 'Df', 'Vf', 'mass', 'all_wall_tet_ids'):
self.assertEqual(out[key].tobytes(), ref[key].tobytes(), msg=f'Production K=1 mismatch on {key}')
def test_two_symmetric_gates_produce_symmetric_fields(self):
pts, tet, mirror = symmetric_box_mesh(nx_half=5, ny=3, nz=3, half_len=1.0)
self.assertTrue(np.array_equal(mirror[mirror], np.arange(len(pts))))
raw_ids = np.arange(len(pts), dtype=np.int64)
gates = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
out, meta = mg.features(pts, tet, raw_ids, gates, backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
self.assertEqual(meta['num_gates'], 2)
# Scalar fields are mirror-even.
for key in ('Dw', 'Di', 'Df', 'Vf'):
np.testing.assert_allclose(out[key][mirror], out[key], atol=1e-12, rtol=1e-12, err_msg=key)
# Per-gate distances swap gate 0 <-> gate 1 under reflection.
np.testing.assert_allclose(out['Di_per_gate'][mirror, 0], out['Di_per_gate'][:, 1], atol=1e-12, rtol=1e-12)
np.testing.assert_allclose(out['Df_per_gate'][mirror, 0], out['Df_per_gate'][:, 1], atol=1e-12, rtol=1e-12)
np.testing.assert_allclose(out['Di_per_gate_star'][mirror, 0], out['Di_per_gate_star'][:, 1], atol=1e-12, rtol=1e-12)
np.testing.assert_allclose(out['Df_per_gate_star'][mirror, 0], out['Df_per_gate_star'][:, 1], atol=1e-12, rtol=1e-12)
# Base 19 columns: Vf (0), Di_star (4), Dw (8), Dw_star (9) even; gradients reflect x -> -x.
x19 = out['features']
for col in (0, 4, 8, 9):
np.testing.assert_allclose(x19[mirror, col], x19[:, col], atol=1e-12, rtol=1e-12)
for gstart in (1, 5, 10):
np.testing.assert_allclose(x19[mirror, gstart], -x19[:, gstart], atol=1e-11, rtol=1e-11)
np.testing.assert_allclose(x19[mirror, gstart + 1:gstart + 3], x19[:, gstart + 1:gstart + 3], atol=1e-11, rtol=1e-11)
# Spatial moment tensor parity under x -> -x: Sxx(13), Syy(16), Syz(17), Szz(18) even; Sxy(14), Sxz(15) odd.
for col in (13, 16, 17, 18):
np.testing.assert_allclose(x19[mirror, col], x19[:, col], atol=1e-11, rtol=1e-11)
for col in (14, 15):
np.testing.assert_allclose(x19[mirror, col], -x19[:, col], atol=1e-11, rtol=1e-11)
# Nearest gate swaps 0 <-> 1 off symmetry plane; symmetry plane is marked tied.
on_plane = np.isclose(pts[:, 0], 0.0, atol=1e-12)
self.assertTrue(bool(out['gate_tie_mask_df'][on_plane].all()))
self.assertTrue(bool(out['gate_tie_mask_di'][on_plane].all()))
off = ~on_plane
np.testing.assert_array_equal(out['nearest_gate_df'][mirror[off]], 1 - out['nearest_gate_df'][off])
np.testing.assert_array_equal(out['nearest_gate_di'][mirror[off]], 1 - out['nearest_gate_di'][off])
def test_moving_one_gate_changes_only_affected_region(self):
pts, tet, _ = symmetric_box_mesh(nx_half=7, ny=3, nz=3, half_len=2.0)
raw_ids = np.arange(len(pts), dtype=np.int64)
g0 = np.array([-2.0, 0.0, 0.0])
g1_old = np.array([2.0, 0.0, 0.0])
g1_new = np.array([1.5, 0.0, 0.0])
out_old, _ = mg.features(pts, tet, raw_ids, [g0, g1_old], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
out_new, _ = mg.features(pts, tet, raw_ids, [g0, g1_new], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
# Unmoved gate channel and wall fields are byte-identical everywhere.
self.assertEqual(out_old['Dw'].tobytes(), out_new['Dw'].tobytes())
self.assertEqual(out_old['Di_per_gate'][:, 0].tobytes(), out_new['Di_per_gate'][:, 0].tobytes())
self.assertEqual(out_old['Df_per_gate'][:, 0].tobytes(), out_new['Df_per_gate'][:, 0].tobytes())
# Outside the affected basin of gate 1 (nodes owned by gate 0 in both runs),
# minimum arrival distances and nearest-gate index are byte-identical.
unaffected_di = (out_old['nearest_gate_di'] == 0) & (out_new['nearest_gate_di'] == 0)
unaffected_df = (out_old['nearest_gate_df'] == 0) & (out_new['nearest_gate_df'] == 0)
self.assertGreater(int(unaffected_di.sum()), 10)
self.assertGreater(int(unaffected_df.sum()), 10)
self.assertEqual(out_old['Di'][unaffected_di].tobytes(), out_new['Di'][unaffected_di].tobytes())
self.assertEqual(out_old['Df'][unaffected_df].tobytes(), out_new['Df'][unaffected_df].tobytes())
np.testing.assert_array_equal(out_old['nearest_gate_di'][unaffected_di], out_new['nearest_gate_di'][unaffected_di])
np.testing.assert_array_equal(out_old['nearest_gate_df'][unaffected_df], out_new['nearest_gate_df'][unaffected_df])
# Inside gate 1's affected region, distances and Vf genuinely change.
affected_df = ~unaffected_df
self.assertGreater(int(affected_df.sum()), 10)
self.assertGreater(float(np.max(np.abs(out_old['Df'][affected_df] - out_new['Df'][affected_df]))), 1e-3)
self.assertGreater(float(np.max(np.abs(out_old['Vf'] - out_new['Vf']))), 1e-3)
def test_three_gates_packing_marked_gates_and_guards(self):
pts, tet, _ = symmetric_box_mesh(nx_half=4, ny=3, nz=3, half_len=1.0)
raw_ids = np.arange(len(pts), dtype=np.int64)
gates = [[-1.0, 0.0, 0.0], [0.0, 0.5, 0.0], [1.0, 0.0, 0.0]]
out, meta = mg.features(pts, tet, raw_ids, gates, backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
self.assertEqual(meta['num_gates'], 3)
packed, cols = mg.pack_multigate_features(out)
self.assertEqual(packed.shape, (len(pts), 19 + 2 * 3 + 1))
self.assertEqual(len(cols), 26)
self.assertTrue(np.isfinite(packed).all())
# Vf is monotone non-decreasing with Df_min.
order = np.argsort(out['Df'], kind='stable')
self.assertTrue(bool(np.all(np.diff(out['Vf'][order]) >= -1e-15)))
# Explicit marked_gates works without coordinates.
out_m, meta_m = mg.features(pts, tet, raw_ids, None, marked_gates=[[0], [len(pts) - 1]],
backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
self.assertEqual(meta_m['num_gates'], 2)
self.assertEqual(out_m['Di_per_gate'].shape, (len(pts), 2))
# Fail-closed validation checks.
with self.assertRaises(ValueError):
mg.features(pts, tet, raw_ids, [], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
with self.assertRaises(ValueError):
mg.features(pts, tet, raw_ids, [[np.nan, 0.0, 0.0]], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
with self.assertRaises(ValueError):
mg.features(pts, tet, raw_ids, gates, backend='numpy', eikonal_solver=None)
if __name__ == '__main__':
unittest.main(verbosity=2)
+155
View File
@@ -0,0 +1,155 @@
"""CPU-only synthetic tests for track_b_transolver_greif_adapter (no real data, no GPU)."""
import sys
import unittest
from pathlib import Path
import numpy as np
import torch
sys.path.insert(0, str(Path(__file__).resolve().parent))
import phase2_h2_model as h2
import track_b_gino_greif_adapter as gino
import track_b_transolver_greif_adapter as tv
def synthetic_tet_part(seed, nx=4, ny=4, nz=3, second_component=False):
"""Build a synthetic 3D tet mesh with lumped positive nodal masses and 19 features."""
rng = np.random.default_rng(seed)
xs, ys, zs = np.meshgrid(np.linspace(0.0, 1.0, nx), np.linspace(0.0, 0.8, ny), np.linspace(0.0, 0.4, nz), indexing='ij')
pts = np.column_stack([xs.ravel(), ys.ravel(), zs.ravel()])
pts += rng.normal(0.0, 0.01, size=pts.shape)
n0 = len(pts)
idx = np.arange(n0).reshape(nx, ny, nz)
tets = []
for i in range(nx - 1):
for j in range(ny - 1):
for k in range(nz - 1):
c = [idx[i + a, j + b, k + c_] for a in (0, 1) for b in (0, 1) for c_ in (0, 1)]
for t in ((0, 1, 3, 7), (0, 1, 5, 7), (0, 4, 5, 7), (0, 2, 3, 7), (0, 2, 6, 7), (0, 4, 6, 7)):
tets.append([c[p] for p in t])
tets = np.asarray(tets, dtype=np.int64)
comp = np.zeros(n0, dtype=np.int64)
if second_component:
pts2 = pts[:12] + np.array([2.0, 0.0, 0.0])
pts = np.vstack([pts, pts2])
extra = np.array([[n0 + i, n0 + i + 1, n0 + i + 2, n0 + i + 3] for i in range(0, 9, 3)], dtype=np.int64)
tets = np.vstack([tets, extra])
comp = np.concatenate([comp, np.ones(len(pts2), dtype=np.int64)])
n = len(pts)
mass = np.zeros(n, dtype=np.float64)
v0, v1, v2, v3 = pts[tets[:, 0]], pts[tets[:, 1]], pts[tets[:, 2]], pts[tets[:, 3]]
vol = np.abs(np.einsum('ij,ij->i', v1 - v0, np.cross(v2 - v0, v3 - v0))) / 6.0
vol = np.maximum(vol, 1e-6)
for corner in range(4):
np.add.at(mass, tets[:, corner], vol / 4.0)
mass = np.maximum(mass, 1e-7)
vf = np.clip(np.argsort(np.argsort(pts[:, 0])).astype(np.float64) / max(n - 1, 1), 0.0, 1.0)
feats = rng.normal(0.0, 1.0, size=(n, len(tv.COLUMNS))).astype(np.float64)
feats[:, 0] = vf
target_star = np.clip(0.95 * vf + 0.05 * rng.normal(size=n), 0.0, None)
return dict(points=pts, tets=tets, mass=mass, features=feats, Vf=vf, target_star=target_star, component_ids=comp)
class TestTransolverGreifAdapter(unittest.TestCase):
def setUp(self):
torch.set_num_threads(1)
self.parts = [synthetic_tet_part(10 + i, second_component=(i == 1)) for i in range(2)]
self.stats = tv.standardize_learning_arrays([p['features'] for p in self.parts])
self.clock = tv.learning_clock([0.96, 1.02], ['fam_a', 'fam_b'])
def test_interface_and_parameter_counts(self):
self.assertEqual(len(tv.COLUMNS), 19)
self.assertEqual(tv.COLUMNS, gino.COLUMNS)
h2_params = tv.count_parameters(h2.H2Geo())
default_params = tv.count_parameters(tv.make_greif_transolver('default'))
wide_params = tv.count_parameters(tv.make_greif_transolver('wide'))
unweighted_params = tv.count_parameters(tv.make_greif_transolver('default', mass_weighted=False))
self.assertEqual(h2_params, 195077)
self.assertEqual(default_params, 197913)
self.assertEqual(wide_params, 293937)
self.assertEqual(unweighted_params, default_params)
def test_zero_init_starts_at_exact_volume_clock_prior(self):
torch.manual_seed(0)
model = tv.make_greif_transolver('default')
p = self.parts[0]
x, m, comp = tv.prepare_inputs(p['features'], p['mass'], self.stats, p['component_ids'])
pred = model(x, m, comp, checkpoint_blocks=False)
self.assertEqual(pred.shape, (len(p['mass']),))
self.assertEqual(pred.dtype, torch.float32)
self.assertTrue(torch.allclose(pred, torch.zeros_like(pred), atol=0.0))
decoded = tv.decode_seconds(pred.detach().numpy(), p['Vf'], self.clock, t_set=2.5)
expected = tv.prior(p['Vf'], self.clock) * 2.5
np.testing.assert_allclose(decoded, expected, rtol=0.0, atol=1e-12)
def test_forward_backward_step_and_multicomponent(self):
torch.manual_seed(7)
model = tv.make_greif_transolver('default')
opt = tv.optimizer(model)
total_nodes = sum(len(p['mass']) for p in self.parts)
for p in self.parts:
x, m, comp = tv.prepare_inputs(p['features'], p['mass'], self.stats, p['component_ids'])
target = torch.from_numpy(tv.residual_target(p['target_star'], p['Vf'], self.clock, fit_dtype='float32'))
opt.zero_grad(set_to_none=True)
pred = model(x, m, comp, node_chunk=17, checkpoint_blocks=True)
loss = tv.weighted_loss(pred, target, len(self.parts), len(m), total_nodes)
self.assertTrue(bool(torch.isfinite(loss)))
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0, error_if_nonfinite=True)
opt.step()
self.assertTrue(all(bool(torch.isfinite(v).all()) for v in model.parameters()))
# After 1 step, head output moves away from zero and gradients reached encoder + physics slices.
self.assertGreater(float(model.head[-1].weight.detach().abs().max()), 0.0)
x, m, comp = tv.prepare_inputs(self.parts[1]['features'], self.parts[1]['mass'], self.stats, self.parts[1]['component_ids'])
out = model(x, m, comp, checkpoint_blocks=False)
out.sum().backward()
self.assertGreater(float(model.encoder[0].weight.grad.abs().max()), 0.0)
self.assertGreater(float(model.blocks[0].attn.in_project_slice.weight.grad.abs().max()), 0.0)
def test_determinism_chunk_invariance_and_mass_scale_invariance(self):
p = self.parts[1]
x, m, comp = tv.prepare_inputs(p['features'], p['mass'], self.stats, p['component_ids'])
target = torch.from_numpy(tv.residual_target(p['target_star'], p['Vf'], self.clock, fit_dtype='float32'))
def run_once(chunk, mass_scale=1.0):
torch.manual_seed(1234)
model = tv.make_greif_transolver('default')
opt = tv.optimizer(model)
for _ in range(2):
opt.zero_grad(set_to_none=True)
pred = model(x, m * mass_scale, comp, node_chunk=chunk, checkpoint_blocks=False)
loss = tv.weighted_loss(pred, target, 1, len(m), len(m))
loss.backward()
opt.step()
model.eval()
with torch.no_grad():
return model(x, m * mass_scale, comp, node_chunk=chunk, checkpoint_blocks=False)
a = run_once(chunk=tv.NODE_CHUNK)
b = run_once(chunk=tv.NODE_CHUNK)
c = run_once(chunk=13)
d = run_once(chunk=tv.NODE_CHUNK, mass_scale=1e-4)
self.assertTrue(torch.equal(a, b))
self.assertTrue(torch.allclose(a, c, atol=1e-6, rtol=1e-5))
self.assertTrue(torch.allclose(a, d, atol=1e-6, rtol=1e-5))
def test_input_guards(self):
model = tv.make_greif_transolver('default')
p = self.parts[0]
x, m, comp = tv.prepare_inputs(p['features'], p['mass'], self.stats, p['component_ids'])
with self.assertRaises(ValueError):
model(x[:, :18], m, comp)
with self.assertRaises(ValueError):
model(x.double(), m, comp)
bad_m = m.clone()
bad_m[0] = 0.0
with self.assertRaises(ValueError):
model(x, bad_m, comp)
bad_x = x.clone()
bad_x[0, 0] = float('nan')
with self.assertRaises(ValueError):
model(bad_x, m, comp)
if __name__ == '__main__':
unittest.main(verbosity=2)
+204
View File
@@ -0,0 +1,204 @@
"""Transolver (Wu et al., ICML 2024) adapter for grouped Greif fill-time comparison.
Pure unstructured-node Physics-Attention model matching H2Geo and GreifGINO:
exact 19 standardized FP32 inputs, positive nodal mass, FP64 volume-clock
residual target/decode, and zero-initialized readout starting at the c*Vf prior.
Code only: no real-data I/O, no GPU launch, no external checkpoint access.
"""
import math
import numpy as np
import torch
from torch import nn
from torch.utils.checkpoint import checkpoint
from phase2_h2_model import lr_epoch, optimizer, weighted_loss
from phase2_residual_math import decode_seconds, learning_clock, prior, residual_target
from track_b_gino_greif_adapter import COLUMNS
NODE_CHUNK = 8192
TEMP_MIN = 0.1
TEMP_MAX = 5.0
MASS_EPS = 1e-6
UNWEIGHTED_EPS = 1e-5
VARIANTS = {
'default': dict(dim=64, depth=6, heads=4, slices=64, mlp_ratio=2),
'wide': dict(dim=96, depth=4, heads=4, slices=64, mlp_ratio=2),
}
def count_parameters(model):
return sum(p.numel() for p in model.parameters())
def standardize_learning_arrays(feature_arrays):
"""FP64 online population mean/std over learning parts only (matches phase2_h2_data)."""
n = 0
mean = np.zeros(len(COLUMNS), dtype=np.float64)
m2 = np.zeros(len(COLUMNS), dtype=np.float64)
for arr in feature_arrays:
x = np.asarray(arr, dtype=np.float64)
if x.ndim != 2 or x.shape[1] != len(COLUMNS) or len(x) == 0 or not np.isfinite(x).all():
raise ValueError('Invalid learning feature array')
k = len(x)
avg = x.mean(axis=0)
delta = avg - mean
m2 += np.square(x - avg).sum(axis=0) + delta * delta * (n * k / (n + k))
mean += delta * (k / (n + k))
n += k
if n == 0:
raise ValueError('Empty learning set')
std = np.sqrt(m2 / n)
scale = np.where(std == 0.0, 1.0, std)
return dict(mean=mean.tolist(), scale=scale.tolist(), population_std=std.tolist(), nodes=n)
def prepare_inputs(features, mass, stats, component_ids=None):
"""Standardize 19 columns in FP64 -> FP32 and validate positive mass and components."""
feat = np.asarray(features, dtype=np.float64)
m = np.asarray(mass, dtype=np.float64)
if feat.ndim != 2 or feat.shape[1] != len(COLUMNS) or len(feat) == 0:
raise ValueError('Expected nonempty (N, 19) feature matrix matching COLUMNS')
if m.shape != (len(feat),) or not np.isfinite(m).all() or np.any(m <= 0):
raise ValueError('Expected finite strictly positive nodal mass')
x = ((feat - np.asarray(stats['mean'], np.float64)) / np.asarray(stats['scale'], np.float64)).astype(np.float32)
if not np.isfinite(x).all():
raise ValueError('Nonfinite standardized features')
if component_ids is None:
comp = np.zeros(len(feat), dtype=np.int64)
else:
comp = np.asarray(component_ids, dtype=np.int64)
if comp.shape != (len(feat),):
raise ValueError('component_ids shape mismatch')
return torch.from_numpy(x), torch.from_numpy(m.astype(np.float32)), torch.from_numpy(comp)
class PhysicsAttention(nn.Module):
"""Chunked multi-head Physics-Attention over learned slices (Wu et al., ICML 2024)."""
def __init__(self, dim=64, heads=4, slices=64, mass_weighted=True):
super().__init__()
if dim % heads != 0 or slices <= 0:
raise ValueError('dim must be divisible by heads and slices > 0')
self.dim = dim
self.heads = heads
self.head_dim = dim // heads
self.slices = slices
self.mass_weighted = bool(mass_weighted)
self.scale = self.head_dim ** -0.5
self.in_project_x = nn.Linear(dim, dim)
self.in_project_fx = nn.Linear(dim, dim)
self.in_project_slice = nn.Linear(self.head_dim, slices)
nn.init.orthogonal_(self.in_project_slice.weight)
self.temperature = nn.Parameter(torch.full((1, heads, 1), 0.5))
self.to_q = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.to_k = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.to_v = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.to_out = nn.Linear(dim, dim)
def forward(self, h, m, components, node_chunk):
out = h.new_zeros(h.shape)
temp = torch.clamp(self.temperature, min=TEMP_MIN, max=TEMP_MAX)
eps = MASS_EPS if self.mass_weighted else UNWEIGHTED_EPS
for ids in components:
m_comp = m[ids]
m_sum = m_comp.sum()
if not bool(torch.isfinite(m_sum)) or float(m_sum) <= 0.0:
raise ValueError('Invalid component mass sum')
m_norm = m_comp / m_sum
num = h.new_zeros((self.heads, self.slices, self.head_dim))
den = h.new_zeros((self.heads, self.slices))
chunks = []
for lo in range(0, len(ids), node_chunk):
hi = lo + node_chunk
ix = ids[lo:hi]
hh = h[ix]
x_mid = self.in_project_x(hh).view(-1, self.heads, self.head_dim)
fx_mid = self.in_project_fx(hh).view(-1, self.heads, self.head_dim)
w = torch.softmax(self.in_project_slice(x_mid) / temp, dim=-1)
weight = w * m_norm[lo:hi, None, None] if self.mass_weighted else w
num = num + torch.einsum('nhg,nhd->hgd', weight, fx_mid)
den = den + weight.sum(dim=0)
chunks.append((ix, w))
if not bool(torch.isfinite(den).all()):
raise ValueError('Nonfinite physics-slice denominator')
tokens = num / (den.unsqueeze(-1) + eps)
q, k, v = self.to_q(tokens), self.to_k(tokens), self.to_v(tokens)
attn = torch.softmax(torch.matmul(q, k.transpose(-2, -1)) * self.scale, dim=-1)
z = torch.matmul(attn, v)
for ix, w in chunks:
desliced = torch.einsum('nhg,hgd->nhd', w, z).reshape(-1, self.dim)
out.index_copy_(0, ix, self.to_out(desliced))
return out
class TransolverBlock(nn.Module):
def __init__(self, dim=64, heads=4, slices=64, mlp_ratio=2, mass_weighted=True):
super().__init__()
self.attn_norm = nn.LayerNorm(dim)
self.attn = PhysicsAttention(dim=dim, heads=heads, slices=slices, mass_weighted=mass_weighted)
self.ffn_norm = nn.LayerNorm(dim)
self.ffn = nn.Sequential(nn.Linear(dim, dim * mlp_ratio), nn.GELU(), nn.Linear(dim * mlp_ratio, dim))
def forward(self, h, m, components, node_chunk):
h = h + self.attn(self.attn_norm(h), m, components, node_chunk)
return h + self.ffn(self.ffn_norm(h))
class GreifTransolver(nn.Module):
"""Per-part Transolver residual regressor aligned with H2Geo and GreifGINO."""
def __init__(self, dim=64, depth=6, heads=4, slices=64, mlp_ratio=2, mass_weighted=True):
super().__init__()
self.dim = dim
self.depth = depth
self.heads = heads
self.slices = slices
self.mlp_ratio = mlp_ratio
self.mass_weighted = bool(mass_weighted)
self.encoder = nn.Sequential(nn.Linear(len(COLUMNS), dim), nn.GELU(), nn.Linear(dim, dim))
self.blocks = nn.ModuleList([
TransolverBlock(dim=dim, heads=heads, slices=slices, mlp_ratio=mlp_ratio, mass_weighted=mass_weighted)
for _ in range(depth)
])
self.head = nn.Sequential(nn.Linear(dim + len(COLUMNS), 64), nn.GELU(), nn.Linear(64, 1))
nn.init.zeros_(self.head[-1].weight)
nn.init.zeros_(self.head[-1].bias)
def forward(self, x, m, component_ids=None, *, node_chunk=NODE_CHUNK, checkpoint_blocks=True):
if x.ndim != 2 or x.shape[1] != len(COLUMNS) or len(x) == 0:
raise ValueError('Expected nonempty (N, 19) FP32 features')
if x.dtype != torch.float32 or m.dtype != torch.float32:
raise ValueError('Only FP32 features and mass are supported')
if m.shape != (len(x),) or not bool(torch.isfinite(x).all()) or not bool(torch.isfinite(m).all()) or bool((m <= 0).any()):
raise ValueError('Invalid features or nonpositive nodal mass')
if component_ids is None:
components = [torch.arange(len(x), device=x.device, dtype=torch.long)]
else:
if component_ids.shape != (len(x),) or component_ids.dtype not in (torch.int32, torch.int64):
raise ValueError('component_ids must be 1D integer tensor matching nodes')
components = [torch.nonzero(component_ids == c, as_tuple=True)[0] for c in torch.unique(component_ids)]
h = self.encoder(x)
for block in self.blocks:
def run(v, b=block):
return b(v, m, components, node_chunk)
if checkpoint_blocks and self.training and torch.is_grad_enabled():
h = checkpoint(run, h, use_reentrant=False, preserve_rng_state=False)
else:
h = run(h)
outputs = [self.head(torch.cat((h[lo:lo + node_chunk], x[lo:lo + node_chunk]), dim=-1))[:, 0]
for lo in range(0, len(x), node_chunk)]
return torch.cat(outputs)
def make_greif_transolver(variant='default', *, mass_weighted=True):
if variant not in VARIANTS:
raise ValueError(f'Unknown variant: {variant}')
return GreifTransolver(**VARIANTS[variant], mass_weighted=mass_weighted)
__all__ = [
'COLUMNS', 'NODE_CHUNK', 'VARIANTS', 'GreifTransolver', 'PhysicsAttention', 'TransolverBlock',
'count_parameters', 'decode_seconds', 'learning_clock', 'lr_epoch', 'make_greif_transolver',
'optimizer', 'prepare_inputs', 'prior', 'residual_target', 'standardize_learning_arrays', 'weighted_loss',
]