Record reproduced fp16 overflow and freeze isolated FP32-slice pilot v2

This commit is contained in:
Frank14f committed 2026-11-15 06:27:43 +08:00
1 parent f502b7b9f8
commit 8a548cc259
28 files changed
+13918

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Declared S2 precision variant; original s2_models remains immutable."""
+62
View File
@@ -0,0 +1,62 @@
# Adapted from Transolver 75e0f676; MIT, see upstream/LICENSE.
import torch.nn as nn
import torch
class Physics_Attention_Irregular_Mesh(nn.Module):
## for irregular meshes in 1D, 2D or 3D space
def __init__(self, dim, heads=8, dim_head=64, dropout=0., slice_num=64):
super().__init__()
inner_dim = dim_head * heads
self.dim_head = dim_head
self.heads = heads
self.scale = dim_head ** -0.5
self.softmax = nn.Softmax(dim=-1)
self.dropout = nn.Dropout(dropout)
self.temperature = nn.Parameter(torch.ones([1, heads, 1, 1]) * 0.5)
self.in_project_x = nn.Linear(dim, inner_dim)
self.in_project_fx = nn.Linear(dim, inner_dim)
self.in_project_slice = nn.Linear(dim_head, slice_num)
for l in [self.in_project_slice]:
torch.nn.init.orthogonal_(l.weight) # use a principled initialization
self.to_q = nn.Linear(dim_head, dim_head, bias=False)
self.to_k = nn.Linear(dim_head, dim_head, bias=False)
self.to_v = nn.Linear(dim_head, dim_head, bias=False)
self.to_out = nn.Sequential(
nn.Linear(inner_dim, dim),
nn.Dropout(dropout)
)
def forward(self, x):
# B N C
B, N, C = x.shape
### (1) Slice
fx_mid = self.in_project_fx(x).reshape(B, N, self.heads, self.dim_head) \
.permute(0, 2, 1, 3).contiguous() # B H N C
x_mid = self.in_project_x(x).reshape(B, N, self.heads, self.dim_head) \
.permute(0, 2, 1, 3).contiguous() # B H N C
slice_weights = self.softmax(self.in_project_slice(x_mid) / self.temperature) # B H N G
# Declared precision fix: the full-node sum can exceed fp16's range.
# Shared by N/E; projections, attention, deslicing and optimizer unchanged.
with torch.autocast(device_type=x.device.type, enabled=False):
slice_norm = slice_weights.float().sum(2) # B H G
slice_token = torch.einsum("bhnc,bhng->bhgc", fx_mid.float(), slice_weights.float())
slice_token = slice_token / ((slice_norm + 1e-5)[:, :, :, None].repeat(1, 1, 1, self.dim_head))
### (2) Attention among slice tokens
q_slice_token = self.to_q(slice_token)
k_slice_token = self.to_k(slice_token)
v_slice_token = self.to_v(slice_token)
dots = torch.matmul(q_slice_token, k_slice_token.transpose(-1, -2)) * self.scale
attn = self.softmax(dots)
attn = self.dropout(attn)
out_slice_token = torch.matmul(attn, v_slice_token) # B H G D
### (3) Deslice
out_x = torch.einsum("bhgc,bhng->bhnc", out_slice_token, slice_weights)
out_x = out_x.permute(0, 2, 1, 3).reshape(B, N, -1)
return self.to_out(out_x)
+71
View File
@@ -0,0 +1,71 @@
# Adapted from Transolver 75e0f676; MIT, see upstream/LICENSE.
import torch
import torch.nn as nn
from .attention import Physics_Attention_Irregular_Mesh
ACTIVATION = {'gelu': nn.GELU, 'tanh': nn.Tanh, 'sigmoid': nn.Sigmoid, 'relu': nn.ReLU, 'leaky_relu': nn.LeakyReLU(0.1),
'softplus': nn.Softplus, 'ELU': nn.ELU, 'silu': nn.SiLU}
class MLP(nn.Module):
def __init__(self, n_input, n_hidden, n_output, n_layers=1, act='gelu', res=True):
super(MLP, self).__init__()
if act in ACTIVATION.keys():
act = ACTIVATION[act]
else:
raise NotImplementedError
self.n_input = n_input
self.n_hidden = n_hidden
self.n_output = n_output
self.n_layers = n_layers
self.res = res
self.linear_pre = nn.Sequential(nn.Linear(n_input, n_hidden), act())
self.linear_post = nn.Linear(n_hidden, n_output)
self.linears = nn.ModuleList([nn.Sequential(nn.Linear(n_hidden, n_hidden), act()) for _ in range(n_layers)])
def forward(self, x):
x = self.linear_pre(x)
for i in range(self.n_layers):
if self.res:
x = self.linears[i](x) + x
else:
x = self.linears[i](x)
x = self.linear_post(x)
return x
class Transolver_block(nn.Module):
"""Transformer encoder block."""
def __init__(
self,
num_heads: int,
hidden_dim: int,
dropout: float,
act='gelu',
mlp_ratio=4,
last_layer=False,
out_dim=1,
slice_num=32,
):
super().__init__()
self.last_layer = last_layer
self.ln_1 = nn.LayerNorm(hidden_dim)
self.Attn = Physics_Attention_Irregular_Mesh(hidden_dim, heads=num_heads, dim_head=hidden_dim // num_heads,
dropout=dropout, slice_num=slice_num)
self.ln_2 = nn.LayerNorm(hidden_dim)
self.mlp = MLP(hidden_dim, hidden_dim * mlp_ratio, hidden_dim, n_layers=0, res=False, act=act)
if self.last_layer:
self.ln_3 = nn.LayerNorm(hidden_dim)
self.mlp2 = nn.Linear(hidden_dim, out_dim)
def forward(self, fx):
fx = self.Attn(self.ln_1(fx)) + fx
fx = self.mlp(self.ln_2(fx)) + fx
if self.last_layer:
return self.mlp2(self.ln_3(fx))
else:
return fx
+119
View File
@@ -0,0 +1,119 @@
"""Transolver 75e0f676 encoder adaptation + S2 query-only N/E decoders.
No optimiser, training loop, data reader or GPU invocation is provided.
"""
import torch
from torch import nn
from .blocks import MLP, Transolver_block
from s2_models.features import BASE_COLUMNS
from s2_models.normalization import BaseStandardizer
TRAINING_CONTRACT = dict(optimizer="AdamW", learning_rate=1e-3, weight_decay=1e-5,
schedule="cosine", batch_parts=1, max_epochs=200,
patience=20, seeds=[0, 1, 2], widths=[128, 256])
def check_tensor(tensor, shape, name):
if tuple(tensor.shape) != tuple(shape) or not torch.isfinite(tensor).all():
raise ValueError(f"invalid {name}")
class WholePartEncoder(nn.Module):
def __init__(self, width, standardizer):
super().__init__()
if width not in (128, 256):
raise ValueError("S2 permits widths 128 or 256 only")
if not isinstance(standardizer, BaseStandardizer):
raise ValueError("frozen learning-pool standardizer required")
self.standardizer = standardizer
self.register_buffer("base_mean", torch.tensor(standardizer.mean, dtype=torch.float64))
self.register_buffer("base_scale", torch.tensor(standardizer.scale, dtype=torch.float64))
self.preprocess = MLP(len(BASE_COLUMNS), width*2, width, n_layers=0, res=False)
self.blocks = nn.ModuleList([Transolver_block(num_heads=8, hidden_dim=width,
dropout=0., mlp_ratio=1, slice_num=32,
last_layer=False) for _ in range(4)])
self.apply(self._initialize)
self.placeholder = nn.Parameter(torch.rand(width)/width)
@staticmethod
def _initialize(module):
# torch.nn.init replaces timm's same trunc_normal_ defaults; no timm dependency.
if isinstance(module, nn.Linear):
nn.init.trunc_normal_(module.weight, std=.02)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
nn.init.zeros_(module.bias)
nn.init.ones_(module.weight)
def forward(self, base):
if base.ndim != 2 or base.shape[0] == 0:
raise ValueError("one whole part with all tet nodes required")
check_tensor(base, (base.shape[0], len(BASE_COLUMNS)), "base inputs")
# Keep normalisation in FP32 even under future mixed-precision training.
base = (base.float()-self.base_mean.float()) / self.base_scale.float()
if not torch.isfinite(base).all():
raise ValueError("nonfinite standardized base input")
fx = self.preprocess(base[None]) + self.placeholder[None, None]
for block in self.blocks:
fx = block(fx)
if not torch.isfinite(fx).all():
raise ValueError("nonfinite encoder output")
return fx[0]
class QueryModel(nn.Module):
def __init__(self, arm, width=128, *, standardizer):
super().__init__()
if arm not in ("N", "E"):
raise ValueError("arm must be N or E")
self.arm, self.width = arm, width
self.encoder = WholePartEncoder(width, standardizer)
query_dim = 2 if arm == "N" else 6
self.decoder = nn.Sequential(nn.Linear(width+query_dim, width), nn.GELU(),
nn.Linear(width, width), nn.GELU(), nn.Linear(width, 1))
self.decoder.apply(WholePartEncoder._initialize)
def forward(self, base, query_ids, gaps, edge_q=None):
if query_ids.ndim != 1 or query_ids.dtype != torch.long or query_ids.numel() == 0:
raise ValueError("nonempty int64 original-node query IDs required")
if int(query_ids.min()) < 0 or int(query_ids.max()) >= len(base):
raise ValueError("query node outside whole part")
check_tensor(gaps, (len(query_ids), 2), "g12/g23")
if self.arm == "E":
if edge_q is None:
raise ValueError("E requires all four edge summaries")
check_tensor(edge_q, (len(query_ids), 4), "edge summaries")
local = torch.cat([gaps, edge_q], dim=-1)
else:
if edge_q is not None:
raise ValueError("N must not receive edge summaries")
local = gaps
embedding = self.encoder(base)[query_ids]
y = self.decoder(torch.cat([embedding, local], dim=-1)).squeeze(-1)
if not torch.isfinite(y).all():
raise ValueError("nonfinite decoder output")
return y
def parameter_counts(self):
return {"encoder": sum(p.numel() for p in self.encoder.parameters()),
"decoder": sum(p.numel() for p in self.decoder.parameters()),
"total": sum(p.numel() for p in self.parameters())}
def weighted_mse(prediction, target, global_weights):
"""Sum of contributions with already globally-normalised hierarchy weights.
Do not renormalise a single part's weights: that would erase component balance.
"""
if prediction.ndim != 1 or prediction.numel() == 0:
raise ValueError("nonempty query predictions required")
check_tensor(prediction, prediction.shape, "prediction")
check_tensor(target, prediction.shape, "target")
check_tensor(global_weights, prediction.shape, "weights")
if (global_weights <= 0).any():
raise ValueError("positive hierarchy weights required")
# FP32 arithmetic under future AMP; do not form residuals in float16.
return torch.sum(global_weights.float() * (prediction.float()-target.float()).square())