Replace the model with 110 optimizer steps in a loop of single-threaded operations
Browse files- README.md +6 -4
- lm.py +675 -584
- model.onnx +2 -2
- sym.py +389 -0
- wrap.py +191 -140
README.md
CHANGED
|
@@ -14,11 +14,13 @@ datasets:
|
|
| 14 |
|
| 15 |
`model.onnx` is an entry for the `fixed_shape` track of the [Coilstellaration benchmark](https://huggingface.co/spaces/proxima-fusion/coilstellaration-bench) (three field periods, five coils per half period). The benchmark asks for a stellarator coilset given a plasma boundary and four engineering targets: the smallest coil-coil distance, the smallest coil-plasma distance, the largest coil curvature and the largest normalized field error on the boundary.
|
| 16 |
|
| 17 |
-
The graph runs in three stages. The first is the per-coil ensemble `per_coil_ensemble_DAr7gipsQu9Mupbnsm2rAaK.onnx` of [proxima-fusion/coilstellaration-models](https://huggingface.co/proxima-fusion/coilstellaration-models) (MIT licence), embedded unchanged, which returns a first coilset. It is asked for the instance's own targets, or, where the field-error target is above 0.1, for 1.2 times the two distance targets (at least 0.40 and 0.60 minor radii), 0.85 times the curvature target (at most 3.5) and a field error of at most 0.01.
|
| 18 |
|
| 19 |
-
The second stage is
|
| 20 |
|
| 21 |
-
The third stage
|
|
|
|
|
|
|
| 22 |
|
| 23 |
## Interface
|
| 24 |
|
|
@@ -47,4 +49,4 @@ coil_x_n, coil_y_n, coil_z_n, currents = session.run(
|
|
| 47 |
|
| 48 |
## Files
|
| 49 |
|
| 50 |
-
`lm.py` is the second and third stages
|
|
|
|
| 14 |
|
| 15 |
`model.onnx` is an entry for the `fixed_shape` track of the [Coilstellaration benchmark](https://huggingface.co/spaces/proxima-fusion/coilstellaration-bench) (three field periods, five coils per half period). The benchmark asks for a stellarator coilset given a plasma boundary and four engineering targets: the smallest coil-coil distance, the smallest coil-plasma distance, the largest coil curvature and the largest normalized field error on the boundary.
|
| 16 |
|
| 17 |
+
The graph runs in three stages. The first is the per-coil ensemble `per_coil_ensemble_DAr7gipsQu9Mupbnsm2rAaK.onnx` of [proxima-fusion/coilstellaration-models](https://huggingface.co/proxima-fusion/coilstellaration-models) (MIT licence), embedded with its weights unchanged, which returns a first coilset. It is asked for the instance's own targets, or, where the field-error target is above 0.1, for 1.2 times the two distance targets (at least 0.40 and 0.60 minor radii), 0.85 times the curvature target (at most 3.5) and a field error of at most 0.01.
|
| 18 |
|
| 19 |
+
The second stage is 110 Levenberg-Marquardt steps on the Fourier coefficients and currents of the five coils, written as an ONNX `Loop`. Its residuals are the part of the normal field over the field strength above nine tenths of the target, at 40 by 21 points of the boundary's half period, and penalties on every coil point that is closer to another coil or to the boundary than the distance targets allow, or more curved than the curvature target allows. The Jacobians are analytic, and each step solves its linear system by twelve conjugate-gradient iterations.
|
| 20 |
|
| 21 |
+
The third stage returns planar circles sized to the two distance targets when they meet all four targets on the optimizer's grids, and the optimized coilset otherwise; the loop is skipped when the circles are returned.
|
| 22 |
+
|
| 23 |
+
Every operation of the graph is one that onnxruntime 1.31 runs in the calling thread: each matrix product is two-dimensional and below 65,536 in rows times columns times inner size, and the graph holds no `Transpose` and no `Clip`. A run therefore uses one processor whatever the size of the session's thread pool.
|
| 24 |
|
| 25 |
## Interface
|
| 26 |
|
|
|
|
| 49 |
|
| 50 |
## Files
|
| 51 |
|
| 52 |
+
`lm.py` is the second and third stages with the settings the file was written with: its functions run on PyTorch tensors and, unchanged, on the tensors of `sym.py`, which write the ONNX nodes. `wrap.py` writes the graph and joins it to the first-guess network, whose matrix products it cuts into blocks of columns. Both read example instances from a local table of the dataset's training boundaries; every setting was chosen on a twentieth of those boundaries.
|
lm.py
CHANGED
|
@@ -1,19 +1,27 @@
|
|
| 1 |
-
"""A coil optimizer for the
|
|
|
|
| 2 |
|
| 3 |
A first guess is improved by ITERS Levenberg-Marquardt steps on least-squares residuals of the instance's four
|
| 4 |
targets: the field error at every point of a surface grid above its target, and penalties for each coil-coil and
|
| 5 |
coil-plasma point pair closer than its target and each coil point more curved than its target. The hinges of those
|
| 6 |
-
residuals are rounded over a width that shrinks from step to step. Jacobians are analytic
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
from __future__ import annotations
|
| 19 |
|
|
@@ -27,52 +35,49 @@ import torch
|
|
| 27 |
HERE = Path(__file__).resolve().parent
|
| 28 |
sys.path[:0] = [str(HERE), str(HERE.parent), str(HERE.parent / "scorer")]
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
DEG = np.pi / 180
|
| 34 |
BASE = HERE.parent / "data" / "models" / "baselines" / "per_coil_ensemble_DAr7gipsQu9Mupbnsm2rAaK.onnx"
|
| 35 |
ASKS = { # what the first-guess network is asked for: the targets times a scale, then held between two bounds
|
| 36 |
"floors": ((1.2, 1.2, 0.85, 1.0), (0.40, 0.60, -1e30, -1e30), (1e30, 1e30, 3.5, 0.01)),
|
| 37 |
"asked": ((1.0, 1.0, 1.0, 1.0), (-1e30, -1e30, -1e30, -1e30), (1e30, 1e30, 1e30, 1e30)),
|
| 38 |
-
"field01": ((1.0, 1.0, 1.0, 1.0), (-1e30, -1e30, -1e30, -1e30), (1e30, 1e30, 1e30, 0.01)),
|
| 39 |
-
"margin10": ((1.1, 1.1, 0.9, 1.0), (-1e30, -1e30, -1e30, -1e30), (1e30, 1e30, 1e30, 0.02)),
|
| 40 |
-
"margin20": ((1.2, 1.2, 0.85, 1.0), (-1e30, -1e30, -1e30, -1e30), (1e30, 1e30, 1e30, 0.01)),
|
| 41 |
}
|
| 42 |
ASK = "switch" # a key of ASKS, or "switch": "floors" where the field-error target is above ASK_SWITCH, else "asked"
|
| 43 |
ASK_SWITCH = 0.1
|
| 44 |
|
| 45 |
-
ITERS =
|
| 46 |
-
P_F, P_G,
|
| 47 |
-
|
| 48 |
NJ = 3 # images of the unique coils kept in the field's Jacobian (the nearby ones)
|
| 49 |
NEAR = 2 # neighbouring coils in the fine coil-coil term
|
| 50 |
-
|
| 51 |
STEP_MAX = 0.10 # largest displacement of a coil point in one step, in metres
|
| 52 |
-
GRID_T,
|
| 53 |
-
|
| 54 |
-
PATCH_W, PATCH_DP, PATCH_DT = 16, 2, 2 # optimizer's plasma patch: half-width, phi and theta strides
|
| 55 |
W_CHECK = 24 # half-width in degrees of the circles' plasma patch
|
| 56 |
-
W_PASS = 16 # half-width in degrees of the check's plasma patch
|
| 57 |
MARGIN_CC, MARGIN_CP, ABS_GAP, MARGIN_K, MARGIN_F = 0.01, 0.02, 0.01, 0.01, 0.10 # what the optimizer asks beyond each target
|
| 58 |
MU_CC, MU_CP, MU_K = 1e3, 1e3, 1e3 # penalty weights of the geometric residuals
|
| 59 |
-
MU_RAMP = 1.0 # the factor those weights grow by from the first step to the last
|
| 60 |
-
CC_EXACT = 0 # 1: the coil-coil gradient by automatic differentiation (not exported)
|
| 61 |
ETA = 0.05 # weight of the plain field residual beside the hinged one
|
| 62 |
LAMBDA0, LAMBDA_DOWN, LAMBDA_UP, LAMBDA_MIN, LAMBDA_MAX = 3.0, 1 / 3, 4.0, 0.1, 1e6
|
| 63 |
RATIO_LO, RATIO_HI = 0.25, 0.75 # actual over predicted drop: below, lambda up; above, lambda down
|
| 64 |
EPS0, EPS1, EPS_F = 0.2, 0.03, 0.1 # width of the smoothed hinges: geometric, first to last step, and field
|
| 65 |
BETA = 0.01 # extra damping of harmonic n, as BETA n^4
|
| 66 |
-
EPS_W = 0.0 # if larger than the hinge's width: the width used for the Gauss-Newton matrix
|
| 67 |
CG_ITERS = 12
|
| 68 |
-
OPT_CURRENT = 1 # 1: the
|
| 69 |
-
PASS_CC, PASS_CP, PASS_GAP, PASS_K,
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
| 73 |
F = torch.float32
|
| 74 |
DEVICE = "cpu"
|
| 75 |
TAB = None
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
def _t(a):
|
|
@@ -87,456 +92,650 @@ def _basis(points):
|
|
| 87 |
np.concatenate([-(n * n * s)[::-1], z, -n * n * c]))
|
| 88 |
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
class Grid:
|
| 91 |
-
"""The boundary on a grid of
|
|
|
|
|
|
|
| 92 |
|
| 93 |
def __init__(self, theta, phi, normals=False):
|
| 94 |
-
m = np.arange(5)[:, None
|
| 95 |
-
n = (np.arange(-4, 5) * NFP)[
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
self.
|
| 100 |
-
self.C, self.S = flat(c), flat(s)
|
| 101 |
if normals:
|
| 102 |
-
self.
|
|
|
|
|
|
|
| 103 |
self.cos, self.sin = _t(np.cos(phi))[:, None], _t(np.sin(phi))[:, None]
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
nrm = cross(et, ep)
|
| 120 |
-
return x,
|
| 121 |
|
| 122 |
|
| 123 |
class Tables:
|
| 124 |
-
"""Constants of the graph."""
|
| 125 |
|
| 126 |
def __init__(self):
|
|
|
|
|
|
|
| 127 |
th64 = 2 * np.pi * np.arange(64) / 64
|
|
|
|
| 128 |
self.area = Grid(th64, 2 * np.pi / NFP * np.arange(48) / 48)
|
| 129 |
self.phi_k = (np.arange(K) + 0.5) * np.pi / (NFP * K)
|
| 130 |
self.cen = Grid(th64, self.phi_k)
|
| 131 |
-
|
| 132 |
-
self.
|
| 133 |
-
self.
|
| 134 |
d = np.arange(-W_CHECK, W_CHECK + 1) * DEG
|
| 135 |
self.dphi_cos, self.dphi_sin = _t(np.cos(d))[:, None], _t(np.sin(d))[:, None]
|
| 136 |
-
self.
|
| 137 |
-
self.
|
| 138 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
# the 2 NFP maps of a unique coil: partner (x, -y, -z) or not, then a rotation
|
| 140 |
ang = 2 * np.pi * np.arange(NFP) / NFP
|
| 141 |
maps = np.stack([np.array([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]]) @ np.diag(f)
|
| 142 |
for a in ang for f in ([1.0, 1.0, 1.0], [1.0, -1.0, -1.0])])
|
| 143 |
sign = np.tile([1.0, -1.0], NFP)
|
| 144 |
-
self.maps = _t(
|
| 145 |
-
self.maps_t = _t(
|
| 146 |
-
self.back = _t(maps.transpose(0, 2, 1) * sign[:, None, None]) # the same with the current's sign
|
| 147 |
-
self.sign = _t(sign)
|
| 148 |
# the same maps for the field, the images near the half period first: the coils, their partners, and the
|
| 149 |
-
# partners turned by one period
|
| 150 |
-
near_first = [0, 1, 3
|
| 151 |
-
self.fmaps = _t(maps[
|
| 152 |
-
self.
|
| 153 |
-
self.
|
| 154 |
-
|
| 155 |
-
self.
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
nominal = np.concatenate([np.concatenate([self.phi_k, -self.phi_k]) + a for a in ang])
|
| 158 |
gap = np.abs((nominal[None, :] - self.phi_k[:, None] + np.pi) % (2 * np.pi) - np.pi)
|
| 159 |
gap[np.arange(K), np.arange(K)] = np.inf
|
| 160 |
-
# "near": the NEAR nearest; "far": the other coils of the half period, its partners' and the next one's partners
|
| 161 |
order = np.argsort(gap, axis=1, kind="stable")
|
| 162 |
-
nearby =
|
| 163 |
-
|
| 164 |
-
self.
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
self.cos_k, self.sin_k = _t(np.cos(self.phi_k)), _t(np.sin(self.phi_k))
|
| 170 |
-
self.alpha = _t(ALPHA)
|
| 171 |
-
self.order = _t([1.9, 2.0]) # both passing: the circles, whose check is the surer
|
| 172 |
-
eps = np.zeros((3, 3, 3))
|
| 173 |
-
for a, b, c in ((0, 1, 2), (1, 2, 0), (2, 0, 1)):
|
| 174 |
-
eps[a, b, c], eps[a, c, b] = 1.0, -1.0
|
| 175 |
-
self.skew = _t(eps.transpose(1, 2, 0).reshape(3, 9)) # m @ skew, as (3, 3): the matrix X with v @ X = m x v
|
| 176 |
self.half = _t([np.cos(np.pi / (2 * NFP)), np.sin(np.pi / (2 * NFP)), 0.0])
|
| 177 |
-
self.eye = _t(np.eye(NPAR + K))
|
| 178 |
harmonic = np.abs(np.arange(NM) - ORDER)
|
| 179 |
-
self.stiff = _t(np.concatenate([np.tile(1.0 + BETA * harmonic ** 4, K * 3), np.ones(K)]))
|
| 180 |
-
self.cur_mask = _t(np.concatenate([np.ones(NPAR), np.full(K, float(OPT_CURRENT))]))
|
|
|
|
| 181 |
|
| 182 |
|
| 183 |
-
def
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
|
| 189 |
-
def
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
|
| 193 |
-
def
|
| 194 |
-
"""
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
|
| 198 |
-
def
|
| 199 |
-
"""
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
# per nearby point, the (8, 3) matrix taking [V12 (3), U1, V3 (3), U0] to m x V12 + U1 (y x m) - V3 + U0 y
|
| 205 |
-
MX = torch.cat([torch.matmul(m[:yj], TAB.skew).reshape(yj, 3, 3), cy[:yj, None, :],
|
| 206 |
-
TAB.minus_eye[None].expand(yj, 3, 3), y[:yj, None, :]], 1)
|
| 207 |
-
return dict(y=y, m=m, cy=cy, ysq=(y * y).sum(-1), ym2=-2.0 * y, o=o, X=x.shape[0], MX=MX)
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
def field(coef, amp, fg, P, jac=False):
|
| 211 |
-
"""Normal field over field strength at the X grid points: f (X,), and with jac its Jacobian (X, NPAR + K) in the
|
| 212 |
-
coefficients and the logarithms of the currents. The coefficient part leaves out the dependence of |B| and the
|
| 213 |
-
images of the coils beyond the NJ nearby ones."""
|
| 214 |
-
B0, B1, _ = TAB.basis[P]
|
| 215 |
-
X, Y, dlt = fg["X"], fg["X"] * NIMG, 2 * np.pi / P
|
| 216 |
-
r, r1 = torch.matmul(coef, B0), torch.matmul(coef, B1) # (K, 3, P)
|
| 217 |
-
rs, r1t = r.transpose(1, 2) - fg["o"], r1.transpose(1, 2) # (K, P, 3), centred
|
| 218 |
-
es = r1t * dlt
|
| 219 |
-
rT, eT = rs.reshape(K * P, 3), es.reshape(K * P, 3)
|
| 220 |
-
exr = cross(eT, rT)
|
| 221 |
-
d2 = fg["ysq"][:, None] + (rT * rT).sum(-1)[None, :] + torch.matmul(fg["ym2"], rT.transpose(0, 1)) # (Y, K P)
|
| 222 |
-
inv = 1.0 / d2
|
| 223 |
-
w3 = inv * inv.sqrt() * amp[:, None].expand(K, P).reshape(1, K * P) # I / |d|^3
|
| 224 |
-
s = torch.matmul(fg["cy"], eT.transpose(0, 1)) - torch.matmul(fg["m"], exr.transpose(0, 1)) # e . (d x m)
|
| 225 |
-
sw = s * w3
|
| 226 |
-
W = w3.reshape(Y, K, P).permute(1, 0, 2) # (K, Y, P)
|
| 227 |
-
gK = sw.reshape(Y, K, P).sum(-1) # (Y, K): each coil family's share of m . B
|
| 228 |
-
ByK = cross(torch.matmul(W, es), fg["y"][None]) - torch.matmul(W, exr.reshape(K, P, 3)) # (K, Y, 3)
|
| 229 |
-
BK = torch.matmul(ByK.reshape(K, NIMG, X, 3), TAB.fback).sum(1) # (K, X, 3): rotated back, images summed
|
| 230 |
-
B = BK.sum(0)
|
| 231 |
-
Bn = (B * B).sum(-1).sqrt()
|
| 232 |
-
gKx = torch.matmul(TAB.fsign_row, gK.reshape(NIMG, X * K)).reshape(X, K)
|
| 233 |
-
f = gKx.sum(-1) / Bn
|
| 234 |
-
if not jac:
|
| 235 |
-
return f
|
| 236 |
-
YJ = NJ * X
|
| 237 |
-
Wn = w3[:YJ].reshape(YJ, K, P).permute(1, 0, 2) # (K, YJ, P): I / |d|^3 at the nearby images
|
| 238 |
-
S5 = (3.0 * sw[:YJ] * inv[:YJ]).reshape(YJ, K, P).permute(1, 0, 2) # 3 I s / |d|^5
|
| 239 |
-
B0t, B1t = B0.transpose(0, 1), B1.transpose(0, 1) # (P, NM)
|
| 240 |
-
M12 = dlt * (B1t[None, :, :, None] * rs[:, :, None, :] - B0t[None, :, :, None] * r1t[:, :, None, :])
|
| 241 |
-
MW = torch.cat([M12, (dlt * B1t)[None, :, :, None].expand(K, P, NM, 1)], 3).reshape(K, P, 4 * NM)
|
| 242 |
-
MS = torch.cat([B0t[None, :, :, None] * rs[:, :, None, :], B0t[None, :, :, None].expand(K, P, NM, 1)], 3).reshape(K, P, 4 * NM)
|
| 243 |
-
R = torch.matmul(torch.cat([Wn, S5]), torch.cat([MW, MS])) # (2 K, YJ, 4 NM)
|
| 244 |
-
R8 = R.reshape(2, K, YJ, NM, 4).permute(1, 2, 3, 0, 4).permute(1, 0, 2, 3, 4).reshape(YJ, K * NM, 8)
|
| 245 |
-
Jy = torch.matmul(R8, fg["MX"]) # (YJ, K NM, 3)
|
| 246 |
-
Jg = torch.matmul(TAB.fsign_near, Jy.reshape(NJ, X * K * NM * 3)).reshape(X, K, NM, 3).permute(0, 1, 3, 2).reshape(X, NPAR)
|
| 247 |
-
Jc = gKx / Bn[:, None] - f[:, None] * (BK.permute(1, 0, 2) * B[:, None, :]).sum(-1) / (Bn * Bn)[:, None]
|
| 248 |
-
return f, torch.cat([Jg / Bn[:, None], Jc], 1)
|
| 249 |
|
| 250 |
|
| 251 |
def smooth(x, eps):
|
| 252 |
"""A hinge max(0, x) rounded over |x| < eps, with its derivative: 0 below -eps, (x + eps)^2 / (4 eps) between."""
|
| 253 |
-
s =
|
| 254 |
-
return eps * s * s +
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
def
|
| 258 |
-
"""The
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
root = inv.sqrt()
|
| 310 |
-
|
| 311 |
-
v, s = smooth(x, eps)
|
| 312 |
c = v * s * root
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
qt = (qc[:, :, :, None] * tc[:, :, None, :] + tc[:, :, :, None] * qc[:, :, None, :]).reshape(n, m, 9)
|
| 321 |
-
tt = (tc[:, :, :, None] * tc[:, :, None, :]).reshape(n, m, 9)
|
| 322 |
-
aqq = (torch.matmul(act, qq) + torch.matmul(au, qt) + torch.matmul(au * u, tt)).reshape(rc.shape[0], rc.shape[1], 3, 3)
|
| 323 |
-
hess = (act.sum(-1)[:, :, None, None] * rc[:, :, :, None] * rc[:, :, None, :] - rc[:, :, :, None] * aq[:, :, None, :]
|
| 324 |
-
- aq[:, :, :, None] * rc[:, :, None, :] + aqq) / (need * need)
|
| 325 |
return (v * v).sum(), grad, hess
|
| 326 |
|
| 327 |
|
| 328 |
-
def
|
| 329 |
-
"""
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
_, B1, B2 = TAB.basis[P_K]
|
| 346 |
-
|
| 347 |
-
aa, bb, ab = (r1 * r1
|
| 348 |
-
n2 =
|
| 349 |
-
kappa = n2.sqrt() / (aa * aa.sqrt())
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
g1 =
|
| 353 |
-
g2 =
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
|
| 358 |
|
| 359 |
def geometry(r_cos, z_sin, target):
|
| 360 |
-
"""Everything the optimizer and the
|
| 361 |
-
|
| 362 |
-
R, Z = TAB.area.rz(
|
| 363 |
-
area = 0.5 * (R *
|
| 364 |
a = (area.mean() / np.pi).sqrt()
|
| 365 |
-
R, Z = TAB.cen.rz(
|
| 366 |
centre_r, centre_z = R.mean(1), Z.mean(1)
|
| 367 |
-
centre =
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
|
|
|
|
|
|
| 373 |
r0 = r_cos[0, 4]
|
| 374 |
o = r0 * TAB.half
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
J = J * TAB.cur_mask
|
| 399 |
-
grad = torch.matmul((hp * sp - hm * sm + plain * ETA) / tau, J)
|
| 400 |
-
A = torch.matmul((J * ((sp * sp + sm * sm + ETA * ETA) / (tau * tau))[:, None]).transpose(0, 1), J)
|
| 401 |
-
# geometry
|
| 402 |
-
B0 = TAB.basis[P_G][0]
|
| 403 |
-
r = torch.matmul(coef, B0).transpose(1, 2) # (K, P, 3)
|
| 404 |
-
near_q, near_t = segments(coef, P_S, "near")
|
| 405 |
-
rc = r - g["centre"][:, None, :]
|
| 406 |
-
l_cc, g_cc, h_cc = segment_terms(rc, near_q - g["centre"][:, None, :], near_t, g["need_cc"], eps, np.pi / P_S)
|
| 407 |
-
l_cp, g_cp, h_cp = distance_terms(rc, g["patch"], g["need_cp"], eps)
|
| 408 |
-
gg, hh = to_coefficients(2.0 * MU_CC * g_cc + MU_CP * g_cp, 2.0 * MU_CC * h_cc + MU_CP * h_cp, B0)
|
| 409 |
-
B0c = TAB.basis[P_GC][0]
|
| 410 |
-
far_q, far_t = segments(coef, P_SC, "far")
|
| 411 |
-
l_far, g_far, h_far = segment_terms(torch.matmul(coef, B0c).transpose(1, 2) - g["centre"][:, None, :], far_q - g["centre"][:, None, :], far_t,
|
| 412 |
-
g["need_cc"], eps, np.pi / P_SC)
|
| 413 |
-
g_far, h_far = to_coefficients(2.0 * MU_CC * g_far, 2.0 * MU_CC * h_far, B0c)
|
| 414 |
-
l_k, g_k, h_k = curvature_terms(coef, g["k_scale"], eps)
|
| 415 |
-
gg, hh = gg + g_far + MU_K * g_k, hh + h_far + MU_K * h_k
|
| 416 |
-
if CC_EXACT:
|
| 417 |
-
def cc_loss(c):
|
| 418 |
-
q1, t1 = segments(c, P_S, "near")
|
| 419 |
-
q2, t2 = segments(c, P_SC, "far")
|
| 420 |
-
return (segment_terms(torch.matmul(c, B0).transpose(1, 2) - g["centre"][:, None, :], q1 - g["centre"][:, None, :], t1,
|
| 421 |
-
g["need_cc"], eps, np.pi / P_S)[0]
|
| 422 |
-
+ segment_terms(torch.matmul(c, B0c).transpose(1, 2) - g["centre"][:, None, :], q2 - g["centre"][:, None, :], t2,
|
| 423 |
-
g["need_cc"], eps, np.pi / P_SC)[0])
|
| 424 |
-
own = to_coefficients(2.0 * MU_CC * g_cc, 0.0 * h_cc, B0)[0] + g_far
|
| 425 |
-
gg = gg - own + 0.5 * MU_CC * torch.func.grad(cc_loss)(coef)
|
| 426 |
-
phi_g = MU_CC * (l_cc + l_far) + MU_CP * l_cp + MU_K * l_k
|
| 427 |
-
n = NPAR + K
|
| 428 |
-
blocks = torch.cat([torch.cat([torch.zeros(3 * NM, 3 * NM * k, dtype=F, device=hh.device), hh[k],
|
| 429 |
-
torch.zeros(3 * NM, n - 3 * NM * (k + 1), dtype=F, device=hh.device)], 1) for k in range(K)])
|
| 430 |
-
A_g = torch.cat([blocks, torch.zeros(K, n, dtype=F, device=hh.device)])
|
| 431 |
-
grad_g = torch.cat([gg.reshape(NPAR), torch.zeros(K, dtype=F, device=hh.device)])
|
| 432 |
-
return phi, A, grad, phi_g, A_g, grad_g, torch.maximum(f.max(), -f.min()) / tau
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
def solve(A, grad, lam):
|
| 436 |
-
"""The Levenberg-Marquardt step: (A + lam D) delta = -grad by preconditioned conjugate gradients, D the diagonal
|
| 437 |
-
of A weighted up for the higher harmonics."""
|
| 438 |
-
diag = (A * TAB.eye).sum(-1)
|
| 439 |
-
diag = (torch.clamp(diag, min=1e-12) + 1e-9 * diag.max()) * TAB.stiff
|
| 440 |
-
M = A + (lam * diag)[:, None] * TAB.eye
|
| 441 |
-
pre = 1.0 / ((A * TAB.eye).sum(-1) + lam * diag)
|
| 442 |
-
pre = pre[:, None]
|
| 443 |
-
r = -grad[:, None]
|
| 444 |
-
x = torch.zeros_like(r)
|
| 445 |
-
z = pre * r
|
| 446 |
-
p, rz = z, (r * z).sum()
|
| 447 |
-
for _ in range(CG_ITERS):
|
| 448 |
-
Mp = torch.matmul(M, p)
|
| 449 |
-
step = rz / torch.clamp((p * Mp).sum(), min=1e-30)
|
| 450 |
-
x, r = x + step * p, r - step * Mp
|
| 451 |
-
z = pre * r
|
| 452 |
-
rz_new = (r * z).sum()
|
| 453 |
-
p, rz = z + (rz_new / torch.clamp(rz, min=1e-30)) * p, rz_new
|
| 454 |
-
return x[:, 0] * TAB.cur_mask
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
def optimize(coef, cur0, g, trace=None):
|
| 458 |
-
logi = torch.zeros(K, dtype=F, device=coef.device)
|
| 459 |
-
state = evaluate(coef, logi, cur0, g, EPS0)
|
| 460 |
-
lam = torch.as_tensor(LAMBDA0, dtype=F, device=coef.device)
|
| 461 |
-
for it in range(ITERS):
|
| 462 |
-
eps = float(EPS0 * (EPS1 / EPS0) ** (it / max(ITERS - 1, 1)))
|
| 463 |
-
rho = float(MU_RAMP ** (it / max(ITERS - 1, 1)))
|
| 464 |
-
phi, A, grad = combined(state, rho)
|
| 465 |
-
delta = solve(A, grad, lam)
|
| 466 |
-
moved = torch.matmul(delta[:NPAR].reshape(K, 3, NM), TAB.basis[P_GC][0]) # (K, 3, P): the points' displacements
|
| 467 |
-
delta = delta * torch.clamp(STEP_MAX / torch.clamp((moved * moved).sum(1).max().sqrt(), min=1e-9), max=1.0)
|
| 468 |
-
predicted = -(2.0 * (grad * delta).sum() + (delta * torch.matmul(A, delta)).sum())
|
| 469 |
-
coef_t, logi_t = coef + delta[:NPAR].reshape(K, 3, NM), logi + delta[NPAR:]
|
| 470 |
-
trial = evaluate(coef_t, logi_t, cur0, g, eps)
|
| 471 |
-
phi_t = trial[0] + rho * trial[3]
|
| 472 |
-
take = phi_t < phi
|
| 473 |
-
ratio = (phi - phi_t) / torch.clamp(predicted, min=1e-30)
|
| 474 |
-
coef, logi = torch.where(take, coef_t, coef), torch.where(take, logi_t, logi)
|
| 475 |
-
state = tuple(torch.where(take, new, old) for new, old in zip(trial, state))
|
| 476 |
-
lam = torch.clamp(torch.where(ratio > RATIO_HI, lam * LAMBDA_DOWN, torch.where(ratio > RATIO_LO, lam, lam * LAMBDA_UP)),
|
| 477 |
-
min=LAMBDA_MIN, max=LAMBDA_MAX)
|
| 478 |
-
if trace is not None:
|
| 479 |
-
trace.append((float(state[0] + rho * state[3]), float(state[6]), bool(take), float(lam)))
|
| 480 |
-
return coef, cur0 * torch.exp(logi)
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
def measure(coef, current, g, fine=True):
|
| 484 |
-
"""The four benchmark metrics of a coilset on the check's grids, in TARGETS order; without fine, the field error
|
| 485 |
-
on the optimizer's grid."""
|
| 486 |
-
rc = torch.matmul(coef, TAB.basis[P_D][0]).transpose(1, 2) - g["centre"][:, None, :] # (K, P, 3)
|
| 487 |
-
near_q, near_t = segments(coef, P_T, "near")
|
| 488 |
-
far_q, far_t = segments(coef, P_TC, "far")
|
| 489 |
-
d_cc = torch.minimum(segment_d2(rc, near_q - g["centre"][:, None, :], near_t, np.pi / P_T)[0].min(),
|
| 490 |
-
segment_d2(torch.matmul(coef, TAB.basis[P_DC][0]).transpose(1, 2) - g["centre"][:, None, :],
|
| 491 |
-
far_q - g["centre"][:, None, :], far_t, np.pi / P_TC)[0].min())
|
| 492 |
-
d_cp = (rc * rc).sum(-1)[:, :, None] + (g["check"] * g["check"]).sum(-1)[:, None, :] - 2.0 * torch.matmul(rc, g["check"].transpose(1, 2))
|
| 493 |
-
f = field(coef, current, g["fc"], P_C) if fine else field(coef, current, g["fg"], P_F)
|
| 494 |
-
return torch.stack([torch.clamp(d_cc, min=0.0).sqrt() / g["a"], torch.clamp(d_cp.min(), min=0.0).sqrt() / g["a"],
|
| 495 |
-
curvature(coef).max() * g["a"], torch.maximum(f.max(), -f.min())])
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
def verdict(got, target, pass_f):
|
| 499 |
-
"""(passes on the check's grids, benchmark score) of measured metrics against the targets."""
|
| 500 |
-
ok = ((got[0] >= torch.maximum(target[0] * PASS_CC, target[0] + PASS_GAP)) & (got[1] >= torch.maximum(target[1] * PASS_CP, target[1] + PASS_GAP))
|
| 501 |
-
& (got[2] <= target[2] * PASS_K) & (got[3] <= target[3] * pass_f))
|
| 502 |
-
lower = torch.clamp((target[:2] - got[:2]) / target[:2], min=0.0)
|
| 503 |
-
upper = torch.clamp((got[2:] - target[2:]) / target[2:], min=0.0)
|
| 504 |
-
return ok, torch.exp(-(torch.cat([lower, upper]) / TAB.alpha).mean())
|
| 505 |
|
| 506 |
|
| 507 |
def circles(g, target):
|
| 508 |
-
"""The clearance circles
|
|
|
|
|
|
|
|
|
|
| 509 |
d = CLEAR * target[1] * g["a"]
|
| 510 |
-
R, Z = g["
|
| 511 |
h = R * TAB.dphi_sin
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
|
|
|
| 515 |
r_c2c = g["centre_r"] - C2C_MARGIN * target[0] * g["a"] / (2 * np.sin(np.pi / (2 * NFP * K)))
|
| 516 |
-
radius =
|
| 517 |
-
zero = torch.
|
| 518 |
-
mid =
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
pad = torch.zeros(K, 3, ORDER - 1, dtype=F, device=
|
| 522 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
|
| 524 |
|
| 525 |
def model(r_cos, z_sin, target, start_x, start_y, start_z, start_current, details=False, trace=None):
|
| 526 |
-
"""
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
if details:
|
| 538 |
-
return
|
| 539 |
-
return
|
| 540 |
|
| 541 |
|
| 542 |
def ask(target):
|
|
@@ -545,204 +744,96 @@ def ask(target):
|
|
| 545 |
return np.minimum(np.maximum(np.asarray(target, float) * scale, lo), hi)
|
| 546 |
|
| 547 |
|
| 548 |
-
def first_guess(sess, r_cos, z_sin, target):
|
| 549 |
return sess.run(["coil_x_n", "coil_y_n", "coil_z_n", "currents"], {
|
| 550 |
"boundary_r_cos": r_cos.astype(np.float32), "boundary_z_sin": z_sin.astype(np.float32),
|
| 551 |
"requirement_metrics": ask(target).astype(np.float32),
|
| 552 |
-
"n_field_periods": np.asarray(
|
| 553 |
|
| 554 |
|
| 555 |
-
def dev_rows(table, n, strata=("loose", "medium", "tight")):
|
| 556 |
import instances
|
| 557 |
rows, stratum = [], []
|
| 558 |
for s in strata:
|
| 559 |
-
order = instances.benchmark_order(table,
|
| 560 |
order = order[np.unique(np.linspace(0, len(order) - 1, n).astype(int))]
|
| 561 |
rows += order.tolist()
|
| 562 |
stratum += [s] * len(order)
|
| 563 |
return np.array(rows), np.array(stratum)
|
| 564 |
|
| 565 |
|
| 566 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
import onnxruntime as ort
|
| 568 |
import queue_io
|
| 569 |
sess = ort.InferenceSession(str(BASE), providers=["CPUExecutionProvider"])
|
| 570 |
table, bnd = queue_io.instances(), queue_io.boundaries()
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
sets["optimized"].append(unpack(coef, cur))
|
| 586 |
-
sets["circles"].append(unpack(ring, ring_cur))
|
| 587 |
-
sets["chosen"].append(sets["circles"][-1] if bool(use_ring) else sets["optimized"][-1])
|
| 588 |
-
flags.append((bool(ok[0]), bool(ok[1]), bool(use_ring)))
|
| 589 |
-
measured.append(got.double().cpu().numpy())
|
| 590 |
-
traces.append(trace)
|
| 591 |
-
if j < 3 or j % 32 == 0:
|
| 592 |
-
print(f"{j} {stratum[j]} target {np.round(tgt, 4)}: objective, worst field error / target, taken, lambda at steps 1, 2, 4, 8, 16, last:",
|
| 593 |
-
" ".join(f"[{trace[s][0]:.3g} {trace[s][1]:.2f} {int(trace[s][2])} {trace[s][3]:.0e}]" for s in sorted({0, 1, 3, 7, 15, len(trace) - 1}) if s < len(trace)),
|
| 594 |
-
f"taken {sum(t[2] for t in trace)}/{len(trace)}", flush=True)
|
| 595 |
-
print(f"{len(rows)} instances in {time.time() - t0:.0f}s ({(time.time() - t0) / len(rows):.2f}s each)", flush=True)
|
| 596 |
-
flags, measured = np.array(flags), np.array(measured)
|
| 597 |
-
names = {k: f"0b_lm_{k}_{tag}" for k in sets}
|
| 598 |
-
for k, name in names.items():
|
| 599 |
-
queue_io.submit(name, table["instance"][rows].tolist(), sets[k], {"kind": "lm", "set": k})
|
| 600 |
-
queue_io.wait(list(names.values()), poll=3)
|
| 601 |
-
res = {k: queue_io.load(name) for k, name in names.items()}
|
| 602 |
-
said = {"optimized": flags[:, 0], "circles": flags[:, 1], "chosen": flags[:, 0] | flags[:, 1]}
|
| 603 |
-
print(f"{'set':9s} {'stratum':7s} {'n':>4s} {'strict':>7s} {'mean':>7s} | misses: c2c c2p curv ferr | judged passing, of which strict")
|
| 604 |
-
for k in sets:
|
| 605 |
miss = res[k]["violation"] > 1e-3
|
| 606 |
for s in strata:
|
| 607 |
m = stratum == s
|
| 608 |
-
cal = f" | {int(said[k][m].sum()):4d} {int((said[k] & res[k]['strict'])[m].sum()):4d}" if k in said else ""
|
| 609 |
print(f"{k:9s} {s:7s} {int(m.sum()):4d} {res[k]['strict'][m].mean():7.4f} {np.nanmean(res[k]['score'][m]):7.4f} |"
|
| 610 |
-
f" " + " ".join(f"{miss[m][:, j].mean():6.3f}" for j in range(4))
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
print(f"{s}: optimized field error / target, 10th 25th 50th 75th 90th percentile:", np.round(np.percentile(ratio, [10, 25, 50, 75, 90]), 3))
|
| 617 |
-
for j, k in enumerate(("optimized", "circles")):
|
| 618 |
-
ratio = measured[:, j] / res[k]["metrics"][:, 1:5]
|
| 619 |
-
good = np.isfinite(ratio).all(1)
|
| 620 |
-
print(f"{k}: this model's metric / the scorer's, 1st, 50th and 99th percentile:",
|
| 621 |
-
" ".join(f"[{a:.4f} {b:.4f} {c:.4f}]" for a, b, c in zip(*np.percentile(ratio[good], [1, 50, 99], axis=0))))
|
| 622 |
-
np.savez(queue_io.DATA / "geo" / f"lm_{tag}.npz", rows=rows, stratum=stratum, flags=flags, measured=measured,
|
| 623 |
-
**{f"strict_{k}": res[k]["strict"] for k in sets}, **{f"score_{k}": res[k]["score"] for k in sets},
|
| 624 |
-
**{f"metrics_{k}": res[k]["metrics"] for k in sets}, target=table["target"][rows])
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
def selftest():
|
| 628 |
-
"""Analytic derivatives against autograd on one dev instance, in float64."""
|
| 629 |
-
import onnxruntime as ort
|
| 630 |
-
import queue_io
|
| 631 |
-
setup("cpu", torch.float64)
|
| 632 |
-
table, bnd = queue_io.instances(), queue_io.boundaries()
|
| 633 |
-
bindex = {b: i for i, b in enumerate(bnd["boundary_id"].tolist())}
|
| 634 |
-
rows, _ = dev_rows(table, 2)
|
| 635 |
-
i = rows[3]
|
| 636 |
-
b = bindex[str(table["boundary_id"][i])]
|
| 637 |
-
tgt = table["target"][i]
|
| 638 |
-
guess = first_guess(ort.InferenceSession(str(BASE), providers=["CPUExecutionProvider"]), bnd["r_cos"][b], bnd["z_sin"][b], tgt)
|
| 639 |
-
g = geometry(_t(bnd["r_cos"][b]), _t(bnd["z_sin"][b]), _t(tgt))
|
| 640 |
-
coef, cur = torch.stack([_t(o) for o in guess[:3]], 1), _t(guess[3])
|
| 641 |
-
logi = 0.1 * torch.randn(K, dtype=F)
|
| 642 |
-
rel = lambda a, b_: float((a - b_).abs().max() / b_.abs().max()) # noqa: E731
|
| 643 |
-
|
| 644 |
-
# the field against a direct Biot-Savart sum over all C coils
|
| 645 |
-
f, J = field(coef, cur * torch.exp(logi), g["fg"], P_F, True)
|
| 646 |
-
x, nrm = TAB.grid.points_normals(_t(bnd["r_cos"][b]).reshape(1, 45), _t(bnd["z_sin"][b]).reshape(1, 45))
|
| 647 |
-
|
| 648 |
-
def direct(coef_, logi_):
|
| 649 |
-
B0, B1, _ = TAB.basis[P_F]
|
| 650 |
-
r, r1 = torch.matmul(coef_, B0).transpose(1, 2), torch.matmul(coef_, B1).transpose(1, 2)
|
| 651 |
-
src, dl = images(r), images(r1) * (2 * np.pi / P_F)
|
| 652 |
-
amp = (TAB.sign[:, None] * (cur * torch.exp(logi_))[None, :]).reshape(-1)[:, None].expand(C, P_F)
|
| 653 |
-
d = x[:, None, None, :] - src[None]
|
| 654 |
-
B = (cross(dl[None].expand_as(d), d) * ((d * d).sum(-1).pow(-1.5) * amp)[..., None]).sum((1, 2))
|
| 655 |
-
return (B * nrm).sum(-1), (B * B).sum(-1).sqrt()
|
| 656 |
-
|
| 657 |
-
gd, bd = direct(coef, logi)
|
| 658 |
-
print("field error against a direct sum, relative:", rel(f, gd / bd))
|
| 659 |
-
Jg_auto = torch.func.jacrev(lambda c_: direct(c_, logi)[0])(coef).reshape(-1, NPAR)
|
| 660 |
-
print(f"Jacobian of the normal field in the coefficients ({NJ} of {NIMG} images kept), relative:", rel(J[:, :NPAR] * bd[:, None], Jg_auto))
|
| 661 |
-
Jc_auto = torch.func.jacrev(lambda l_: direct(coef, l_)[0] / direct(coef, l_)[1])(logi)
|
| 662 |
-
print("Jacobian of the field error in the log currents, relative:", rel(J[:, NPAR:], Jc_auto))
|
| 663 |
-
# distances and curvature
|
| 664 |
-
B0 = TAB.basis[P_G][0]
|
| 665 |
-
|
| 666 |
-
def pieces(coef_):
|
| 667 |
-
return torch.matmul(coef_, B0).transpose(1, 2) - g["centre"][:, None, :]
|
| 668 |
-
|
| 669 |
-
def cc(coef_, need, eps=0.1):
|
| 670 |
-
q, t = segments(coef_, P_S, "near")
|
| 671 |
-
return segment_terms(pieces(coef_), q - g["centre"][:, None, :], t, need, eps, np.pi / P_S)
|
| 672 |
-
|
| 673 |
-
for name, need, which in (("coil-coil", 1.6 * g["need_cc"], 0), ("coil-plasma", 1.6 * g["need_cp"], 1)):
|
| 674 |
-
def loss(coef_):
|
| 675 |
-
return cc(coef_, need)[0] if which == 0 else distance_terms(pieces(coef_), g["patch"], need, 0.1)[0]
|
| 676 |
-
rc = pieces(coef)
|
| 677 |
-
val, grad, hess = cc(coef, need) if which == 0 else distance_terms(rc, g["patch"], need, 0.1)
|
| 678 |
-
gc, hc = to_coefficients(grad, hess, B0)
|
| 679 |
-
auto = torch.func.grad(loss)(coef)
|
| 680 |
-
print(f"{name}: loss {float(val):.4g}, gradient relative difference (coil-coil: twice the own-role part against the whole):",
|
| 681 |
-
rel((2.0 if which == 0 else 1.0) * 2 * gc, auto))
|
| 682 |
-
if which == 1:
|
| 683 |
-
def resid(coef_):
|
| 684 |
-
rc_ = pieces(coef_)
|
| 685 |
-
d = (rc_[:, :, None, :] - g["patch"][:, None]).pow(2).sum(-1).sqrt()
|
| 686 |
-
return smooth(1 - d / need, 0.1)[0]
|
| 687 |
-
Jr = torch.func.jacfwd(resid)(coef).reshape(-1, K, 3 * NM)
|
| 688 |
-
gn = torch.einsum("rka,rkb->kab", Jr, Jr)
|
| 689 |
-
print("coil-plasma Gauss-Newton matrix, relative:", rel(hc, gn))
|
| 690 |
-
k_scale = 3.0 * g["k_scale"]
|
| 691 |
-
val, gk, hk = curvature_terms(coef, k_scale, 0.1)
|
| 692 |
-
auto = torch.func.grad(lambda c_: (smooth(curvature(c_) * k_scale - (1 - MARGIN_K), 0.1)[0] ** 2).sum())(coef)
|
| 693 |
-
print(f"curvature: loss {float(val):.4g}, gradient relative difference:", rel(2 * gk, auto))
|
| 694 |
-
Jr = torch.func.jacrev(lambda c_: smooth(curvature(c_) * k_scale - (1 - MARGIN_K), 0.1)[0])(coef).reshape(K, P_K, K, 3 * NM)
|
| 695 |
-
print("curvature Gauss-Newton matrix, relative:", rel(hk, torch.einsum("kpka,kpkb->kab", Jr, Jr)))
|
| 696 |
-
# the assembled half-gradient against autograd of the objective
|
| 697 |
-
state = evaluate(coef, logi, cur, g, 0.05)
|
| 698 |
-
(phi, A, grad), worst = combined(state), state[6]
|
| 699 |
-
|
| 700 |
-
def objective(coef_, logi_):
|
| 701 |
-
gd_, bd_ = direct(coef_, logi_)
|
| 702 |
-
f_ = gd_ / bd_
|
| 703 |
-
tau = g["tau"]
|
| 704 |
-
hp, hm = smooth(f_ / tau - (1 - MARGIN_F), EPS_F)[0], smooth(-f_ / tau - (1 - MARGIN_F), EPS_F)[0]
|
| 705 |
-
far_q, far_t = segments(coef_, P_SC, "far")
|
| 706 |
-
far = segment_terms(torch.matmul(coef_, TAB.basis[P_GC][0]).transpose(1, 2) - g["centre"][:, None, :], far_q - g["centre"][:, None, :], far_t,
|
| 707 |
-
g["need_cc"], 0.05, np.pi / P_SC)[0]
|
| 708 |
-
return ((hp * hp).sum() + (hm * hm).sum() + ((f_ * ETA / tau) ** 2).sum() + MU_CC * (cc(coef_, g["need_cc"], 0.05)[0] + far)
|
| 709 |
-
+ MU_CP * distance_terms(pieces(coef_), g["patch"], g["need_cp"], 0.05)[0]
|
| 710 |
-
+ MU_K * (smooth(curvature(coef_) * g["k_scale"] - (1 - MARGIN_K), 0.05)[0] ** 2).sum())
|
| 711 |
-
|
| 712 |
-
print(f"objective {float(phi):.6g} against {float(objective(coef, logi)):.6g}; worst field error / target {float(worst):.3f}")
|
| 713 |
-
ga, gl = torch.func.grad(objective, argnums=(0, 1))(coef, logi)
|
| 714 |
-
print("half-gradient in the coefficients (|B| held fixed in the analytic one), relative:", rel(grad[:NPAR], 0.5 * ga.reshape(-1)),
|
| 715 |
-
"in the log currents:", rel(grad[NPAR:], 0.5 * gl))
|
| 716 |
|
| 717 |
|
| 718 |
if __name__ == "__main__":
|
| 719 |
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 720 |
-
argv, device, strata, dtype = sys.argv[1:], "cpu", ("loose", "medium", "tight"), torch.float32
|
| 721 |
while "--set" in argv:
|
| 722 |
j = argv.index("--set")
|
| 723 |
name, value = argv[j + 1].split("=")
|
| 724 |
globals()[name] = type(globals()[name])(value)
|
| 725 |
del argv[j:j + 2]
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
|
|
|
|
|
|
| 734 |
if "--double" in argv:
|
| 735 |
argv.remove("--double")
|
| 736 |
dtype = torch.float64
|
| 737 |
-
|
| 738 |
-
selftest()
|
| 739 |
-
elif argv[0] == "try":
|
| 740 |
-
setup(device, dtype)
|
| 741 |
-
attempt(int(argv[1]), argv[2], strata)
|
| 742 |
-
else:
|
| 743 |
-
import wrap
|
| 744 |
-
setup("cpu")
|
| 745 |
-
if argv[0] == "export":
|
| 746 |
-
wrap.export(sys.modules[__name__], argv[1])
|
| 747 |
-
else:
|
| 748 |
-
wrap.timing(sys.modules[__name__], argv[1], *[int(a) for a in argv[2:]])
|
|
|
|
| 1 |
+
"""A coil optimizer for the Coilstellaration benchmark that writes its own ONNX graph, for any number of field
|
| 2 |
+
periods and coils per half period, in which no operation is one onnxruntime hands to its thread pool.
|
| 3 |
|
| 4 |
A first guess is improved by ITERS Levenberg-Marquardt steps on least-squares residuals of the instance's four
|
| 5 |
targets: the field error at every point of a surface grid above its target, and penalties for each coil-coil and
|
| 6 |
coil-plasma point pair closer than its target and each coil point more curved than its target. The hinges of those
|
| 7 |
+
residuals are rounded over a width that shrinks from step to step. Jacobians are analytic; each step solves its
|
| 8 |
+
linear system by conjugate gradients without forming the Gauss-Newton matrix. The model is three functions:
|
| 9 |
+
prepare() measures the boundary and the clearance circles, step() is the body of a loop, and finish() returns the
|
| 10 |
+
circles when they pass and the optimized coilset otherwise. A pass of the loop evaluates the trial coilset, keeps
|
| 11 |
+
it if the objective fell, and solves for the next trial, so ITERS steps take ITERS + 1 passes; none is taken when
|
| 12 |
+
the circles pass.
|
| 13 |
|
| 14 |
+
The functions run on torch tensors and, unchanged, on sym.Sym tensors, which write the ONNX nodes. Every matrix
|
| 15 |
+
product is two-dimensional with rows x columns x inner size at most MM_MAX and every other operation touches at
|
| 16 |
+
most EL_MAX values: the field is evaluated over chunks of surface points and the distances over chunks of coil
|
| 17 |
+
points. There is no Transpose: a transposed array is built by a second product or by a gather.
|
| 18 |
|
| 19 |
+
The parameter vector holds the coefficients ordered (coil, axis, mode) and then the logarithms of the currents.
|
| 20 |
+
|
| 21 |
+
python lm.py try N TAG [--track fixed_shape|variable_shape] [--strata loose,medium,tight] [--device cuda] [--double]
|
| 22 |
+
[--set NAME=VALUE ...]
|
| 23 |
+
|
| 24 |
+
try reads dev instances (a twentieth of the training boundaries) from a local table of the dataset.
|
| 25 |
"""
|
| 26 |
from __future__ import annotations
|
| 27 |
|
|
|
|
| 35 |
HERE = Path(__file__).resolve().parent
|
| 36 |
sys.path[:0] = [str(HERE), str(HERE.parent), str(HERE.parent / "scorer")]
|
| 37 |
|
| 38 |
+
import sym as S # noqa: E402
|
| 39 |
+
|
| 40 |
+
ORDER = 7
|
| 41 |
+
NM = 2 * ORDER + 1
|
| 42 |
DEG = np.pi / 180
|
| 43 |
BASE = HERE.parent / "data" / "models" / "baselines" / "per_coil_ensemble_DAr7gipsQu9Mupbnsm2rAaK.onnx"
|
| 44 |
ASKS = { # what the first-guess network is asked for: the targets times a scale, then held between two bounds
|
| 45 |
"floors": ((1.2, 1.2, 0.85, 1.0), (0.40, 0.60, -1e30, -1e30), (1e30, 1e30, 3.5, 0.01)),
|
| 46 |
"asked": ((1.0, 1.0, 1.0, 1.0), (-1e30, -1e30, -1e30, -1e30), (1e30, 1e30, 1e30, 1e30)),
|
|
|
|
|
|
|
|
|
|
| 47 |
}
|
| 48 |
ASK = "switch" # a key of ASKS, or "switch": "floors" where the field-error target is above ASK_SWITCH, else "asked"
|
| 49 |
ASK_SWITCH = 0.1
|
| 50 |
|
| 51 |
+
ITERS = 110 # Levenberg-Marquardt steps
|
| 52 |
+
P_F, P_G, P_K = 40, 96, 400 # coil points: field quadrature, distances and segments, curvature
|
| 53 |
+
P_GC = 32 # points and segments of the coarse coil-coil term, a divisor of P_G
|
| 54 |
NJ = 3 # images of the unique coils kept in the field's Jacobian (the nearby ones)
|
| 55 |
NEAR = 2 # neighbouring coils in the fine coil-coil term
|
| 56 |
+
P_R = 64 # points per circle in the circles' coil-coil check
|
| 57 |
STEP_MAX = 0.10 # largest displacement of a coil point in one step, in metres
|
| 58 |
+
GRID_T, GRID_PK = 40, 4.0 # field grid: theta points, and phi points per coil over the half period
|
| 59 |
+
PATCH_W, PATCH_DP, PATCH_DT = 16, 2, 2 # plasma patch: half-width in degrees, phi and theta strides
|
|
|
|
| 60 |
W_CHECK = 24 # half-width in degrees of the circles' plasma patch
|
|
|
|
| 61 |
MARGIN_CC, MARGIN_CP, ABS_GAP, MARGIN_K, MARGIN_F = 0.01, 0.02, 0.01, 0.01, 0.10 # what the optimizer asks beyond each target
|
| 62 |
MU_CC, MU_CP, MU_K = 1e3, 1e3, 1e3 # penalty weights of the geometric residuals
|
|
|
|
|
|
|
| 63 |
ETA = 0.05 # weight of the plain field residual beside the hinged one
|
| 64 |
LAMBDA0, LAMBDA_DOWN, LAMBDA_UP, LAMBDA_MIN, LAMBDA_MAX = 3.0, 1 / 3, 4.0, 0.1, 1e6
|
| 65 |
RATIO_LO, RATIO_HI = 0.25, 0.75 # actual over predicted drop: below, lambda up; above, lambda down
|
| 66 |
EPS0, EPS1, EPS_F = 0.2, 0.03, 0.1 # width of the smoothed hinges: geometric, first to last step, and field
|
| 67 |
BETA = 0.01 # extra damping of harmonic n, as BETA n^4
|
|
|
|
| 68 |
CG_ITERS = 12
|
| 69 |
+
OPT_CURRENT = 1 # 1: the currents are free as well
|
| 70 |
+
PASS_CC, PASS_CP, PASS_GAP, PASS_K, PASS_F_RING = 1.002, 1.006, 0.004, 0.997, 0.97 # the circles' pass check: room for the benchmark's own grids
|
| 71 |
+
CAP, CLEAR, C2C_MARGIN = 0.45, 1.03, 1.05 # the clearance circles
|
| 72 |
+
MM_MAX, EL_MAX = 65000, 50000 # largest matrix product (rows x columns x inner) and other operation (values)
|
| 73 |
+
BIG = 1.0e6 # added to the squared distance, in m^2, of a pair that does not count
|
| 74 |
+
P120, P201 = [1, 2, 0], [2, 0, 1]
|
| 75 |
+
|
| 76 |
+
NFP, K, C, NPAR, NIMG, N = 3, 5, 30, 225, 6, 230
|
| 77 |
F = torch.float32
|
| 78 |
DEVICE = "cpu"
|
| 79 |
TAB = None
|
| 80 |
+
TABS = {}
|
| 81 |
|
| 82 |
|
| 83 |
def _t(a):
|
|
|
|
| 92 |
np.concatenate([-(n * n * s)[::-1], z, -n * n * c]))
|
| 93 |
|
| 94 |
|
| 95 |
+
def mm(a, b):
|
| 96 |
+
"""A two-dimensional matrix product small enough to run in the calling thread."""
|
| 97 |
+
assert len(a.shape) == 2 and len(b.shape) == 2 and a.shape[0] * a.shape[1] * b.shape[1] <= MM_MAX, (tuple(a.shape), tuple(b.shape))
|
| 98 |
+
return S.matmul(a, b)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def ones(n):
|
| 102 |
+
"""A column of n ones."""
|
| 103 |
+
if n not in TAB.ones:
|
| 104 |
+
TAB.ones[n] = torch.ones(n, 1, dtype=F, device=DEVICE)
|
| 105 |
+
return TAB.ones[n]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def zeros(*shape):
|
| 109 |
+
"""Zeros: written into a graph as an Expand when large, so that the file does not hold them."""
|
| 110 |
+
if S.G is not None and int(np.prod(shape)) > 64:
|
| 111 |
+
return S.lift(0.0).expand(*shape)
|
| 112 |
+
return torch.zeros(*shape, dtype=F, device=DEVICE)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def scalar(v):
|
| 116 |
+
return torch.as_tensor(v, dtype=F, device=DEVICE)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def spans(n, size):
|
| 120 |
+
return [(a, min(a + size, n)) for a in range(0, n, size)]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def add(total, part):
|
| 124 |
+
return part if total is None else total + part
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def cross(a, b):
|
| 128 |
+
"""The cross product of the rows of two (n, 3) arrays."""
|
| 129 |
+
return S.take(a, P120, 1) * S.take(b, P201, 1) - S.take(a, P201, 1) * S.take(b, P120, 1)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def cross_rows(a, b):
|
| 133 |
+
"""The cross product of the columns of two (3, n) arrays."""
|
| 134 |
+
return S.take(a, P120, 0) * S.take(b, P201, 0) - S.take(a, P201, 0) * S.take(b, P120, 0)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def outer9(p, q):
|
| 138 |
+
"""Row by row the outer product of two (n, 3) arrays, as (n, 9)."""
|
| 139 |
+
return (p[:, :, None] * q[:, None, :]).reshape(-1, 9)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
class Grid:
|
| 143 |
+
"""The boundary on a grid of phi (P,) by theta (T,), from tables of each angle alone:
|
| 144 |
+
R = sum r_cos[m, n] cos(m theta - n NFP phi), Z = sum z_sin[m, n] sin(m theta - n NFP phi).
|
| 145 |
+
The coefficient arrays come transposed, (9, 5)."""
|
| 146 |
|
| 147 |
def __init__(self, theta, phi, normals=False):
|
| 148 |
+
m = np.arange(5)[:, None]
|
| 149 |
+
n = (np.arange(-4, 5) * NFP)[:, None]
|
| 150 |
+
ct, st = np.cos(m * theta), np.sin(m * theta) # (5, T)
|
| 151 |
+
cp, sp = np.cos(n * phi).T, np.sin(n * phi).T # (P, 9)
|
| 152 |
+
self.CP, self.SP = _t(cp), _t(sp)
|
| 153 |
+
self.R, self.Z = _t(np.concatenate([ct, st])), _t(np.concatenate([st, -ct])) # (10, T), for [a | b] and [c | d]
|
|
|
|
| 154 |
if normals:
|
| 155 |
+
self.nCP, self.nSP = _t(n.T * cp), _t(n.T * sp)
|
| 156 |
+
self.Rt, self.Zt = _t(np.concatenate([-m * st, m * ct])), _t(np.concatenate([m * ct, m * st]))
|
| 157 |
+
self.Rp, self.Zp = _t(np.concatenate([-ct, st])), _t(np.concatenate([-st, -ct]))
|
| 158 |
self.cos, self.sin = _t(np.cos(phi))[:, None], _t(np.sin(phi))[:, None]
|
| 159 |
+
self.points = len(phi) * len(theta)
|
| 160 |
+
self.rows = spans(len(phi), max(1, MM_MAX // (10 * len(theta)))) # phi rows per matrix product
|
| 161 |
+
|
| 162 |
+
def _rows(self, left, table):
|
| 163 |
+
"""left (P, 10) times table (10, T), a span of rows at a time."""
|
| 164 |
+
if len(self.rows) == 1:
|
| 165 |
+
return mm(left, table)
|
| 166 |
+
return S.cat([mm(left[a:b], table) for a, b in self.rows])
|
| 167 |
+
|
| 168 |
+
def lefts(self, rcT, zsT):
|
| 169 |
+
return S.cat([mm(self.CP, rcT), mm(self.SP, rcT)], 1), S.cat([mm(self.CP, zsT), mm(self.SP, zsT)], 1)
|
| 170 |
+
|
| 171 |
+
def rz(self, rcT, zsT):
|
| 172 |
+
"""R and Z, (P, T) each."""
|
| 173 |
+
L1, L2 = self.lefts(rcT, zsT)
|
| 174 |
+
return self._rows(L1, self.R), self._rows(L2, self.Z)
|
| 175 |
+
|
| 176 |
+
def xyz(self, rcT, zsT):
|
| 177 |
+
R, Z = self.rz(rcT, zsT)
|
| 178 |
+
return S.stack([R * self.cos, R * self.sin, Z], -1)
|
| 179 |
+
|
| 180 |
+
def points_normals(self, rcT, zsT):
|
| 181 |
+
"""The grid's points and unit normals, (P T, 3) each."""
|
| 182 |
+
L1, L2 = self.lefts(rcT, zsT)
|
| 183 |
+
L3 = S.cat([mm(self.nSP, rcT), mm(self.nCP, rcT)], 1)
|
| 184 |
+
L4 = S.cat([mm(self.nSP, zsT), mm(self.nCP, zsT)], 1)
|
| 185 |
+
R, Z = self._rows(L1, self.R), self._rows(L2, self.Z)
|
| 186 |
+
Rt, Zt = self._rows(L1, self.Rt), self._rows(L2, self.Zt)
|
| 187 |
+
Rp, Zp = self._rows(L3, self.Rp), self._rows(L4, self.Zp)
|
| 188 |
+
x = S.stack([R * self.cos, R * self.sin, Z], -1).reshape(-1, 3)
|
| 189 |
+
et = S.stack([Rt * self.cos, Rt * self.sin, Zt], -1).reshape(-1, 3)
|
| 190 |
+
ep = S.stack([Rp * self.cos - R * self.sin, Rp * self.sin + R * self.cos, Zp], -1).reshape(-1, 3)
|
| 191 |
nrm = cross(et, ep)
|
| 192 |
+
return x, nrm / mm(nrm * nrm, ones(3)).sqrt()
|
| 193 |
|
| 194 |
|
| 195 |
class Tables:
|
| 196 |
+
"""Constants of the graph for the current NFP and K."""
|
| 197 |
|
| 198 |
def __init__(self):
|
| 199 |
+
assert P_G % P_GC == 0 and NFP >= 2
|
| 200 |
+
self.ones = {}
|
| 201 |
th64 = 2 * np.pi * np.arange(64) / 64
|
| 202 |
+
self.shift = np.roll(np.arange(64), -1)
|
| 203 |
self.area = Grid(th64, 2 * np.pi / NFP * np.arange(48) / 48)
|
| 204 |
self.phi_k = (np.arange(K) + 0.5) * np.pi / (NFP * K)
|
| 205 |
self.cen = Grid(th64, self.phi_k)
|
| 206 |
+
around = lambda w, step: (self.phi_k[:, None] + (np.arange(-w, w + 1, step) * DEG)[None]).reshape(-1) # noqa: E731
|
| 207 |
+
self.patch = Grid(th64[::PATCH_DT], around(PATCH_W, PATCH_DP))
|
| 208 |
+
self.plane = Grid(th64, around(W_CHECK, 1))
|
| 209 |
d = np.arange(-W_CHECK, W_CHECK + 1) * DEG
|
| 210 |
self.dphi_cos, self.dphi_sin = _t(np.cos(d))[:, None], _t(np.sin(d))[:, None]
|
| 211 |
+
self.grid_p = int(round(GRID_PK * K)) + 1
|
| 212 |
+
self.grid = Grid(2 * np.pi * np.arange(GRID_T) / GRID_T, np.linspace(0, np.pi / NFP, self.grid_p), True)
|
| 213 |
+
self.X = self.grid.points
|
| 214 |
+
# surface points per chunk of the field: the pair arrays, the Jacobian and every product with them stay small
|
| 215 |
+
self.xspans = spans(self.X, min(EL_MAX // (K * P_F), EL_MAX // N, MM_MAX // (P_F * NM), MM_MAX // (3 * K * P_F), MM_MAX // (9 * K * K)))
|
| 216 |
+
self.one_rows = {b - a: torch.ones(1, b - a, dtype=F, device=DEVICE) for a, b in self.xspans}
|
| 217 |
+
self.basis = {p: tuple(_t(b) for b in _basis(p)) for p in {P_F, P_G, P_K, P_R}}
|
| 218 |
+
self.basis_t = {p: tuple(_t(b.T) for b in _basis(p)) for p in {P_F, P_G, P_K, P_R}}
|
| 219 |
+
step = 2 * np.pi / P_F
|
| 220 |
+
self.B0, self.dB1 = self.basis[P_F][0], step * self.basis[P_F][1] # (NM, P_F)
|
| 221 |
+
self.B0t, self.dB1t = self.basis_t[P_F][0], step * self.basis_t[P_F][1] # (P_F, NM)
|
| 222 |
+
self.B0c, self.B0ct = _t(_basis(P_G)[0][:, ::P_G // P_GC]), _t(_basis(P_G)[0][:, ::P_G // P_GC].T)
|
| 223 |
# the 2 NFP maps of a unique coil: partner (x, -y, -z) or not, then a rotation
|
| 224 |
ang = 2 * np.pi * np.arange(NFP) / NFP
|
| 225 |
maps = np.stack([np.array([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]]) @ np.diag(f)
|
| 226 |
for a in ang for f in ([1.0, 1.0, 1.0], [1.0, -1.0, -1.0])])
|
| 227 |
sign = np.tile([1.0, -1.0], NFP)
|
| 228 |
+
self.maps = [_t(m) for m in maps] # maps[j] @ v = T_j v
|
| 229 |
+
self.maps_t = [_t(m.T) for m in maps] # v @ maps_t[j] = T_j v
|
|
|
|
|
|
|
| 230 |
# the same maps for the field, the images near the half period first: the coils, their partners, and the
|
| 231 |
+
# partners turned by one period
|
| 232 |
+
near_first = [0, 1, 3] + [j for j in range(NIMG) if j not in (0, 1, 3)]
|
| 233 |
+
self.fmaps = [_t(maps[j]) for j in near_first] # x @ fmaps[j] = T_j^T x
|
| 234 |
+
self.fsign = [float(sign[j]) for j in near_first]
|
| 235 |
+
self.kron_back = [_t(np.kron(np.eye(K), maps[j].T * sign[j])) for j in near_first] # (n, 3 K) @ it: each coil's field turned back
|
| 236 |
+
eye = np.eye(3)
|
| 237 |
+
self.tile3, self.tile3t = _t(np.tile(eye, (K, 1))), _t(np.tile(eye, (1, K))) # (3 K, 3) sums the coils; (3, 3 K) repeats a row
|
| 238 |
+
self.block1 = _t(np.kron(np.eye(K), np.ones((3, 1)))) # (3 K, K) sums each coil's three columns
|
| 239 |
+
self.idx120 = [6 * k + c for k in range(K) for c in (1, 2, 0)]
|
| 240 |
+
self.idx201 = [6 * k + c for k in range(K) for c in (2, 0, 1)]
|
| 241 |
+
self.idx345 = [6 * k + c for k in range(K) for c in (3, 4, 5)]
|
| 242 |
+
self.rows_ck = [k * 3 + c for c in range(3) for k in range(K)] # rows (coil, axis) reordered (axis, coil)
|
| 243 |
+
self.perm_T = np.arange(3 * K * NM).reshape(3 * K, NM).T.reshape(-1)
|
| 244 |
+
# "near": the NEAR nearest coils in toroidal angle, as (image, coil) pairs per unique coil. The coarse term
|
| 245 |
+
# is against every coil of the nearby images but the coil itself and its near ones, which its mask removes.
|
| 246 |
nominal = np.concatenate([np.concatenate([self.phi_k, -self.phi_k]) + a for a in ang])
|
| 247 |
gap = np.abs((nominal[None, :] - self.phi_k[:, None] + np.pi) % (2 * np.pi) - np.pi)
|
| 248 |
gap[np.arange(K), np.arange(K)] = np.inf
|
|
|
|
| 249 |
order = np.argsort(gap, axis=1, kind="stable")
|
| 250 |
+
self.nearby = (0, 1, 3)
|
| 251 |
+
self.near = [[divmod(int(c), K) for c in order[k, :NEAR]] for k in range(K)]
|
| 252 |
+
self.near_images = sorted({j for members in self.near for j, _ in members})
|
| 253 |
+
self.needed = sorted(set(self.nearby) | set(self.near_images))
|
| 254 |
+
mask = np.zeros((K, 1, len(self.nearby) * K * P_GC))
|
| 255 |
+
for k in range(K):
|
| 256 |
+
for slot, j in enumerate(self.nearby):
|
| 257 |
+
for other in range(K):
|
| 258 |
+
if (j, other) == (0, k) or (j, other) in self.near[k]:
|
| 259 |
+
mask[k, 0, (slot * K + other) * P_GC:(slot * K + other + 1) * P_GC] = BIG
|
| 260 |
+
self.far_mask = [_t(mask[k]) for k in range(K)]
|
| 261 |
self.cos_k, self.sin_k = _t(np.cos(self.phi_k)), _t(np.sin(self.phi_k))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
self.half = _t([np.cos(np.pi / (2 * NFP)), np.sin(np.pi / (2 * NFP)), 0.0])
|
|
|
|
| 263 |
harmonic = np.abs(np.arange(NM) - ORDER)
|
| 264 |
+
self.stiff = _t(np.concatenate([np.tile(1.0 + BETA * harmonic ** 4, K * 3), np.ones(K)]))[:, None]
|
| 265 |
+
self.cur_mask = _t(np.concatenate([np.ones(NPAR), np.full(K, float(OPT_CURRENT))]))[:, None]
|
| 266 |
+
self.zero_k = torch.zeros(K, 1, dtype=F, device=DEVICE)
|
| 267 |
|
| 268 |
|
| 269 |
+
def configure(nfp=3, k=5, device="cpu", dtype=torch.float32, fresh=False):
|
| 270 |
+
"""Set the number of field periods and of coils per half period, and build or reuse their tables."""
|
| 271 |
+
global NFP, K, C, NPAR, NIMG, N, DEVICE, F, TAB
|
| 272 |
+
NFP, K, DEVICE, F = nfp, k, device, dtype
|
| 273 |
+
C, NPAR, NIMG = 2 * nfp * k, k * 3 * NM, 2 * nfp
|
| 274 |
+
N = NPAR + k
|
| 275 |
+
key = (nfp, k, device, dtype)
|
| 276 |
+
if fresh or key not in TABS:
|
| 277 |
+
TABS[key] = Tables()
|
| 278 |
+
TAB = TABS[key]
|
| 279 |
|
| 280 |
|
| 281 |
+
def layouts(coef):
|
| 282 |
+
"""The coefficients (K, 3, NM) as rows ordered (coil, axis), as rows ordered (axis, coil), both (3 K, NM), and
|
| 283 |
+
transposed, (NM, 3 K) with columns ordered (coil, axis)."""
|
| 284 |
+
flat = coef.reshape(3 * K, NM)
|
| 285 |
+
return flat, S.take(flat, TAB.rows_ck, 0), S.take(coef.reshape(3 * K * NM), TAB.perm_T, 0).reshape(NM, 3 * K)
|
| 286 |
|
| 287 |
|
| 288 |
+
def points(flatT, Bt):
|
| 289 |
+
"""Per coil, (P, 3): a basis table (P, NM) on the transposed coefficients (NM, 3 K)."""
|
| 290 |
+
per = max(1, min(K, MM_MAX // (3 * NM * Bt.shape[0])))
|
| 291 |
+
out = []
|
| 292 |
+
for a in range(0, K, per):
|
| 293 |
+
b = min(a + per, K)
|
| 294 |
+
out += S.split(mm(Bt, flatT if (a, b) == (0, K) else flatT[:, 3 * a:3 * b]), 3, 1)
|
| 295 |
+
return out
|
| 296 |
|
| 297 |
|
| 298 |
+
def rows_of(flat, B):
|
| 299 |
+
"""flat (rows, NM) times a basis table (NM, P), a span of rows at a time."""
|
| 300 |
+
per = max(1, MM_MAX // (NM * B.shape[1]))
|
| 301 |
+
if flat.shape[0] <= per:
|
| 302 |
+
return mm(flat, B)
|
| 303 |
+
return S.cat([mm(flat[a:b], B) for a, b in spans(flat.shape[0], per)])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
|
| 306 |
def smooth(x, eps):
|
| 307 |
"""A hinge max(0, x) rounded over |x| < eps, with its derivative: 0 below -eps, (x + eps)^2 / (4 eps) between."""
|
| 308 |
+
s = S.clamp(x * (0.5 / eps) + 0.5, min=0.0, max=1.0)
|
| 309 |
+
return eps * s * s + S.clamp(x - eps, min=0.0), s
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def field_terms(coef, amp, g, jac):
|
| 313 |
+
"""The field error f at the X grid points, chunk by chunk of surface points. Without jac, the largest |f|. With
|
| 314 |
+
jac: the objective (hinged and plain residuals), half its gradient (N, 1), the diagonal of its Gauss-Newton
|
| 315 |
+
matrix (N, 1), the largest |f| over its target, and per chunk the Jacobian of f (n, N) with each row scaled by
|
| 316 |
+
the root of its weight. The dependence of |B| on the coefficients and the images of the coils beyond the NJ
|
| 317 |
+
nearby ones are left out of the Jacobian."""
|
| 318 |
+
P, o = P_F, g["o"]
|
| 319 |
+
flat, flat_ck, flatT = layouts(coef)
|
| 320 |
+
r_pt = [p - o for p in points(flatT, TAB.B0t)] # (P, 3) per coil, centred
|
| 321 |
+
e_pt = points(flatT, TAB.dB1t)
|
| 322 |
+
eT = S.cat(e_pt)
|
| 323 |
+
EXk = S.split(S.cat([eT, cross(eT, S.cat(r_pt))], 1), P, 0) # (P, 6) per coil: e and e x r
|
| 324 |
+
rTt = rows_of(flat_ck, TAB.B0).reshape(3, K * P) - o.reshape(3, 1) # (3, K P)
|
| 325 |
+
eTt = rows_of(flat_ck, TAB.dB1).reshape(3, K * P)
|
| 326 |
+
exrt = cross_rows(eTt, rTt)
|
| 327 |
+
rsq = (rTt * rTt).sum(0).reshape(1, K * P)
|
| 328 |
+
amp_row = amp.reshape(K, 1).expand(K, P).reshape(1, K * P)
|
| 329 |
+
if jac:
|
| 330 |
+
rc = [S.split(r, 1, 1) for r in r_pt]
|
| 331 |
+
ec = [S.split(e, 1, 1) for e in e_pt]
|
| 332 |
+
M12 = [[TAB.dB1t * rc[k][c] - TAB.B0t * ec[k][c] for c in range(3)] for k in range(K)]
|
| 333 |
+
M3 = [[TAB.B0t * rc[k][c] for c in range(3)] for k in range(K)]
|
| 334 |
+
inv_tau = 1.0 / g["tau"]
|
| 335 |
+
phi = worst = grad = diag = None
|
| 336 |
+
Jh = []
|
| 337 |
+
for s, (a, b) in enumerate(TAB.xspans):
|
| 338 |
+
n = b - a
|
| 339 |
+
gk = BK = Jg = None
|
| 340 |
+
for j in range(NIMG):
|
| 341 |
+
t = g["fld"][j][s]
|
| 342 |
+
inv = 1.0 / (t["ysq"] + rsq + mm(t["ym2"], rTt)) # (n, K P): 1 / |d|^2
|
| 343 |
+
w3 = inv * inv.sqrt() * amp_row # I / |d|^3
|
| 344 |
+
sw = (mm(t["cy"], eTt) - mm(t["m"], exrt)) * w3 # I e . (d x m) / |d|^3, with the image's sign
|
| 345 |
+
Wk, SWk = S.split(w3, P, 1), S.split(sw, P, 1)
|
| 346 |
+
gj = S.cat([mm(SWk[k], ones(P)) for k in range(K)], 1) # (n, K)
|
| 347 |
+
WB = S.cat([mm(Wk[k], EXk[k]) for k in range(K)], 1) # (n, 6 K): sums of w e and of w e x r
|
| 348 |
+
bj = mm(S.take(WB, TAB.idx120, 1) * t["y201"] - S.take(WB, TAB.idx201, 1) * t["y120"] - S.take(WB, TAB.idx345, 1),
|
| 349 |
+
TAB.kron_back[j]) # (n, 3 K): each coil family's field
|
| 350 |
+
gk, BK = add(gk, gj), add(BK, bj)
|
| 351 |
+
if jac and j < NJ:
|
| 352 |
+
S5k = S.split(3.0 * sw * inv, P, 1) # 3 I s / |d|^5
|
| 353 |
+
v12 = [[mm(Wk[k], M12[k][c]) for c in range(3)] for k in range(K)]
|
| 354 |
+
v3 = [[mm(S5k[k], M3[k][c]) for c in range(3)] for k in range(K)]
|
| 355 |
+
u1 = S.cat([mm(Wk[k], TAB.dB1t) for k in range(K)], 1).reshape(n, K, 1, NM)
|
| 356 |
+
u0 = S.cat([mm(S5k[k], TAB.B0t) for k in range(K)], 1).reshape(n, K, 1, NM)
|
| 357 |
+
A = S.cat([v12[k][(c + 2) % 3] for k in range(K) for c in range(3)], 1).reshape(n, K, 3, NM)
|
| 358 |
+
Bm = S.cat([v12[k][(c + 1) % 3] for k in range(K) for c in range(3)], 1).reshape(n, K, 3, NM)
|
| 359 |
+
V3 = S.cat([v3[k][c] for k in range(K) for c in range(3)], 1).reshape(n, K, 3, NM)
|
| 360 |
+
Jg = add(Jg, t["mc1"] * A - t["mc2"] * Bm + t["cy4"] * u1 - V3 + t["y4"] * u0) # m x V12 + (y x m) U1 - V3 + y U0
|
| 361 |
+
B = mm(BK, TAB.tile3) # (n, 3)
|
| 362 |
+
inv_bn = 1.0 / mm(B * B, ones(3)).sqrt() # (n, 1)
|
| 363 |
+
f = mm(gk, ones(K)) * inv_bn
|
| 364 |
+
worst = S.maximum(worst, f.abs().max()) if worst is not None else f.abs().max()
|
| 365 |
+
if not jac:
|
| 366 |
+
continue
|
| 367 |
+
Jc = (gk - f * mm(BK * mm(B, TAB.tile3t), TAB.block1) * inv_bn) * inv_bn # in the log currents, (n, K)
|
| 368 |
+
J = S.cat([Jg.reshape(n, NPAR) * inv_bn, Jc if OPT_CURRENT else Jc * 0.0], 1) # (n, N)
|
| 369 |
+
ft = f * inv_tau
|
| 370 |
+
(hp, sp), (hm, sm) = smooth(ft - (1 - MARGIN_F), EPS_F), smooth(-ft - (1 - MARGIN_F), EPS_F)
|
| 371 |
+
plain = ft * ETA
|
| 372 |
+
w = (sp * sp + sm * sm + ETA * ETA) * (inv_tau * inv_tau) # (n, 1)
|
| 373 |
+
phi = add(phi, (hp * hp).sum() + (hm * hm).sum() + (plain * plain).sum())
|
| 374 |
+
grad = add(grad, mm(((hp * sp - hm * sm + plain * ETA) * inv_tau).reshape(1, n), J))
|
| 375 |
+
Jw = w.sqrt() * J
|
| 376 |
+
diag = add(diag, mm(TAB.one_rows[n], Jw * Jw))
|
| 377 |
+
Jh.append(Jw)
|
| 378 |
+
if not jac:
|
| 379 |
+
return worst
|
| 380 |
+
return phi, grad.reshape(N, 1), diag.reshape(N, 1), worst * inv_tau, Jh
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def images(Q_pt, T_pt, Q_ax, T_ax, needed):
|
| 384 |
+
"""The coils' points and tangents under each needed map: (K P, 3), (K P, 3), (3, K P), (3, K P) per map."""
|
| 385 |
+
out = {}
|
| 386 |
+
for j in needed:
|
| 387 |
+
out[j] = (Q_pt, T_pt, Q_ax, T_ax) if j == 0 else (mm(Q_pt, TAB.maps_t[j]), mm(T_pt, TAB.maps_t[j]),
|
| 388 |
+
mm(TAB.maps[j], Q_ax), mm(TAB.maps[j], T_ax))
|
| 389 |
+
return out
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def tangents(t, tT, full=True):
|
| 393 |
+
"""What the distance terms take from the other side's tangents alone, (S, 3) and (3, S)."""
|
| 394 |
+
n = t.shape[0]
|
| 395 |
+
b = S.clamp((tT * tT).sum(0), min=1e-12).reshape(1, n)
|
| 396 |
+
out = dict(t=t, tt=tT, b=b, inv_b=1.0 / b)
|
| 397 |
+
if full:
|
| 398 |
+
out["ttm"] = S.split(outer9(t, t), 3, 1)
|
| 399 |
+
return out
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def side(q, qT, tan=None, full=True):
|
| 403 |
+
"""What the distance terms take from the other side's points, (S, 3) and (3, S), with tangents() of its
|
| 404 |
+
tangents if it is segments; full adds the tables of the second derivatives."""
|
| 405 |
+
n = q.shape[0]
|
| 406 |
+
out = dict(q=q, qt2=-2.0 * qT, q2=(qT * qT).sum(0).reshape(1, n))
|
| 407 |
+
if full:
|
| 408 |
+
out["qq"] = S.split(outer9(q, q), 3, 1)
|
| 409 |
+
if tan is not None:
|
| 410 |
+
out.update(tan)
|
| 411 |
+
out["qdt"] = (qT * tan["tt"]).sum(0).reshape(1, n)
|
| 412 |
+
if full:
|
| 413 |
+
out["qtm"] = S.split(outer9(q, tan["t"]) + outer9(tan["t"], q), 3, 1)
|
| 414 |
+
return out
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def wide(weights, parts):
|
| 418 |
+
"""weights (n, S) times a table (S, 9) given as three (S, 3) parts."""
|
| 419 |
+
return S.cat([mm(weights, part) for part in parts], 1)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def distance_terms(rc, o, need, eps, hw=None, mask=None):
|
| 423 |
+
"""Coil points rc (n, 3) against the other side `o` (points, or with hw the segments q + u t, |u| <= hw) with
|
| 424 |
+
residuals v = smooth(1 - d / need): the sum of v^2, sum v dv/dr (n, 3) and the Gauss-Newton matrices
|
| 425 |
+
sum dv/dr dv/dr^T per coil point (n, 9). mask (1, S) is added to the squared distances."""
|
| 426 |
+
d2 = mm(rc * rc, ones(3)) + o["q2"] + mm(rc, o["qt2"]) # (n, S)
|
| 427 |
+
if hw is not None:
|
| 428 |
+
a = mm(rc, o["tt"]) - o["qdt"]
|
| 429 |
+
u = S.clamp(a * o["inv_b"], min=-hw, max=hw)
|
| 430 |
+
d2 = d2 - u * (2.0 * a - u * o["b"])
|
| 431 |
+
if mask is not None:
|
| 432 |
+
d2 = d2 + mask
|
| 433 |
+
inv = 1.0 / S.clamp(d2, min=1e-10)
|
| 434 |
root = inv.sqrt()
|
| 435 |
+
v, s = smooth(1.0 - d2 * root / need, eps)
|
|
|
|
| 436 |
c = v * s * root
|
| 437 |
+
act = inv * s * s
|
| 438 |
+
grad, aq, aqq = mm(c, o["q"]), mm(act, o["q"]), wide(act, o["qq"])
|
| 439 |
+
if hw is not None:
|
| 440 |
+
au = act * u
|
| 441 |
+
grad, aq, aqq = grad + mm(c * u, o["t"]), aq + mm(au, o["t"]), aqq + wide(au, o["qtm"]) + wide(au * u, o["ttm"])
|
| 442 |
+
grad = (grad - rc * mm(c, ones(c.shape[1]))) / need
|
| 443 |
+
hess = (mm(act, ones(act.shape[1])) * outer9(rc, rc) - outer9(rc, aq) - outer9(aq, rc) + aqq) / (need * need)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
return (v * v).sum(), grad, hess
|
| 445 |
|
| 446 |
|
| 447 |
+
def chunks(rc, o, need, eps, hw=None, mask=None):
|
| 448 |
+
"""distance_terms over spans of the coil points that keep its arrays and products small."""
|
| 449 |
+
size = o["q"].shape[0]
|
| 450 |
+
per = max(1, min(MM_MAX // (3 * size), EL_MAX // size))
|
| 451 |
+
assert size <= MM_MAX, size
|
| 452 |
+
if rc.shape[0] <= per:
|
| 453 |
+
return distance_terms(rc, o, need, eps, hw, mask)
|
| 454 |
+
loss, gs, hs = None, [], []
|
| 455 |
+
for a, b in spans(rc.shape[0], per):
|
| 456 |
+
part, g_, h_ = distance_terms(rc[a:b], o, need, eps, hw, mask)
|
| 457 |
+
loss = add(loss, part)
|
| 458 |
+
gs.append(g_)
|
| 459 |
+
hs.append(h_)
|
| 460 |
+
return loss, S.cat(gs), S.cat(hs)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def to_coefficients(grad, hess, B0, B0t):
|
| 464 |
+
"""One coil's point derivatives (P, 3) and (P, 9) as coefficient derivatives: a column (3 NM, 1) ordered
|
| 465 |
+
(axis, mode) and a matrix (3 NM, 3 NM)."""
|
| 466 |
+
g = S.tr(mm(B0, grad)).reshape(3 * NM, 1)
|
| 467 |
+
rows = S.split(S.tr(hess), 1, 0) # (1, P) each
|
| 468 |
+
blk = {}
|
| 469 |
+
for a in range(3):
|
| 470 |
+
for b in range(a, 3):
|
| 471 |
+
blk[a, b] = blk[b, a] = mm(B0 * rows[3 * a + b], B0t)
|
| 472 |
+
return g, S.cat([S.cat([blk[a, b] for b in range(3)], 1) for a in range(3)])
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def curvature_terms(r1, r2, k_scale, eps):
|
| 476 |
+
"""One coil's residuals v = smooth(curvature k_scale - (1 - MARGIN_K)) at P_K points from its derivatives
|
| 477 |
+
(P, 3): sum v^2, sum v dv/dcoef (3 NM, 1), the Gauss-Newton matrix (3 NM, 3 NM) and the largest curvature."""
|
| 478 |
_, B1, B2 = TAB.basis[P_K]
|
| 479 |
+
_, B1t, B2t = TAB.basis_t[P_K]
|
| 480 |
+
aa, bb, ab = mm(r1 * r1, ones(3)), mm(r2 * r2, ones(3)), mm(r1 * r2, ones(3)) # (P, 1)
|
| 481 |
+
n2 = S.clamp(aa * bb - ab * ab, min=1e-20)
|
| 482 |
+
kappa = n2.sqrt() / (aa * aa.sqrt())
|
| 483 |
+
v, s = smooth(kappa * k_scale - (1.0 - MARGIN_K), eps)
|
| 484 |
+
ks, kn = k_scale * s, kappa / n2
|
| 485 |
+
g1 = (kn * (bb * r1 - ab * r2) - 3.0 * kappa / aa * r1) * ks # d residual / d r', weighted
|
| 486 |
+
g2 = kn * (aa * r2 - ab * r1) * ks
|
| 487 |
+
c1, c2 = S.split(g1, 1, 1), S.split(g2, 1, 1) # (P, 1) per axis
|
| 488 |
+
Jt = S.cat([c1[c] * B1t + c2[c] * B2t for c in range(3)], 1) # (P, 3 NM)
|
| 489 |
+
J = S.cat([c1[c].reshape(1, P_K) * B1 + c2[c].reshape(1, P_K) * B2 for c in range(3)]) # (3 NM, P)
|
| 490 |
+
per = MM_MAX // (9 * NM * NM)
|
| 491 |
+
H = None
|
| 492 |
+
for left, right in zip(S.split(J, per, 1), S.split(Jt, per, 0)):
|
| 493 |
+
H = add(H, mm(left, right))
|
| 494 |
+
return (v * v).sum(), mm(J, v), H, kappa.max()
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def geometry_terms(coef, g, eps):
|
| 498 |
+
"""The geometric penalties: their value, half their gradient (N, 1), the diagonal of their Gauss-Newton matrix
|
| 499 |
+
(N, 1) and that matrix's blocks, one (3 NM, 3 NM) per coil."""
|
| 500 |
+
P, step = P_G, P_G // P_GC
|
| 501 |
+
flat, flat_ck, flatT = layouts(coef)
|
| 502 |
+
B0, B1, _ = TAB.basis[P]
|
| 503 |
+
B0t, B1t, _ = TAB.basis_t[P]
|
| 504 |
+
r_pt, t_pt = points(flatT, B0t), points(flatT, B1t)
|
| 505 |
+
img = images(S.cat(r_pt), S.cat(t_pt), rows_of(flat_ck, B0).reshape(3, K * P), rows_of(flat_ck, B1).reshape(3, K * P), TAB.needed)
|
| 506 |
+
far_q = S.cat([img[j][0][::step] for j in TAB.nearby]) # every nearby coil at the coarse points
|
| 507 |
+
far_qT = S.cat([img[j][2][:, ::step] for j in TAB.nearby], 1)
|
| 508 |
+
far_tan = tangents(S.cat([img[j][1][::step] for j in TAB.nearby]), S.cat([img[j][3][:, ::step] for j in TAB.nearby], 1))
|
| 509 |
+
per_coil = {j: (S.split(img[j][0], P, 0), S.split(img[j][1], P, 0), S.split(img[j][2], P, 1), S.split(img[j][3], P, 1))
|
| 510 |
+
for j in TAB.near_images}
|
| 511 |
+
k1, k2 = points(flatT, TAB.basis_t[P_K][1]), points(flatT, TAB.basis_t[P_K][2])
|
| 512 |
+
phi, grads, blocks = None, [], []
|
| 513 |
+
for k in range(K):
|
| 514 |
+
row, col, members = g["centre_rows"][k], g["centre_cols"][k], TAB.near[k]
|
| 515 |
+
near = side(S.cat([per_coil[j][0][m] for j, m in members]) - row, S.cat([per_coil[j][2][m] for j, m in members], 1) - col,
|
| 516 |
+
tangents(S.cat([per_coil[j][1][m] for j, m in members]), S.cat([per_coil[j][3][m] for j, m in members], 1)))
|
| 517 |
+
own = r_pt[k] - row
|
| 518 |
+
l_cc, g_cc, h_cc = chunks(own, near, g["need_cc"], eps, np.pi / P)
|
| 519 |
+
l_cp, g_cp, h_cp = chunks(own, g["patches"][k], g["need_cp"], eps)
|
| 520 |
+
l_far, g_far, h_far = chunks(own[::step], side(far_q - row, far_qT - col, far_tan), g["need_cc"], eps, np.pi / P_GC, TAB.far_mask[k])
|
| 521 |
+
gk, hk = to_coefficients(2.0 * MU_CC * g_cc + MU_CP * g_cp, 2.0 * MU_CC * h_cc + MU_CP * h_cp, B0, B0t)
|
| 522 |
+
gf, hf = to_coefficients(g_far, h_far, TAB.B0c, TAB.B0ct)
|
| 523 |
+
l_k, g_k, h_k, _ = curvature_terms(k1[k], k2[k], g["k_scale"], eps)
|
| 524 |
+
phi = add(phi, MU_CC * (l_cc + l_far) + MU_CP * l_cp + MU_K * l_k)
|
| 525 |
+
grads.append(gk + (2.0 * MU_CC) * gf + MU_K * g_k)
|
| 526 |
+
blocks.append(hk + (2.0 * MU_CC) * hf + MU_K * h_k)
|
| 527 |
+
diag = [h.reshape(9 * NM * NM)[::3 * NM + 1].reshape(3 * NM, 1) for h in blocks]
|
| 528 |
+
return phi, S.cat(grads + [TAB.zero_k]), S.cat(diag + [TAB.zero_k]), blocks
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def evaluate(coef, logi, g, eps):
|
| 532 |
+
"""The state of the optimizer at a coilset: the objective, half its gradient (N, 1), the diagonal of the
|
| 533 |
+
Gauss-Newton matrix (N, 1), the largest field error over its target, the geometric blocks, one (3 NM, 3 NM) per
|
| 534 |
+
coil, and the field's weighted Jacobian, one (n, N) per chunk of surface points."""
|
| 535 |
+
phi_f, grad_f, diag_f, worst, Jh = field_terms(coef, g["cur0"] * S.exp(logi), g, True)
|
| 536 |
+
phi_g, grad_g, diag_g, blocks = geometry_terms(coef, g, eps)
|
| 537 |
+
return phi_f + phi_g, grad_f + grad_g, diag_f + diag_g, worst, blocks, Jh
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def gauss_newton(p, blocks, Jh):
|
| 541 |
+
"""The Gauss-Newton matrix times a column p (N, 1)."""
|
| 542 |
+
row = None
|
| 543 |
+
for J in Jh:
|
| 544 |
+
row = add(row, mm(mm(J, p).reshape(1, J.shape[0]), J))
|
| 545 |
+
pieces = S.split(p, [3 * NM] * K + [K], 0)
|
| 546 |
+
return row.reshape(N, 1) + S.cat([mm(blocks[k], pieces[k]) for k in range(K)] + [TAB.zero_k])
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def solve(grad, diag, blocks, Jh, lam):
|
| 550 |
+
"""The Levenberg-Marquardt step: (A + lam D) delta = -grad by preconditioned conjugate gradients, A the
|
| 551 |
+
Gauss-Newton matrix and D its diagonal weighted up for the higher harmonics."""
|
| 552 |
+
damp = lam * (S.clamp(diag, min=1e-12) + 1e-9 * diag.max()) * TAB.stiff
|
| 553 |
+
pre = 1.0 / (diag + damp)
|
| 554 |
+
r = -grad
|
| 555 |
+
z = pre * r
|
| 556 |
+
p, rz, x = z, (r * z).sum(), None
|
| 557 |
+
for it in range(CG_ITERS):
|
| 558 |
+
Mp = gauss_newton(p, blocks, Jh) + damp * p
|
| 559 |
+
step = rz / S.clamp((p * Mp).sum(), min=1e-30)
|
| 560 |
+
x = add(x, step * p)
|
| 561 |
+
if it == CG_ITERS - 1:
|
| 562 |
+
break
|
| 563 |
+
r = r - step * Mp
|
| 564 |
+
z = pre * r
|
| 565 |
+
rz_new = (r * z).sum()
|
| 566 |
+
p, rz = z + (rz_new / S.clamp(rz, min=1e-30)) * p, rz_new
|
| 567 |
+
return x * TAB.cur_mask
|
| 568 |
|
| 569 |
|
| 570 |
def geometry(r_cos, z_sin, target):
|
| 571 |
+
"""Everything the optimizer and the circles need from the boundary and the targets."""
|
| 572 |
+
rcT, zsT = S.tr(r_cos), S.tr(z_sin)
|
| 573 |
+
R, Z = TAB.area.rz(rcT, zsT)
|
| 574 |
+
area = 0.5 * (R * S.take(Z, TAB.shift, 1) - S.take(R, TAB.shift, 1) * Z).sum(1).abs()
|
| 575 |
a = (area.mean() / np.pi).sqrt()
|
| 576 |
+
R, Z = TAB.cen.rz(rcT, zsT)
|
| 577 |
centre_r, centre_z = R.mean(1), Z.mean(1)
|
| 578 |
+
centre = S.stack([centre_r * TAB.cos_k, centre_r * TAB.sin_k, centre_z], 1) # (K, 3)
|
| 579 |
+
centre_rows = S.split(centre, 1, 0)
|
| 580 |
+
patch = TAB.patch.xyz(rcT, zsT).reshape(K, -1, 3)
|
| 581 |
+
patches = []
|
| 582 |
+
for k in range(K):
|
| 583 |
+
q = patch[k] - centre_rows[k]
|
| 584 |
+
patches.append(side(q, S.tr(q)))
|
| 585 |
+
R, Z = TAB.plane.rz(rcT, zsT)
|
| 586 |
r0 = r_cos[0, 4]
|
| 587 |
o = r0 * TAB.half
|
| 588 |
+
x, n = TAB.grid.points_normals(rcT, zsT)
|
| 589 |
+
fld = []
|
| 590 |
+
for j in range(NIMG): # the points in each image's frame
|
| 591 |
+
y = mm(x, TAB.fmaps[j]) - o
|
| 592 |
+
m = mm(n, TAB.fmaps[j]) if TAB.fsign[j] > 0 else -mm(n, TAB.fmaps[j]) # with the image's sign
|
| 593 |
+
tables = dict(ysq=mm(y * y, ones(3)), ym2=-2.0 * y, cy=cross(y, m), m=m,
|
| 594 |
+
y120=S.cat([S.take(y, P120, 1)] * K, 1), y201=S.cat([S.take(y, P201, 1)] * K, 1))
|
| 595 |
+
if j < NJ:
|
| 596 |
+
tables.update(mc1=S.take(m, P120, 1), mc2=S.take(m, P201, 1), cy4=tables["cy"], y4=y)
|
| 597 |
+
per_span = []
|
| 598 |
+
for a_, b_ in TAB.xspans:
|
| 599 |
+
part = {key: value[a_:b_] for key, value in tables.items()}
|
| 600 |
+
for key in ("mc1", "mc2", "cy4", "y4"):
|
| 601 |
+
if key in part:
|
| 602 |
+
part[key] = part[key].reshape(b_ - a_, 1, 3, 1)
|
| 603 |
+
per_span.append(part)
|
| 604 |
+
fld.append(per_span)
|
| 605 |
+
return dict(a=a, r0=r0, o=o, centre_r=centre_r, centre_z=centre_z, centre_rows=centre_rows,
|
| 606 |
+
centre_cols=[c.reshape(3, 1) for c in centre_rows], patches=patches,
|
| 607 |
+
plane_R=R.reshape(K, 2 * W_CHECK + 1, 64), plane_Z=Z.reshape(K, 2 * W_CHECK + 1, 64),
|
| 608 |
+
need_cc=S.maximum(target[0] * (1 + MARGIN_CC), target[0] + ABS_GAP) * a,
|
| 609 |
+
need_cp=S.maximum(target[1] * (1 + MARGIN_CP), target[1] + ABS_GAP) * a,
|
| 610 |
+
k_scale=a / target[2], tau=target[3], fld=fld)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 611 |
|
| 612 |
|
| 613 |
def circles(g, target):
|
| 614 |
+
"""The clearance circles as order-7 coefficient arrays (K, 3, NM), their currents, their radii and their
|
| 615 |
+
distance to the sampled boundary in minor radii: centred on each cross-section, in planes of constant toroidal
|
| 616 |
+
angle, as large as the coil-coil target allows up to CAP R0 and at least the radius that keeps CLEAR times the
|
| 617 |
+
coil-plasma target from the sampled boundary."""
|
| 618 |
d = CLEAR * target[1] * g["a"]
|
| 619 |
+
R, Z = g["plane_R"], g["plane_Z"] # (K, 2 W + 1, 64)
|
| 620 |
h = R * TAB.dphi_sin
|
| 621 |
+
dr, dz = R * TAB.dphi_cos - g["centre_r"].reshape(K, 1, 1), Z - g["centre_z"].reshape(K, 1, 1)
|
| 622 |
+
rho = (dr * dr + dz * dz).sqrt()
|
| 623 |
+
need = (rho + S.clamp(d * d - h * h, min=0.0).sqrt()) * (h.abs() < d).to(F)
|
| 624 |
+
r_clear = S.stack([need[k].max() for k in range(K)])
|
| 625 |
r_c2c = g["centre_r"] - C2C_MARGIN * target[0] * g["a"] / (2 * np.sin(np.pi / (2 * NFP * K)))
|
| 626 |
+
radius = S.maximum(r_clear, S.minimum(r_c2c, CAP * g["r0"]))
|
| 627 |
+
zero = torch.zeros(K, dtype=F, device=DEVICE)
|
| 628 |
+
mid = S.stack([S.stack([zero, g["centre_r"] * TAB.cos_k, radius * TAB.cos_k], 1), # x: sin 1, const, cos 1
|
| 629 |
+
S.stack([zero, g["centre_r"] * TAB.sin_k, radius * TAB.sin_k], 1),
|
| 630 |
+
S.stack([radius, g["centre_z"], zero], 1)], 1) # (K, 3, 3)
|
| 631 |
+
pad = torch.zeros(K, 3, ORDER - 1, dtype=F, device=DEVICE)
|
| 632 |
+
gap = rho - radius.reshape(K, 1, 1) # each boundary point to its circle
|
| 633 |
+
c2p = (h * h + gap * gap).min().sqrt() / g["a"]
|
| 634 |
+
return S.cat([pad, mid, pad], 2), (g["r0"] * (5.0e6 / (2 * NFP * K))).expand(K), radius, c2p
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def circles_pass(ring, ring_current, radius, c2p, g, target):
|
| 638 |
+
"""Whether the circles meet the four targets: the coil-coil distance between each circle and its neighbours'
|
| 639 |
+
segments, the coil-plasma distance from their construction, the curvature from the radii, the field error on
|
| 640 |
+
the optimizer's grid."""
|
| 641 |
+
P, hw = P_R, np.pi / P_R
|
| 642 |
+
flat, flat_ck, flatT = layouts(ring)
|
| 643 |
+
B0, B1, _ = TAB.basis[P]
|
| 644 |
+
B0t, B1t, _ = TAB.basis_t[P]
|
| 645 |
+
q_pt, t_pt = points(flatT, B0t), points(flatT, B1t)
|
| 646 |
+
img = images(S.cat(q_pt), S.cat(t_pt), rows_of(flat_ck, B0).reshape(3, K * P), rows_of(flat_ck, B1).reshape(3, K * P), TAB.near_images)
|
| 647 |
+
per_coil = {j: (S.split(v[0], P, 0), S.split(v[1], P, 0), S.split(v[2], P, 1), S.split(v[3], P, 1)) for j, v in img.items()}
|
| 648 |
+
d_cc = None
|
| 649 |
+
for k in range(K):
|
| 650 |
+
row, col, members = g["centre_rows"][k], g["centre_cols"][k], TAB.near[k]
|
| 651 |
+
o = side(S.cat([per_coil[j][0][m] for j, m in members]) - row, S.cat([per_coil[j][2][m] for j, m in members], 1) - col,
|
| 652 |
+
tangents(S.cat([per_coil[j][1][m] for j, m in members]), S.cat([per_coil[j][3][m] for j, m in members], 1), False), False)
|
| 653 |
+
own = q_pt[k] - row
|
| 654 |
+
for a, b in spans(P, max(1, MM_MAX // (3 * o["q"].shape[0]))):
|
| 655 |
+
rc = own if (a, b) == (0, P) else own[a:b]
|
| 656 |
+
d2 = mm(rc * rc, ones(3)) + o["q2"] + mm(rc, o["qt2"])
|
| 657 |
+
along = mm(rc, o["tt"]) - o["qdt"]
|
| 658 |
+
u = S.clamp(along * o["inv_b"], min=-hw, max=hw)
|
| 659 |
+
low = (d2 - u * (2.0 * along - u * o["b"])).min()
|
| 660 |
+
d_cc = S.minimum(d_cc, low) if d_cc is not None else low
|
| 661 |
+
worst = field_terms(ring, ring_current, g, False)
|
| 662 |
+
return ((S.clamp(d_cc, min=0.0).sqrt() / g["a"] >= S.maximum(target[0] * PASS_CC, target[0] + PASS_GAP))
|
| 663 |
+
& (c2p >= S.maximum(target[1] * PASS_CP, target[1] + PASS_GAP))
|
| 664 |
+
& (g["a"] / radius.min() <= target[2] * PASS_K) & (worst <= target[3] * PASS_F_RING))
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def names():
|
| 668 |
+
"""The names of the loop's state tensors, in order."""
|
| 669 |
+
return ("coef", "logi", "lam", "phi", "grad", "diag", "worst", *[f"H{k}" for k in range(K)],
|
| 670 |
+
*[f"J{i}" for i in range(len(TAB.xspans))], "coef_t", "logi_t", "predicted")
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
def prepare(r_cos, z_sin, target, start_x, start_y, start_z, start_current):
|
| 674 |
+
"""From the instance and the first guess: the geometry, the loop's starting state (names()'s tensors, the first
|
| 675 |
+
guess as the trial and nothing kept yet), the circles with their currents, and whether the circles pass."""
|
| 676 |
+
g = geometry(r_cos, z_sin, target)
|
| 677 |
+
g["cur0"] = start_current
|
| 678 |
+
coef = S.stack([start_x, start_y, start_z], 1)
|
| 679 |
+
logi = torch.zeros(K, dtype=F, device=DEVICE)
|
| 680 |
+
state = (coef, logi, scalar(LAMBDA0), scalar(1e30), zeros(N, 1), zeros(N, 1), scalar(0.0), *[zeros(3 * NM, 3 * NM) for _ in range(K)],
|
| 681 |
+
*[zeros(b - a, N) for a, b in TAB.xspans], coef, logi, scalar(1.0))
|
| 682 |
+
ring, ring_current, radius, c2p = circles(g, target)
|
| 683 |
+
ring_ok = circles_pass(ring, ring_current, radius, c2p, g, target)
|
| 684 |
+
return g, state, ring, ring_current, ring_ok
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def step(i, coef, logi, lam, phi, grad, diag, worst, *rest, g):
|
| 688 |
+
"""Pass number i (an integer tensor) of the loop on its state: the trial coilset is evaluated and kept if the
|
| 689 |
+
objective fell, lambda follows the ratio of the actual to the predicted drop, and the next trial is solved for.
|
| 690 |
+
Returns whether another pass is wanted (always) and the new state."""
|
| 691 |
+
count = len(TAB.xspans)
|
| 692 |
+
blocks, Jh, (coef_t, logi_t, predicted) = rest[:K], rest[K:K + count], rest[K + count:]
|
| 693 |
+
judged = S.clamp(i.to(F) - 1.0, min=0.0) # trials judged before this one
|
| 694 |
+
eps = EPS0 * S.power(EPS1 / EPS0, judged / float(max(ITERS - 1, 1)))
|
| 695 |
+
phi_t, grad_t, diag_t, worst_t, blocks_t, Jh_t = evaluate(coef_t, logi_t, g, eps)
|
| 696 |
+
take = phi_t < phi
|
| 697 |
+
ratio = (phi - phi_t) / S.clamp(predicted, min=1e-30)
|
| 698 |
+
moved = S.clamp(S.where(ratio > RATIO_HI, lam * LAMBDA_DOWN, S.where(ratio > RATIO_LO, lam, lam * LAMBDA_UP)), min=LAMBDA_MIN, max=LAMBDA_MAX)
|
| 699 |
+
lam = S.where(i < 1, lam, moved) # the first pass judges no step
|
| 700 |
+
pick = lambda new, old: S.where(take, new, old) # noqa: E731
|
| 701 |
+
coef, logi, phi, grad, diag, worst = (pick(coef_t, coef), pick(logi_t, logi), pick(phi_t, phi), pick(grad_t, grad), pick(diag_t, diag),
|
| 702 |
+
pick(worst_t, worst))
|
| 703 |
+
blocks = [pick(new, old) for new, old in zip(blocks_t, blocks)]
|
| 704 |
+
Jh = [pick(new, old) for new, old in zip(Jh_t, Jh)]
|
| 705 |
+
delta = solve(grad, diag, blocks, Jh, lam)
|
| 706 |
+
d_coef, d_logi = S.split(delta, [NPAR, K], 0)
|
| 707 |
+
shift = mm(d_coef.reshape(3 * K, NM), TAB.B0c) # (3 K, P_GC): each coil point's displacement by axis
|
| 708 |
+
reach = (shift * shift).reshape(K, 3, P_GC).sum(1).max().sqrt()
|
| 709 |
+
scale = S.clamp(STEP_MAX / S.clamp(reach, min=1e-9), max=1.0)
|
| 710 |
+
delta, d_coef, d_logi = delta * scale, d_coef * scale, d_logi * scale
|
| 711 |
+
predicted = -(2.0 * (grad * delta).sum() + (delta * gauss_newton(delta, blocks, Jh)).sum())
|
| 712 |
+
return (S.true(), coef, logi, lam, phi, grad, diag, worst, *blocks, *Jh, coef + d_coef.reshape(K, 3, NM), logi + d_logi.reshape(K), predicted)
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
def finish(coef, logi, cur0, ring, ring_current, ring_ok):
|
| 716 |
+
"""The output coilset: the circles when they pass or the optimized coilset is not sound, else the optimized one."""
|
| 717 |
+
current = cur0 * S.exp(logi)
|
| 718 |
+
sane = (coef.abs() < 1e3).all() & (current.abs() < 1e12).all() # false for a value that is not a number, too
|
| 719 |
+
use_ring = ring_ok | ~sane
|
| 720 |
+
out = S.where(use_ring, ring, coef)
|
| 721 |
+
return out[:, 0], out[:, 1], out[:, 2], S.where(use_ring, ring_current, current), current, use_ring
|
| 722 |
|
| 723 |
|
| 724 |
def model(r_cos, z_sin, target, start_x, start_y, start_z, start_current, details=False, trace=None):
|
| 725 |
+
"""The whole model, eagerly: inputs are the boundary (5, 9), the targets (4,), the first guess (K, NM) per axis
|
| 726 |
+
and its currents."""
|
| 727 |
+
g, state, ring, ring_current, ring_ok = prepare(r_cos, z_sin, target, start_x, start_y, start_z, start_current)
|
| 728 |
+
passes = 0
|
| 729 |
+
if not bool(ring_ok):
|
| 730 |
+
for i in range(ITERS + 1):
|
| 731 |
+
state = step(torch.as_tensor(i), *state, g=g)[1:]
|
| 732 |
+
passes = i + 1
|
| 733 |
+
if trace is not None:
|
| 734 |
+
trace.append((float(state[3]), float(state[6]), float(state[2])))
|
| 735 |
+
x, y, z, current, own_current, use_ring = finish(state[0], state[1], start_current, ring, ring_current, ring_ok)
|
| 736 |
if details:
|
| 737 |
+
return state[0], own_current, ring, ring_current, ring_ok, use_ring, max(passes - 1, 0)
|
| 738 |
+
return x, y, z, current
|
| 739 |
|
| 740 |
|
| 741 |
def ask(target):
|
|
|
|
| 744 |
return np.minimum(np.maximum(np.asarray(target, float) * scale, lo), hi)
|
| 745 |
|
| 746 |
|
| 747 |
+
def first_guess(sess, r_cos, z_sin, target, nfp, k):
|
| 748 |
return sess.run(["coil_x_n", "coil_y_n", "coil_z_n", "currents"], {
|
| 749 |
"boundary_r_cos": r_cos.astype(np.float32), "boundary_z_sin": z_sin.astype(np.float32),
|
| 750 |
"requirement_metrics": ask(target).astype(np.float32),
|
| 751 |
+
"n_field_periods": np.asarray(nfp, np.int64), "n_coils_per_half_period": np.asarray(k, np.int64)})
|
| 752 |
|
| 753 |
|
| 754 |
+
def dev_rows(table, n, track="fixed_shape", strata=("loose", "medium", "tight")):
|
| 755 |
import instances
|
| 756 |
rows, stratum = [], []
|
| 757 |
for s in strata:
|
| 758 |
+
order = instances.benchmark_order(table, track, s, "dev")
|
| 759 |
order = order[np.unique(np.linspace(0, len(order) - 1, n).astype(int))]
|
| 760 |
rows += order.tolist()
|
| 761 |
stratum += [s] * len(order)
|
| 762 |
return np.array(rows), np.array(stratum)
|
| 763 |
|
| 764 |
|
| 765 |
+
def run_rows(rows, device, dtype, table, bnd, sess):
|
| 766 |
+
"""The model on dev rows: per row the optimized, circle and chosen coilsets, whether the circles passed their
|
| 767 |
+
check and were used, and the steps taken."""
|
| 768 |
+
bindex = getattr(run_rows, "bindex", None)
|
| 769 |
+
if bindex is None:
|
| 770 |
+
bindex = run_rows.bindex = {b: i for i, b in enumerate(bnd["boundary_id"].tolist())}
|
| 771 |
+
unpack = lambda c, i_: tuple(c[:, a].double().cpu().numpy() for a in range(3)) + (i_.double().cpu().numpy(),) # noqa: E731
|
| 772 |
+
out = []
|
| 773 |
+
for i in rows:
|
| 774 |
+
b = bindex[str(table["boundary_id"][i])]
|
| 775 |
+
nfp, k, tgt = int(table["nfp"][i]), int(table["n_coils"][i]), table["target"][i]
|
| 776 |
+
guess = first_guess(sess, bnd["r_cos"][b], bnd["z_sin"][b], tgt, nfp, k)
|
| 777 |
+
configure(nfp, k, device, dtype)
|
| 778 |
+
with torch.no_grad():
|
| 779 |
+
coef, cur, ring, ring_cur, ring_ok, use_ring, steps = model(_t(bnd["r_cos"][b]), _t(bnd["z_sin"][b]), _t(tgt), *[_t(o) for o in guess],
|
| 780 |
+
details=True)
|
| 781 |
+
sets = dict(optimized=unpack(coef, cur), circles=unpack(ring, ring_cur))
|
| 782 |
+
sets["chosen"] = sets["circles"] if bool(use_ring) else sets["optimized"]
|
| 783 |
+
out.append(dict(sets=sets, ring_ok=bool(ring_ok), use_ring=bool(use_ring), steps=steps))
|
| 784 |
+
return out
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
def attempt(n, tag, track, strata, device, dtype):
|
| 788 |
import onnxruntime as ort
|
| 789 |
import queue_io
|
| 790 |
sess = ort.InferenceSession(str(BASE), providers=["CPUExecutionProvider"])
|
| 791 |
table, bnd = queue_io.instances(), queue_io.boundaries()
|
| 792 |
+
rows, stratum = dev_rows(table, n, track, strata)
|
| 793 |
+
t0 = time.time()
|
| 794 |
+
results = run_rows(rows, device, dtype, table, bnd, sess)
|
| 795 |
+
took = time.time() - t0
|
| 796 |
+
steps = np.array([r["steps"] for r in results])
|
| 797 |
+
ring_ok = np.array([r["ring_ok"] for r in results])
|
| 798 |
+
print(f"{len(rows)} instances in {took:.0f}s ({took / len(rows):.2f}s each); steps taken: mean {steps.mean():.1f}, none {np.mean(steps == 0):.2f}", flush=True)
|
| 799 |
+
names_ = {k: f"0b_lm_{k}_{tag}" for k in ("circles", "chosen")}
|
| 800 |
+
for k, name in names_.items():
|
| 801 |
+
queue_io.submit(name, table["instance"][rows].tolist(), [r["sets"][k] for r in results], {"kind": "lm", "set": k})
|
| 802 |
+
queue_io.wait(list(names_.values()), poll=3)
|
| 803 |
+
res = {k: queue_io.load(name) for k, name in names_.items()}
|
| 804 |
+
print(f"{'set':9s} {'stratum':7s} {'n':>4s} {'strict':>7s} {'mean':>7s} | misses: c2c c2p curv ferr | circles judged passing, of which strict")
|
| 805 |
+
for k in names_:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 806 |
miss = res[k]["violation"] > 1e-3
|
| 807 |
for s in strata:
|
| 808 |
m = stratum == s
|
|
|
|
| 809 |
print(f"{k:9s} {s:7s} {int(m.sum()):4d} {res[k]['strict'][m].mean():7.4f} {np.nanmean(res[k]['score'][m]):7.4f} |"
|
| 810 |
+
f" " + " ".join(f"{miss[m][:, j].mean():6.3f}" for j in range(4))
|
| 811 |
+
+ f" | {int(ring_ok[m].sum()):4d} {int((ring_ok & res['circles']['strict'])[m].sum()):4d}")
|
| 812 |
+
weight = {"loose": 0.37, "medium": 0.31, "tight": 0.32} if track == "fixed_shape" else {"loose": 0.335, "medium": 0.33, "tight": 0.335}
|
| 813 |
+
print("chosen, weighted by the eval set's strata: strict %.3f mean %.3f" % (
|
| 814 |
+
sum(weight[s] * res["chosen"]["strict"][stratum == s].mean() for s in strata),
|
| 815 |
+
sum(weight[s] * np.nanmean(res["chosen"]["score"][stratum == s]) for s in strata)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 816 |
|
| 817 |
|
| 818 |
if __name__ == "__main__":
|
| 819 |
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 820 |
+
argv, device, strata, dtype, track = sys.argv[1:], "cpu", ("loose", "medium", "tight"), torch.float32, "fixed_shape"
|
| 821 |
while "--set" in argv:
|
| 822 |
j = argv.index("--set")
|
| 823 |
name, value = argv[j + 1].split("=")
|
| 824 |
globals()[name] = type(globals()[name])(value)
|
| 825 |
del argv[j:j + 2]
|
| 826 |
+
for flag in ("--device", "--strata", "--track"):
|
| 827 |
+
if flag in argv:
|
| 828 |
+
j = argv.index(flag)
|
| 829 |
+
if flag == "--device":
|
| 830 |
+
device = argv[j + 1]
|
| 831 |
+
elif flag == "--strata":
|
| 832 |
+
strata = tuple(argv[j + 1].split(","))
|
| 833 |
+
else:
|
| 834 |
+
track = argv[j + 1]
|
| 835 |
+
del argv[j:j + 2]
|
| 836 |
if "--double" in argv:
|
| 837 |
argv.remove("--double")
|
| 838 |
dtype = torch.float64
|
| 839 |
+
attempt(int(argv[1]), argv[2], track, strata, device, dtype)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model.onnx
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:82e22bee721b28f06fca48f7db3b77ef4d1254456f0b3aa86e55a619bacdd403
|
| 3 |
+
size 18269215
|
sym.py
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tensors that record ONNX nodes.
|
| 2 |
+
|
| 3 |
+
A Sym stands for a tensor of known shape in a graph being written. Arithmetic, indexing and the functions of this
|
| 4 |
+
module append nodes to the current Graph when given Syms and compute in PyTorch when given tensors, so one piece of
|
| 5 |
+
numerical code both runs eagerly and writes its own ONNX graph. Every node is held to the sizes at which
|
| 6 |
+
onnxruntime 1.31 runs an operation in the calling thread: a matrix product below 65,536 in rows x columns x inner
|
| 7 |
+
size, an element-wise operation, concatenation or selection on at most EL_LIMIT values, a reduction over some of
|
| 8 |
+
the axes on at most RED_LIMIT values, a gather of at most GATHER_LIMIT values. Transpose and Clip are never
|
| 9 |
+
written: onnxruntime threads a Transpose of any size and a Clip over more than 16,384 values.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import collections
|
| 14 |
+
import contextlib
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from onnx import TensorProto, helper, numpy_helper
|
| 19 |
+
|
| 20 |
+
MM_LIMIT, EL_LIMIT, RED_LIMIT, GATHER_LIMIT = 65000, 50000, 8000, 30000
|
| 21 |
+
ONNX_TYPE = {np.dtype(np.float32): TensorProto.FLOAT, np.dtype(np.int64): TensorProto.INT64, np.dtype(np.bool_): TensorProto.BOOL}
|
| 22 |
+
G = None # the graph being written
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Graph:
|
| 26 |
+
"""Nodes and constants of one ONNX graph; equal constants are stored once."""
|
| 27 |
+
|
| 28 |
+
def __init__(self, tag):
|
| 29 |
+
self.tag, self.nodes, self.inits, self.pool, self.count = tag, [], [], {}, 0
|
| 30 |
+
|
| 31 |
+
def fresh(self):
|
| 32 |
+
self.count += 1
|
| 33 |
+
return f"{self.tag}{self.count}"
|
| 34 |
+
|
| 35 |
+
def const(self, value, dtype=None):
|
| 36 |
+
a = np.asarray(value, dtype)
|
| 37 |
+
if a.ndim: # ascontiguousarray would give a scalar one dimension
|
| 38 |
+
a = np.ascontiguousarray(a)
|
| 39 |
+
key = (a.dtype.str, a.shape, a.tobytes())
|
| 40 |
+
if key not in self.pool:
|
| 41 |
+
name = self.fresh()
|
| 42 |
+
self.inits.append(numpy_helper.from_array(a, name))
|
| 43 |
+
self.pool[key] = name
|
| 44 |
+
return self.pool[key]
|
| 45 |
+
|
| 46 |
+
def emit(self, op, inputs, shape, dtype=np.float32, **attrs):
|
| 47 |
+
name = self.fresh()
|
| 48 |
+
self.nodes.append(helper.make_node(op, list(inputs), [name], **attrs))
|
| 49 |
+
return Sym(name, shape, dtype)
|
| 50 |
+
|
| 51 |
+
def operations(self):
|
| 52 |
+
return collections.Counter(node.op_type for node in self.nodes)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@contextlib.contextmanager
|
| 56 |
+
def use(graph):
|
| 57 |
+
"""Write into `graph` inside the block."""
|
| 58 |
+
global G
|
| 59 |
+
previous, G = G, graph
|
| 60 |
+
try:
|
| 61 |
+
yield graph
|
| 62 |
+
finally:
|
| 63 |
+
G = previous
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def info(name, shape, dtype=np.float32):
|
| 67 |
+
return helper.make_tensor_value_info(name, ONNX_TYPE[np.dtype(dtype)], list(shape))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _array(v):
|
| 71 |
+
if isinstance(v, torch.Tensor):
|
| 72 |
+
v = v.detach().cpu().numpy()
|
| 73 |
+
a = np.asarray(v)
|
| 74 |
+
if a.dtype == np.float64:
|
| 75 |
+
a = a.astype(np.float32)
|
| 76 |
+
elif a.dtype.kind == "i" and a.dtype != np.int64:
|
| 77 |
+
a = a.astype(np.int64)
|
| 78 |
+
return a
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def lift(v, like=np.float32):
|
| 82 |
+
"""An operand as a Sym: a Sym as it is, a number as a constant of the other operand's type, a tensor as a constant."""
|
| 83 |
+
if isinstance(v, Sym):
|
| 84 |
+
return v
|
| 85 |
+
if isinstance(v, (bool, np.bool_)):
|
| 86 |
+
a = np.asarray(v, np.bool_)
|
| 87 |
+
elif isinstance(v, (int, float, np.integer, np.floating)):
|
| 88 |
+
a = np.asarray(v, like)
|
| 89 |
+
else:
|
| 90 |
+
a = _array(v)
|
| 91 |
+
return Sym(G.const(a), a.shape, a.dtype)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _held(op, shape, limit):
|
| 95 |
+
size = int(np.prod(shape, dtype=np.int64))
|
| 96 |
+
assert size <= limit, f"{op} on {tuple(shape)}: {size} values, over the {limit} onnxruntime keeps in the calling thread"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _binary(op, a, b, dtype=None):
|
| 100 |
+
if isinstance(a, Sym):
|
| 101 |
+
b = lift(b, a.dtype)
|
| 102 |
+
else:
|
| 103 |
+
a = lift(a, b.dtype)
|
| 104 |
+
shape = tuple(np.broadcast_shapes(a.shape, b.shape))
|
| 105 |
+
_held(op, shape, EL_LIMIT)
|
| 106 |
+
return G.emit(op, [a.name, b.name], shape, dtype or a.dtype)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class Sym:
|
| 110 |
+
"""A tensor of the graph being written: its name, its shape and its element type."""
|
| 111 |
+
|
| 112 |
+
__slots__ = ("name", "shape", "dtype")
|
| 113 |
+
__array_ufunc__ = None # numpy scalars and arrays defer to the reflected methods
|
| 114 |
+
device = "cpu"
|
| 115 |
+
|
| 116 |
+
def __init__(self, name, shape, dtype=np.float32):
|
| 117 |
+
self.name, self.shape, self.dtype = name, tuple(int(s) for s in shape), np.dtype(dtype)
|
| 118 |
+
|
| 119 |
+
def __bool__(self):
|
| 120 |
+
raise TypeError("a Sym has no truth value while its graph is being written")
|
| 121 |
+
|
| 122 |
+
def dim(self):
|
| 123 |
+
return len(self.shape)
|
| 124 |
+
|
| 125 |
+
def numel(self):
|
| 126 |
+
return int(np.prod(self.shape, dtype=np.int64))
|
| 127 |
+
|
| 128 |
+
def _unary(self, op, dtype=None):
|
| 129 |
+
_held(op, self.shape, EL_LIMIT)
|
| 130 |
+
return G.emit(op, [self.name], self.shape, dtype or self.dtype)
|
| 131 |
+
|
| 132 |
+
def __add__(self, o):
|
| 133 |
+
return _binary("Add", self, o)
|
| 134 |
+
|
| 135 |
+
def __radd__(self, o):
|
| 136 |
+
return _binary("Add", o, self)
|
| 137 |
+
|
| 138 |
+
def __sub__(self, o):
|
| 139 |
+
return _binary("Sub", self, o)
|
| 140 |
+
|
| 141 |
+
def __rsub__(self, o):
|
| 142 |
+
return _binary("Sub", o, self)
|
| 143 |
+
|
| 144 |
+
def __mul__(self, o):
|
| 145 |
+
return _binary("Mul", self, o)
|
| 146 |
+
|
| 147 |
+
def __rmul__(self, o):
|
| 148 |
+
return _binary("Mul", o, self)
|
| 149 |
+
|
| 150 |
+
def __truediv__(self, o):
|
| 151 |
+
return _binary("Div", self, o)
|
| 152 |
+
|
| 153 |
+
def __rtruediv__(self, o):
|
| 154 |
+
if isinstance(o, (int, float)) and o == 1:
|
| 155 |
+
return self._unary("Reciprocal")
|
| 156 |
+
return _binary("Div", o, self)
|
| 157 |
+
|
| 158 |
+
def __neg__(self):
|
| 159 |
+
return self._unary("Neg")
|
| 160 |
+
|
| 161 |
+
def __lt__(self, o):
|
| 162 |
+
return _binary("Less", self, o, np.bool_)
|
| 163 |
+
|
| 164 |
+
def __le__(self, o):
|
| 165 |
+
return _binary("LessOrEqual", self, o, np.bool_)
|
| 166 |
+
|
| 167 |
+
def __gt__(self, o):
|
| 168 |
+
return _binary("Greater", self, o, np.bool_)
|
| 169 |
+
|
| 170 |
+
def __ge__(self, o):
|
| 171 |
+
return _binary("GreaterOrEqual", self, o, np.bool_)
|
| 172 |
+
|
| 173 |
+
def __and__(self, o):
|
| 174 |
+
return _binary("And", self, o)
|
| 175 |
+
|
| 176 |
+
def __or__(self, o):
|
| 177 |
+
return _binary("Or", self, o)
|
| 178 |
+
|
| 179 |
+
def __invert__(self):
|
| 180 |
+
return self._unary("Not")
|
| 181 |
+
|
| 182 |
+
def abs(self):
|
| 183 |
+
return self._unary("Abs")
|
| 184 |
+
|
| 185 |
+
def sqrt(self):
|
| 186 |
+
return self._unary("Sqrt")
|
| 187 |
+
|
| 188 |
+
def to(self, dtype):
|
| 189 |
+
target = np.dtype({torch.float32: np.float32, torch.float64: np.float32, torch.int64: np.int64, torch.bool: np.bool_}.get(dtype, dtype))
|
| 190 |
+
if target == self.dtype:
|
| 191 |
+
return self
|
| 192 |
+
return G.emit("Cast", [self.name], self.shape, target, to=ONNX_TYPE[target])
|
| 193 |
+
|
| 194 |
+
def reshape(self, *shape):
|
| 195 |
+
shape = list(shape[0]) if len(shape) == 1 and isinstance(shape[0], (tuple, list)) else list(shape)
|
| 196 |
+
size = self.numel()
|
| 197 |
+
if -1 in shape:
|
| 198 |
+
known = int(np.prod([s for s in shape if s != -1], dtype=np.int64))
|
| 199 |
+
shape[shape.index(-1)] = size // known
|
| 200 |
+
assert int(np.prod(shape, dtype=np.int64)) == size, (self.shape, shape)
|
| 201 |
+
if tuple(shape) == self.shape:
|
| 202 |
+
return self
|
| 203 |
+
return G.emit("Reshape", [self.name, G.const(shape, np.int64)], shape, self.dtype)
|
| 204 |
+
|
| 205 |
+
def expand(self, *shape):
|
| 206 |
+
shape = tuple(np.broadcast_shapes(self.shape, tuple(shape)))
|
| 207 |
+
_held("Expand", shape, EL_LIMIT)
|
| 208 |
+
return G.emit("Expand", [self.name, G.const(shape, np.int64)], shape, self.dtype)
|
| 209 |
+
|
| 210 |
+
def __getitem__(self, index):
|
| 211 |
+
index = index if isinstance(index, tuple) else (index,)
|
| 212 |
+
starts, ends, axes, steps, whole, final, picked, axis = [], [], [], [], list(self.shape), [], [], 0
|
| 213 |
+
for item in index:
|
| 214 |
+
if item is None:
|
| 215 |
+
final.append(1)
|
| 216 |
+
continue
|
| 217 |
+
size = self.shape[axis]
|
| 218 |
+
if isinstance(item, (int, np.integer)):
|
| 219 |
+
i = int(item) + (size if item < 0 else 0)
|
| 220 |
+
assert 0 <= i < size, (self.shape, index)
|
| 221 |
+
picked.append((axis, i))
|
| 222 |
+
starts.append(i), ends.append(i + 1), axes.append(axis), steps.append(1)
|
| 223 |
+
whole[axis] = 1
|
| 224 |
+
else:
|
| 225 |
+
a, b, s = item.indices(size)
|
| 226 |
+
assert s > 0, "a slice runs forwards"
|
| 227 |
+
n = max(0, (b - a + s - 1) // s)
|
| 228 |
+
if (a, n, s) != (0, size, 1):
|
| 229 |
+
starts.append(a), ends.append(b), axes.append(axis), steps.append(s)
|
| 230 |
+
whole[axis] = n
|
| 231 |
+
final.append(n)
|
| 232 |
+
axis += 1
|
| 233 |
+
final += list(self.shape[axis:])
|
| 234 |
+
x = self
|
| 235 |
+
if len(picked) == 1 and len(starts) == 1: # one position along one axis: a Gather drops the axis
|
| 236 |
+
a, i = picked[0]
|
| 237 |
+
x = G.emit("Gather", [x.name, G.const(i, np.int64)], self.shape[:a] + self.shape[a + 1:], self.dtype, axis=a)
|
| 238 |
+
elif starts:
|
| 239 |
+
inputs = [x.name, G.const(starts, np.int64), G.const(ends, np.int64), G.const(axes, np.int64)]
|
| 240 |
+
if any(s != 1 for s in steps):
|
| 241 |
+
inputs.append(G.const(steps, np.int64))
|
| 242 |
+
x = G.emit("Slice", inputs, whole, self.dtype)
|
| 243 |
+
return x.reshape(final)
|
| 244 |
+
|
| 245 |
+
def _reduce(self, op, dim):
|
| 246 |
+
if dim is None:
|
| 247 |
+
return G.emit(op, [self.name], (), self.dtype, keepdims=0)
|
| 248 |
+
axis = dim % len(self.shape)
|
| 249 |
+
_held(op, self.shape, RED_LIMIT)
|
| 250 |
+
return G.emit(op, [self.name, G.const([axis], np.int64)], self.shape[:axis] + self.shape[axis + 1:], self.dtype, keepdims=0)
|
| 251 |
+
|
| 252 |
+
def sum(self, dim=None):
|
| 253 |
+
return self._reduce("ReduceSum", dim)
|
| 254 |
+
|
| 255 |
+
def mean(self, dim=None):
|
| 256 |
+
return self._reduce("ReduceMean", dim)
|
| 257 |
+
|
| 258 |
+
def max(self):
|
| 259 |
+
return self._reduce("ReduceMax", None)
|
| 260 |
+
|
| 261 |
+
def min(self):
|
| 262 |
+
return self._reduce("ReduceMin", None)
|
| 263 |
+
|
| 264 |
+
def all(self):
|
| 265 |
+
return self.to(np.float32).min() > 0.5
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def is_sym(*values):
|
| 269 |
+
return any(isinstance(v, Sym) for v in values)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def matmul(a, b):
|
| 273 |
+
"""A two-dimensional matrix product."""
|
| 274 |
+
if not is_sym(a, b):
|
| 275 |
+
return torch.matmul(a, b)
|
| 276 |
+
a, b = lift(a), lift(b)
|
| 277 |
+
assert len(a.shape) == 2 and len(b.shape) == 2 and a.shape[1] == b.shape[0], (a.shape, b.shape)
|
| 278 |
+
work = a.shape[0] * a.shape[1] * b.shape[1]
|
| 279 |
+
assert work <= MM_LIMIT, f"MatMul {a.shape} @ {b.shape}: {work}, over the {MM_LIMIT} onnxruntime keeps in the calling thread"
|
| 280 |
+
return G.emit("MatMul", [a.name, b.name], (a.shape[0], b.shape[1]), a.dtype)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def cat(parts, dim=0):
|
| 284 |
+
parts = list(parts)
|
| 285 |
+
if not is_sym(*parts):
|
| 286 |
+
return torch.cat(parts, dim)
|
| 287 |
+
parts = [lift(p) for p in parts]
|
| 288 |
+
if len(parts) == 1:
|
| 289 |
+
return parts[0]
|
| 290 |
+
axis = dim % len(parts[0].shape)
|
| 291 |
+
shape = list(parts[0].shape)
|
| 292 |
+
shape[axis] = sum(p.shape[axis] for p in parts)
|
| 293 |
+
for p in parts:
|
| 294 |
+
assert p.shape[:axis] + p.shape[axis + 1:] == parts[0].shape[:axis] + parts[0].shape[axis + 1:], [q.shape for q in parts]
|
| 295 |
+
_held("Concat", p.shape, EL_LIMIT)
|
| 296 |
+
return G.emit("Concat", [p.name for p in parts], shape, parts[0].dtype, axis=axis)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def stack(parts, dim=0):
|
| 300 |
+
parts = list(parts)
|
| 301 |
+
if not is_sym(*parts):
|
| 302 |
+
return torch.stack(parts, dim)
|
| 303 |
+
parts = [lift(p) for p in parts]
|
| 304 |
+
shape = parts[0].shape
|
| 305 |
+
axis = dim % (len(shape) + 1)
|
| 306 |
+
if axis == 0 and shape:
|
| 307 |
+
return cat(parts, 0).reshape((len(parts),) + shape)
|
| 308 |
+
return cat([p.reshape(shape[:axis] + (1,) + shape[axis:]) for p in parts], axis)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def split(x, size, dim=0):
|
| 312 |
+
"""Consecutive pieces of x along dim, `size` long each; a list gives each piece's length."""
|
| 313 |
+
axis = dim % len(x.shape)
|
| 314 |
+
n = x.shape[axis]
|
| 315 |
+
sizes = list(size) if isinstance(size, (list, tuple)) else [size] * (n // size) + ([n % size] if n % size else [])
|
| 316 |
+
assert sum(sizes) == n, (x.shape, sizes)
|
| 317 |
+
if not isinstance(x, Sym):
|
| 318 |
+
return list(torch.split(x, sizes, axis))
|
| 319 |
+
if len(sizes) == 1:
|
| 320 |
+
return [x]
|
| 321 |
+
names = [G.fresh() for _ in sizes]
|
| 322 |
+
G.nodes.append(helper.make_node("Split", [x.name, G.const(sizes, np.int64)], names, axis=axis))
|
| 323 |
+
return [Sym(name, x.shape[:axis] + (s,) + x.shape[axis + 1:], x.dtype) for name, s in zip(names, sizes)]
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def take(x, index, dim):
|
| 327 |
+
"""x at a constant list of positions along dim."""
|
| 328 |
+
index = np.asarray(index, np.int64)
|
| 329 |
+
if not isinstance(x, Sym):
|
| 330 |
+
return x.index_select(dim, torch.as_tensor(index, device=x.device))
|
| 331 |
+
axis = dim % len(x.shape)
|
| 332 |
+
shape = x.shape[:axis] + (len(index),) + x.shape[axis + 1:]
|
| 333 |
+
_held("Gather", shape, GATHER_LIMIT)
|
| 334 |
+
return G.emit("Gather", [x.name, G.const(index)], shape, x.dtype, axis=axis)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def tr(x):
|
| 338 |
+
"""The transpose of a matrix; in a graph, a gather on its flattened values."""
|
| 339 |
+
if not isinstance(x, Sym):
|
| 340 |
+
return x.transpose(0, 1)
|
| 341 |
+
m, n = x.shape
|
| 342 |
+
return take(x.reshape(m * n), np.arange(m * n).reshape(m, n).T.reshape(-1), 0).reshape(n, m)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def where(c, a, b):
|
| 346 |
+
if not is_sym(c, a, b):
|
| 347 |
+
return torch.where(c, a, b)
|
| 348 |
+
like = a.dtype if isinstance(a, Sym) else b.dtype if isinstance(b, Sym) else np.float32
|
| 349 |
+
c, a, b = lift(c), lift(a, like), lift(b, like)
|
| 350 |
+
shape = tuple(np.broadcast_shapes(c.shape, a.shape, b.shape))
|
| 351 |
+
_held("Where", shape, EL_LIMIT)
|
| 352 |
+
return G.emit("Where", [c.name, a.name, b.name], shape, a.dtype)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def maximum(a, b):
|
| 356 |
+
return _binary("Max", a, b) if is_sym(a, b) else torch.maximum(a, b)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def minimum(a, b):
|
| 360 |
+
return _binary("Min", a, b) if is_sym(a, b) else torch.minimum(a, b)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def clamp(x, min=None, max=None):
|
| 364 |
+
"""x held between two numbers, as a Max and a Min."""
|
| 365 |
+
if not isinstance(x, Sym):
|
| 366 |
+
return torch.clamp(x, min=min, max=max)
|
| 367 |
+
if min is not None:
|
| 368 |
+
x = _binary("Max", x, min)
|
| 369 |
+
if max is not None:
|
| 370 |
+
x = _binary("Min", x, max)
|
| 371 |
+
return x
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def exp(x):
|
| 375 |
+
return x._unary("Exp") if isinstance(x, Sym) else torch.exp(x)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def power(base, x):
|
| 379 |
+
"""A number to the power x."""
|
| 380 |
+
if isinstance(x, Sym):
|
| 381 |
+
return _binary("Pow", base, x)
|
| 382 |
+
return torch.pow(torch.as_tensor(base, dtype=x.dtype, device=x.device), x)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def true():
|
| 386 |
+
"""The constant true: a node's output in a graph, so that it may be a loop body's output."""
|
| 387 |
+
if G is None:
|
| 388 |
+
return torch.ones((), dtype=torch.bool)
|
| 389 |
+
return G.emit("Identity", [G.const(True, np.bool_)], (), np.bool_)
|
wrap.py
CHANGED
|
@@ -1,176 +1,227 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
the
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
-
import
|
| 11 |
import time
|
| 12 |
from pathlib import Path
|
| 13 |
|
| 14 |
import numpy as np
|
| 15 |
import torch
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
bindex = {b: i for i, b in enumerate(bnd["boundary_id"].tolist())}
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
return out
|
| 51 |
|
| 52 |
|
| 53 |
-
def
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
import onnx
|
| 61 |
import onnxruntime as ort
|
|
|
|
| 62 |
from onnx import TensorProto, compose, helper, numpy_helper
|
| 63 |
-
|
| 64 |
-
cases = feeds(mod, n_check)
|
| 65 |
-
base_sess = ort.InferenceSession(str(mod.BASE), providers=["CPUExecutionProvider"])
|
| 66 |
-
_, r_cos, z_sin, tgt = cases[0]
|
| 67 |
-
example = (mod._t(r_cos), mod._t(z_sin), mod._t(tgt), *[mod._t(o) for o in mod.first_guess(base_sess, r_cos, z_sin, tgt)])
|
| 68 |
-
|
| 69 |
-
def core_fn(r_cos, z_sin, target, start_x, start_y, start_z, start_current):
|
| 70 |
-
return mod.model(r_cos, z_sin, target, start_x, start_y, start_z, start_current)
|
| 71 |
-
|
| 72 |
-
t0 = time.time()
|
| 73 |
-
with torch.no_grad():
|
| 74 |
-
gm = make_fx(core_fn)(*example)
|
| 75 |
-
print(f"traced: {len(gm.graph.nodes)} nodes [{time.time() - t0:.0f}s]", flush=True)
|
| 76 |
-
prog = torch.onnx.export(gm, example, dynamo=True, opset_version=20, input_names=CORE_IN, output_names=CORE_OUT, verbose=False)
|
| 77 |
-
core = prog.model_proto
|
| 78 |
-
removed = dedupe(core.graph)
|
| 79 |
-
big = sorted(((int(np.prod(t.dims)), t.name) for t in core.graph.initializer), reverse=True)[:5]
|
| 80 |
-
print(f"exported: {len(core.graph.node)} nodes, opsets {[(o.domain, o.version) for o in core.opset_import]}, {len(core.functions)} functions, "
|
| 81 |
-
f"{removed} duplicate constants merged, {sum(int(np.prod(t.dims)) for t in core.graph.initializer)} constant values, largest {big}, "
|
| 82 |
-
f"ops {sorted({nd.op_type for nd in core.graph.node})} [{time.time() - t0:.0f}s]", flush=True)
|
| 83 |
-
base = compose.add_prefix(onnx.load(str(mod.BASE)), "fg/")
|
| 84 |
-
core = compose.add_prefix(core, "rp/")
|
| 85 |
f32, i64 = TensorProto.FLOAT, TensorProto.INT64
|
| 86 |
-
const = lambda name, v: numpy_helper.from_array(np.asarray(v,
|
| 87 |
wire = lambda a, b: helper.make_node("Identity", [a], [b]) # noqa: E731
|
| 88 |
-
|
| 89 |
# the request to the first-guess network: one transform of the targets, or one of two by the field-error target
|
| 90 |
-
switch =
|
| 91 |
-
scale, lo, hi =
|
| 92 |
nodes = [helper.make_node("Mul", ["requirement_metrics", "ask_scale"], ["ask_0"]),
|
| 93 |
helper.make_node("Max", ["ask_0", "ask_lo"], ["ask_1"]),
|
| 94 |
helper.make_node("Min", ["ask_1", "ask_hi"], ["ask_2" if switch else "fg/requirement_metrics"])]
|
| 95 |
-
|
| 96 |
if switch:
|
| 97 |
-
assert
|
| 98 |
nodes += [helper.make_node("Gather", ["requirement_metrics", "ask_index"], ["ask_field"], axis=0),
|
| 99 |
helper.make_node("Greater", ["ask_field", "ask_switch"], ["ask_high"]),
|
| 100 |
helper.make_node("Where", ["ask_high", "ask_2", "requirement_metrics"], ["fg/requirement_metrics"])]
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
graph = helper.make_graph(
|
| 112 |
nodes, "coilstellaration_optimizer",
|
| 113 |
[helper.make_tensor_value_info("boundary_r_cos", f32, [5, 9]), helper.make_tensor_value_info("boundary_z_sin", f32, [5, 9]),
|
| 114 |
helper.make_tensor_value_info("requirement_metrics", f32, [4]), helper.make_tensor_value_info("n_field_periods", i64, []),
|
| 115 |
helper.make_tensor_value_info("n_coils_per_half_period", i64, [])],
|
| 116 |
-
[helper.make_tensor_value_info(
|
| 117 |
-
helper.make_tensor_value_info("coil_z_n", f32, [k, nm]), helper.make_tensor_value_info("currents", f32, [k])],
|
| 118 |
-
[const("ask_scale", scale), const("ask_lo", lo), const("ask_hi", hi), *extra, *base.graph.initializer, *core.graph.initializer])
|
| 119 |
-
for node in graph.node: # the exporter records source paths on every node
|
| 120 |
-
node.doc_string = ""
|
| 121 |
-
del node.metadata_props[:]
|
| 122 |
final = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 20)], ir_version=10, producer_name="coilstellaration-optimizer")
|
| 123 |
-
|
| 124 |
-
final.metadata_props.append(onnx.StringStringEntryProto(key="supported_tracks", value=
|
| 125 |
-
onnx.checker.check_model(final, full_check=True)
|
| 126 |
onnx.save(final, out)
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
took.append(time.time() - t1)
|
| 134 |
-
with torch.no_grad():
|
| 135 |
-
want = mod.model(mod._t(r_cos), mod._t(z_sin), mod._t(tgt), *[mod._t(o) for o in mod.first_guess(base_sess, r_cos, z_sin, tgt)])
|
| 136 |
-
diff = max(float(np.abs(a - b.numpy()).max()) for a, b in zip(got[:3], want[:3]))
|
| 137 |
-
worst = max(worst, diff)
|
| 138 |
-
print(f"{name}: largest coefficient difference from PyTorch {diff:.2e} m, current {float(np.abs(got[3] / want[3].numpy() - 1).max()):.1e}, "
|
| 139 |
-
f"{took[-1]:.2f}s", flush=True)
|
| 140 |
-
print(f"largest difference {worst:.2e} m; seconds per instance {np.mean(took[1:]):.3f}")
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
def timing(mod, path, n=20, threads=0, profile=0):
|
| 144 |
-
import collections
|
| 145 |
-
import json
|
| 146 |
-
import os
|
| 147 |
-
import onnxruntime as ort
|
| 148 |
opts = ort.SessionOptions()
|
| 149 |
-
|
| 150 |
-
opts.intra_op_num_threads = threads
|
| 151 |
-
if profile:
|
| 152 |
-
opts.enable_profiling = True
|
| 153 |
-
opts.profile_file_prefix = str(Path(path).with_suffix("")) + "_prof"
|
| 154 |
t0 = time.time()
|
| 155 |
-
sess = ort.InferenceSession(
|
| 156 |
-
print(f"
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""lm's optimizer written to the benchmark's ONNX contract, for one or several (field periods, coils) shapes.
|
| 2 |
|
| 3 |
+
python wrap.py OUT.onnx [NFPxK ...] [--set NAME=VALUE ...] [--no-check] (3x5 alone by default; "all" is every shape of the dataset)
|
| 4 |
+
|
| 5 |
+
For each shape lm's prepare, step and finish run on sym.Sym tensors, which write their nodes directly, and are
|
| 6 |
+
joined as prepare -> Loop(step) -> finish, the loop taking no pass when the circles pass. With several shapes the
|
| 7 |
+
file holds one such branch per shape under nested If nodes on the two shape inputs; a shape without a branch gets
|
| 8 |
+
the first-guess network's coilset. The first-guess network is embedded ahead of the branches and asked with the
|
| 9 |
+
transformed targets, its matrix products cut into column chunks that onnxruntime runs in the calling thread.
|
| 10 |
"""
|
| 11 |
from __future__ import annotations
|
| 12 |
|
| 13 |
+
import sys
|
| 14 |
import time
|
| 15 |
from pathlib import Path
|
| 16 |
|
| 17 |
import numpy as np
|
| 18 |
import torch
|
| 19 |
|
| 20 |
+
HERE = Path(__file__).resolve().parent
|
| 21 |
+
sys.path[:0] = [str(HERE), str(HERE.parent), str(HERE.parent / "scorer")]
|
| 22 |
+
|
| 23 |
+
import lm # noqa: E402
|
| 24 |
+
import sym as S # noqa: E402
|
| 25 |
+
|
| 26 |
+
SHAPES = [(2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (3, 4), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8),
|
| 27 |
+
(5, 4), (5, 5), (5, 6), (5, 7)]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def split_gemms(model):
|
| 31 |
+
"""Each Gemm of the first-guess network whose product onnxruntime would thread, as products over chunks of the
|
| 32 |
+
weight's columns joined by a Concat."""
|
| 33 |
+
from onnx import helper, numpy_helper, shape_inference
|
| 34 |
+
inferred = shape_inference.infer_shapes(model)
|
| 35 |
+
rows = {vi.name: vi.type.tensor_type.shape.dim[0].dim_value for vi in [*inferred.graph.value_info, *inferred.graph.input]
|
| 36 |
+
if len(vi.type.tensor_type.shape.dim) == 2}
|
| 37 |
+
inits = {t.name: t for t in model.graph.initializer}
|
| 38 |
+
nodes, added, dropped, cut = [], [], set(), 0
|
| 39 |
+
for node in model.graph.node:
|
| 40 |
+
if node.op_type != "Gemm":
|
| 41 |
+
nodes.append(node)
|
| 42 |
+
continue
|
| 43 |
+
attrs = {a.name: helper.get_attribute_value(a) for a in node.attribute}
|
| 44 |
+
assert attrs.get("transA", 0) == 0 and attrs.get("transB", 0) == 0 and attrs.get("alpha", 1.0) == 1.0 and attrs.get("beta", 1.0) == 1.0
|
| 45 |
+
weight, bias = numpy_helper.to_array(inits[node.input[1]]), numpy_helper.to_array(inits[node.input[2]])
|
| 46 |
+
per = max(1, S.MM_LIMIT // (rows[node.input[0]] * weight.shape[0]))
|
| 47 |
+
if per >= weight.shape[1]:
|
| 48 |
+
nodes.append(node)
|
| 49 |
+
continue
|
| 50 |
+
parts = []
|
| 51 |
+
for a in range(0, weight.shape[1], per):
|
| 52 |
+
b = min(a + per, weight.shape[1])
|
| 53 |
+
names = [f"{node.output[0]}_w{a}", f"{node.output[0]}_b{a}", f"{node.output[0]}_p{a}"]
|
| 54 |
+
added += [numpy_helper.from_array(np.ascontiguousarray(weight[:, a:b]), names[0]), numpy_helper.from_array(np.ascontiguousarray(bias[a:b]), names[1])]
|
| 55 |
+
nodes.append(helper.make_node("Gemm", [node.input[0], names[0], names[1]], [names[2]]))
|
| 56 |
+
parts.append(names[2])
|
| 57 |
+
nodes.append(helper.make_node("Concat", parts, [node.output[0]], axis=1))
|
| 58 |
+
dropped |= {node.input[1], node.input[2]}
|
| 59 |
+
cut += 1
|
| 60 |
+
used = {name for node in nodes for name in node.input}
|
| 61 |
+
keep = [t for t in model.graph.initializer if t.name not in dropped or t.name in used]
|
| 62 |
+
del model.graph.node[:]
|
| 63 |
+
model.graph.node.extend(nodes)
|
| 64 |
+
del model.graph.initializer[:]
|
| 65 |
+
model.graph.initializer.extend(keep + added)
|
| 66 |
+
return cut
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def examples(shapes, table, bnd, sess, per_stratum=2):
|
| 70 |
+
"""Dev instances of each shape with their first guesses, as model inputs: the first few of each stratum."""
|
| 71 |
bindex = {b: i for i, b in enumerate(bnd["boundary_id"].tolist())}
|
| 72 |
+
out = {shape: [] for shape in shapes}
|
| 73 |
+
for stratum in ("medium", "loose", "tight"):
|
| 74 |
+
rows, _ = lm.dev_rows(table, 10 ** 6, "fixed_shape" if shapes == [(3, 5)] else "variable_shape", (stratum,))
|
| 75 |
+
taken = {shape: 0 for shape in shapes}
|
| 76 |
+
for i in rows:
|
| 77 |
+
shape = (int(table["nfp"][i]), int(table["n_coils"][i]))
|
| 78 |
+
if shape in out and taken[shape] < per_stratum:
|
| 79 |
+
b = bindex[str(table["boundary_id"][i])]
|
| 80 |
+
tgt = table["target"][i]
|
| 81 |
+
out[shape].append((bnd["r_cos"][b], bnd["z_sin"][b], tgt, lm.first_guess(sess, bnd["r_cos"][b], bnd["z_sin"][b], tgt, *shape)))
|
| 82 |
+
taken[shape] += 1
|
| 83 |
return out
|
| 84 |
|
| 85 |
|
| 86 |
+
def branch(nfp, k, tag):
|
| 87 |
+
"""The nodes and constants of one shape's prepare -> Loop(step) -> finish, reading the outer names
|
| 88 |
+
boundary_r_cos, boundary_z_sin, requirement_metrics and fg/coil_*_n, fg/currents, and its four output names."""
|
| 89 |
+
from onnx import helper
|
| 90 |
+
t0 = time.time()
|
| 91 |
+
lm.configure(nfp, k, "cpu", torch.float32)
|
| 92 |
+
main, body = S.Graph(tag + "m"), S.Graph(tag + "s")
|
| 93 |
+
with S.use(main):
|
| 94 |
+
args = (S.Sym("boundary_r_cos", (5, 9)), S.Sym("boundary_z_sin", (5, 9)), S.Sym("requirement_metrics", (4,)),
|
| 95 |
+
S.Sym("fg/coil_x_n", (k, lm.NM)), S.Sym("fg/coil_y_n", (k, lm.NM)), S.Sym("fg/coil_z_n", (k, lm.NM)), S.Sym("fg/currents", (k,)))
|
| 96 |
+
g, state, ring, ring_current, ring_ok = lm.prepare(*args)
|
| 97 |
+
state = [S.lift(v) for v in state]
|
| 98 |
+
go = ~ring_ok
|
| 99 |
+
count_prepare = len(main.nodes)
|
| 100 |
+
with S.use(body):
|
| 101 |
+
i = S.Sym(tag + "s_i", (), np.int64)
|
| 102 |
+
ins = [S.Sym(f"{tag}s_{name}", v.shape) for name, v in zip(lm.names(), state)]
|
| 103 |
+
out = lm.step(i, *ins, g=g)
|
| 104 |
+
assert len(out) == len(ins) + 1 and all(o.shape == v.shape for o, v in zip(out[1:], ins)), "the loop's state changed shape"
|
| 105 |
+
loop_body = helper.make_graph(
|
| 106 |
+
body.nodes, tag + "_step",
|
| 107 |
+
[S.info(i.name, (), np.int64), S.info(tag + "s_cond", (), np.bool_), *[S.info(v.name, v.shape) for v in ins]],
|
| 108 |
+
[S.info(out[0].name, (), np.bool_), *[S.info(v.name, v.shape) for v in out[1:]]], body.inits)
|
| 109 |
+
with S.use(main):
|
| 110 |
+
finals = [main.fresh() for _ in state]
|
| 111 |
+
main.nodes.append(helper.make_node("Loop", [main.const(lm.ITERS + 1, np.int64), go.name, *[v.name for v in state]], finals, body=loop_body))
|
| 112 |
+
outs = lm.finish(S.Sym(finals[0], state[0].shape), S.Sym(finals[1], state[1].shape), args[6], ring, ring_current, ring_ok)[:4]
|
| 113 |
+
values = sum(int(np.prod(t.dims)) for t in [*main.inits, *body.inits])
|
| 114 |
+
ops = body.operations()
|
| 115 |
+
print(f"{nfp}x{k}: nodes prepare {count_prepare}, pass {len(body.nodes)}, finish {len(main.nodes) - count_prepare - 1}; "
|
| 116 |
+
f"{len(lm.TAB.xspans)} chunks of {lm.TAB.X} surface points; constants {values} values; a pass holds "
|
| 117 |
+
f"{', '.join(f'{n} {op}' for op, n in ops.most_common(8))} [{time.time() - t0:.1f}s]", flush=True)
|
| 118 |
+
return main.nodes, main.inits, [v.name for v in outs]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def export(out, shapes, check=True):
|
| 122 |
import onnx
|
| 123 |
import onnxruntime as ort
|
| 124 |
+
import queue_io
|
| 125 |
from onnx import TensorProto, compose, helper, numpy_helper
|
| 126 |
+
torch.set_num_threads(4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
f32, i64 = TensorProto.FLOAT, TensorProto.INT64
|
| 128 |
+
const = lambda name, v, dtype=np.float32: numpy_helper.from_array(np.asarray(v, dtype), name) # noqa: E731
|
| 129 |
wire = lambda a, b: helper.make_node("Identity", [a], [b]) # noqa: E731
|
| 130 |
+
outs = ("coil_x_n", "coil_y_n", "coil_z_n", "currents")
|
| 131 |
# the request to the first-guess network: one transform of the targets, or one of two by the field-error target
|
| 132 |
+
switch = lm.ASK == "switch"
|
| 133 |
+
scale, lo, hi = lm.ASKS["floors" if switch else lm.ASK]
|
| 134 |
nodes = [helper.make_node("Mul", ["requirement_metrics", "ask_scale"], ["ask_0"]),
|
| 135 |
helper.make_node("Max", ["ask_0", "ask_lo"], ["ask_1"]),
|
| 136 |
helper.make_node("Min", ["ask_1", "ask_hi"], ["ask_2" if switch else "fg/requirement_metrics"])]
|
| 137 |
+
inits = [const("ask_scale", scale), const("ask_lo", lo), const("ask_hi", hi)]
|
| 138 |
if switch:
|
| 139 |
+
assert lm.ASKS["asked"][0] == (1.0, 1.0, 1.0, 1.0)
|
| 140 |
nodes += [helper.make_node("Gather", ["requirement_metrics", "ask_index"], ["ask_field"], axis=0),
|
| 141 |
helper.make_node("Greater", ["ask_field", "ask_switch"], ["ask_high"]),
|
| 142 |
helper.make_node("Where", ["ask_high", "ask_2", "requirement_metrics"], ["fg/requirement_metrics"])]
|
| 143 |
+
inits += [const("ask_index", 3, np.int64), const("ask_switch", lm.ASK_SWITCH)]
|
| 144 |
+
base = onnx.load(str(lm.BASE))
|
| 145 |
+
cut = split_gemms(base)
|
| 146 |
+
base = compose.add_prefix(base, "fg/")
|
| 147 |
+
print(f"first-guess network: {len(base.graph.node)} nodes, {cut} matrix products cut into column chunks", flush=True)
|
| 148 |
+
nodes += [wire("boundary_r_cos", "fg/boundary_r_cos"), wire("boundary_z_sin", "fg/boundary_z_sin"),
|
| 149 |
+
wire("n_field_periods", "fg/n_field_periods"), wire("n_coils_per_half_period", "fg/n_coils_per_half_period"),
|
| 150 |
+
*base.graph.node]
|
| 151 |
+
inits += list(base.graph.initializer)
|
| 152 |
+
if len(shapes) == 1:
|
| 153 |
+
nfp, k = shapes[0]
|
| 154 |
+
b_nodes, b_inits, b_outs = branch(nfp, k, f"b{nfp}{k}")
|
| 155 |
+
nodes += [*b_nodes, *[wire(a, b) for a, b in zip(b_outs, outs)]]
|
| 156 |
+
inits += b_inits
|
| 157 |
+
out_shapes = [[k, lm.NM]] * 3 + [[k]]
|
| 158 |
+
else:
|
| 159 |
+
# nested If nodes, innermost first: a shape without a branch keeps the first-guess network's coilset
|
| 160 |
+
inner = helper.make_graph([wire("fg/" + name, "else/" + name) for name in outs], "no_branch", [],
|
| 161 |
+
[helper.make_tensor_value_info("else/" + name, f32, None) for name in outs])
|
| 162 |
+
for depth, (nfp, k) in enumerate(reversed(shapes)):
|
| 163 |
+
tag = f"b{nfp}{k}"
|
| 164 |
+
b_nodes, b_inits, b_outs = branch(nfp, k, tag)
|
| 165 |
+
then = helper.make_graph(b_nodes, tag, [], [helper.make_tensor_value_info(name, f32, None) for name in b_outs], b_inits)
|
| 166 |
+
nodes += [helper.make_node("Equal", ["n_field_periods", f"{tag}/nfp"], [f"{tag}/is_nfp"]),
|
| 167 |
+
helper.make_node("Equal", ["n_coils_per_half_period", f"{tag}/k"], [f"{tag}/is_k"]),
|
| 168 |
+
helper.make_node("And", [f"{tag}/is_nfp", f"{tag}/is_k"], [f"{tag}/is"])]
|
| 169 |
+
inits += [const(f"{tag}/nfp", nfp, np.int64), const(f"{tag}/k", k, np.int64)]
|
| 170 |
+
last = depth == len(shapes) - 1
|
| 171 |
+
names = list(outs) if last else [f"{tag}/if/{name}" for name in outs]
|
| 172 |
+
if_node = helper.make_node("If", [f"{tag}/is"], names, then_branch=then, else_branch=inner)
|
| 173 |
+
if last:
|
| 174 |
+
nodes.append(if_node)
|
| 175 |
+
else:
|
| 176 |
+
inner = helper.make_graph([if_node], f"{tag}/else", [], [helper.make_tensor_value_info(name, f32, None) for name in names])
|
| 177 |
+
out_shapes = [["n_coils", lm.NM]] * 3 + [["n_coils"]]
|
| 178 |
graph = helper.make_graph(
|
| 179 |
nodes, "coilstellaration_optimizer",
|
| 180 |
[helper.make_tensor_value_info("boundary_r_cos", f32, [5, 9]), helper.make_tensor_value_info("boundary_z_sin", f32, [5, 9]),
|
| 181 |
helper.make_tensor_value_info("requirement_metrics", f32, [4]), helper.make_tensor_value_info("n_field_periods", i64, []),
|
| 182 |
helper.make_tensor_value_info("n_coils_per_half_period", i64, [])],
|
| 183 |
+
[helper.make_tensor_value_info(name, f32, shape) for name, shape in zip(outs, out_shapes)], inits)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
final = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 20)], ir_version=10, producer_name="coilstellaration-optimizer")
|
| 185 |
+
tracks = "fixed_shape" if shapes == [(3, 5)] else "fixed_shape,variable_shape"
|
| 186 |
+
final.metadata_props.append(onnx.StringStringEntryProto(key="supported_tracks", value=tracks))
|
|
|
|
| 187 |
onnx.save(final, out)
|
| 188 |
+
onnx.checker.check_model(out)
|
| 189 |
+
print(f"wrote {out}: {Path(out).stat().st_size / 2 ** 20:.1f} MiB, supported_tracks {tracks}, {lm.ITERS} steps", flush=True)
|
| 190 |
+
if not check:
|
| 191 |
+
return
|
| 192 |
+
table, bnd = queue_io.instances(), queue_io.boundaries()
|
| 193 |
+
cases = examples(shapes, table, bnd, ort.InferenceSession(str(lm.BASE), providers=["CPUExecutionProvider"]), 2 if len(shapes) == 1 else 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
opts = ort.SessionOptions()
|
| 195 |
+
opts.intra_op_num_threads = 1
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
t0 = time.time()
|
| 197 |
+
sess = ort.InferenceSession(out, opts, providers=["CPUExecutionProvider"])
|
| 198 |
+
print(f"session in {time.time() - t0:.1f}s")
|
| 199 |
+
for (nfp, k), rows in cases.items():
|
| 200 |
+
lm.configure(nfp, k, "cpu", torch.float32)
|
| 201 |
+
worst, took = 0.0, []
|
| 202 |
+
for r_cos, z_sin, tgt, guess in rows:
|
| 203 |
+
feed = {"boundary_r_cos": r_cos.astype(np.float32), "boundary_z_sin": z_sin.astype(np.float32),
|
| 204 |
+
"requirement_metrics": tgt.astype(np.float32), "n_field_periods": np.asarray(nfp, np.int64),
|
| 205 |
+
"n_coils_per_half_period": np.asarray(k, np.int64)}
|
| 206 |
+
t1 = time.perf_counter()
|
| 207 |
+
got = sess.run(None, feed)
|
| 208 |
+
took.append(time.perf_counter() - t1)
|
| 209 |
+
with torch.no_grad():
|
| 210 |
+
want = lm.model(lm._t(r_cos), lm._t(z_sin), lm._t(tgt), *[lm._t(o) for o in guess])
|
| 211 |
+
worst = max(worst, max(float(np.abs(got[a] - want[a].numpy()).max()) for a in range(3)))
|
| 212 |
+
print(f"{nfp}x{k}: largest coefficient difference from PyTorch {worst:.2e} m over {len(rows)} instances; "
|
| 213 |
+
f"one thread, ms per instance {' '.join(f'{1e3 * t:.0f}' for t in took)}", flush=True)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 218 |
+
argv = sys.argv[1:]
|
| 219 |
+
while "--set" in argv:
|
| 220 |
+
j = argv.index("--set")
|
| 221 |
+
name, value = argv[j + 1].split("=")
|
| 222 |
+
setattr(lm, name, type(getattr(lm, name))(value))
|
| 223 |
+
del argv[j:j + 2]
|
| 224 |
+
check = "--no-check" not in argv
|
| 225 |
+
argv = [a for a in argv if a != "--no-check"]
|
| 226 |
+
names = argv[1:] or ["3x5"]
|
| 227 |
+
export(argv[0], SHAPES if names == ["all"] else [tuple(int(v) for v in n.split("x")) for n in names], check)
|