Files
MeltMind/tools/track_b_gino_greif_adapter.py

101 lines
4.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Greif node-to-grid integral, Tucker FNO, and grid-to-original-node readout."""
from itertools import product
import numpy as np
import torch
from torch import nn
GRID = 64
WIDTH = 32
MODES = (24, 24, 24)
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')
CHUNK = 8192
def stencil(points, raw_ids, size=GRID):
"""An isotropic part cube with one lattice cell of margin on each face."""
xyz = np.asarray(points, dtype=np.float64)
ids = np.asarray(raw_ids)
if (size < 5 or xyz.ndim != 2 or xyz.shape[1] != 3 or len(xyz) < 2
or not np.isfinite(xyz).all() or ids.shape != (len(xyz),)
or ids.dtype.kind not in 'iu' or not np.all(ids[1:] > ids[:-1])):
raise ValueError('Original coordinates and strictly ordered raw node IDs required')
low, high = xyz.min(axis=0), xyz.max(axis=0)
side = (high - low).max()
if not np.isfinite(side) or side <= 0:
raise ValueError('Invalid bounding cube')
lattice = (xyz - (low + high) / 2) / side * (size - 3) + (size - 1) / 2
if not np.isfinite(lattice).all() or lattice.min() < .999999 or lattice.max() > size - 1.999999:
raise ValueError('Node outside fixed interpolation cube')
base = np.floor(lattice).astype(np.int64)
frac = lattice - base
vertices, weights = [], []
for bits in product((0, 1), repeat=3):
corners = base + np.asarray(bits)
vertices.append(np.ravel_multi_index(corners.T, (size, size, size)))
weights.append(np.prod(np.where(bits, frac, 1 - frac), axis=1))
return (torch.from_numpy(np.stack(vertices, axis=1)),
torch.from_numpy(np.stack(weights, axis=1).astype(np.float32)))
def deposit(features, mass, vertices, weights, size=GRID):
if (features.ndim != 2 or features.shape[1] != len(COLUMNS) or mass.shape != features.shape[:1]
or vertices.shape != (len(mass), 8) or weights.shape != vertices.shape
or mass.dtype != torch.float32 or features.dtype != torch.float32 or weights.dtype != torch.float32
or vertices.dtype != torch.int64 or not torch.isfinite(features).all()
or not torch.isfinite(mass).all() or torch.any(mass <= 0)):
raise ValueError('Expected full original FP32 features, positive mass and reviewed stencil')
total = mass.sum()
if not torch.isfinite(total) or total <= 0:
raise ValueError('Invalid total nodal mass')
volume = mass / total
cells = size**3
numerator = features.new_zeros((cells, len(COLUMNS)))
denominator = features.new_zeros(cells)
# Keep the (nodes × 8 × channels) product out of memory.
for corner in range(8):
ids = vertices[:, corner]
weighted_mass = volume * weights[:, corner]
denominator.index_add_(0, ids, weighted_mass)
numerator.index_add_(0, ids, weighted_mass[:, None] * features)
occupied = denominator > 0
field = numerator / torch.where(occupied, denominator, 1.)[:, None]
grid = torch.cat((field, occupied[:, None].to(field.dtype)), dim=1)
return grid.T.reshape(len(COLUMNS) + 1, size, size, size), denominator
def gather(grid, vertices, weights):
channels = grid.shape[0]
values = grid.reshape(channels, -1).T
return torch.cat([
(values[vertices[lo:lo + CHUNK]] * weights[lo:lo + CHUNK, :, None]).sum(1)
for lo in range(0, len(vertices), CHUNK)
])
class GreifGINO(nn.Module):
"""Fixed trilinear integral layers around the pinned GINO-family spectral core."""
def __init__(self, size=GRID, modes=MODES):
super().__init__()
from neuralop.models import FNO
self.size = size
self.fno = FNO(list(modes), hidden_channels=WIDTH, in_channels=len(COLUMNS) + 1,
out_channels=WIDTH, norm='group_norm', use_mlp=True,
mlp={'expansion': 1., 'dropout': 0.}, domain_padding=.125,
factorization='tucker', rank=.4)
self.readout = nn.Sequential(nn.Linear(WIDTH + len(COLUMNS), 64), nn.GELU(), nn.Linear(64, 1))
nn.init.zeros_(self.readout[-1].weight)
nn.init.zeros_(self.readout[-1].bias)
def forward(self, features, mass, vertices, weights):
grid, _ = deposit(features, mass, vertices, weights, self.size)
latent = self.fno(grid[None])[0]
at_nodes = gather(latent, vertices, weights)
return self.readout(torch.cat((at_nodes, features), dim=1))[:, 0]