File size: 24,954 Bytes
f1564a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
"""Train and evaluate constitutive-memory baselines for T2 multiaxial v2."""

from __future__ import annotations

import argparse
import json
import math
import random
import time
from dataclasses import dataclass
from pathlib import Path

import h5py
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F


ROOT = Path(__file__).resolve().parents[1]
DATA_ROOT = ROOT / "data" / "t2_multiaxial_ood_v2"
ARTIFACT_ROOT = ROOT / "artifacts" / "t2_multiaxial_ood_v2"
MODEL_ROOT = ROOT / "models" / "t2_multiaxial_ood_v2"
PROTOCOLS = {
    "id": "split_id",
    "path_ood": "split_path_ood",
    "parameter_ood": "split_parameter_ood",
}
MODEL_NAMES = ("pointwise_mlp", "gru", "lstm", "causal_tcn", "physics_state_gru")
PARAMETER_NAMES = (
    "young_pa",
    "poisson",
    "yield_stress_pa",
    "hardening_modulus_pa",
    "backstress_c1_pa",
    "backstress_gamma1",
    "backstress_c2_pa",
    "backstress_gamma2",
    "isotropic_saturation_pa",
    "isotropic_rate",
)


@dataclass
class DatasetBundle:
    ids: list[str]
    material_models: list[str]
    path_families: list[str]
    splits: dict[str, list[str]]
    strain: torch.Tensor
    stress: torch.Tensor
    plastic_strain: torch.Tensor
    peeq: torch.Tensor
    backstress: torch.Tensor
    plastic_increment: torch.Tensor
    parameters: torch.Tensor


def _resolve_shard(relative_path: str) -> Path:
    path = ROOT / relative_path
    if path.exists():
        return path
    fallback = DATA_ROOT / "shards" / Path(relative_path).name
    if fallback.exists():
        return fallback
    raise FileNotFoundError(relative_path)


def load_dataset() -> DatasetBundle:
    manifest = json.loads((DATA_ROOT / "manifest.json").read_text(encoding="utf-8"))
    ids: list[str] = []
    models: list[str] = []
    families: list[str] = []
    splits = {field: [] for field in PROTOCOLS.values()}
    strain = []
    stress = []
    plastic = []
    peeq = []
    backstress = []
    plastic_increment = []
    parameters = []
    for shard in manifest["shards"]:
        with h5py.File(_resolve_shard(shard["path"]), "r") as h5:
            for sample_id in sorted(h5.keys()):
                group = h5[sample_id]
                ids.append(sample_id)
                models.append(str(group.attrs["material_model"]))
                families.append(str(group.attrs["path_family"]))
                for field in splits:
                    splits[field].append(str(group.attrs[field]))
                strain.append(group["total_strain_voigt"][:].astype(np.float32))
                stress.append(group["stress_voigt_pa"][:].astype(np.float32))
                plastic.append(group["plastic_strain_voigt"][:].astype(np.float32))
                peeq.append(group["equivalent_plastic_strain"][:].astype(np.float32))
                backstress.append(group["backstress_voigt_pa"][:].astype(np.float32))
                plastic_increment.append(group["plastic_multiplier_increment"][:].astype(np.float32))
                parameters.append(group["material_parameter_vector"][:].astype(np.float32))
    return DatasetBundle(
        ids=ids,
        material_models=models,
        path_families=families,
        splits=splits,
        strain=torch.from_numpy(np.stack(strain)),
        stress=torch.from_numpy(np.stack(stress)),
        plastic_strain=torch.from_numpy(np.stack(plastic)),
        peeq=torch.from_numpy(np.stack(peeq)),
        backstress=torch.from_numpy(np.stack(backstress)),
        plastic_increment=torch.from_numpy(np.stack(plastic_increment)),
        parameters=torch.from_numpy(np.stack(parameters)),
    )


def _safe_mean_std(value: torch.Tensor, dimensions: tuple[int, ...]) -> tuple[torch.Tensor, torch.Tensor]:
    mean = value.mean(dim=dimensions, keepdim=True)
    std = value.std(dim=dimensions, keepdim=True)
    std = torch.where(std < 1.0e-12, torch.ones_like(std), std)
    return mean, std


def masks(bundle: DatasetBundle, split_field: str) -> dict[str, torch.Tensor]:
    values = bundle.splits[split_field]
    return {
        split: torch.tensor([value == split for value in values], dtype=torch.bool)
        for split in ("train", "validation", "test")
    }


def model_indicator(bundle: DatasetBundle) -> torch.Tensor:
    return torch.tensor(
        [[1.0, 0.0] if name == "j2_linear_isotropic" else [0.0, 1.0] for name in bundle.material_models],
        dtype=torch.float32,
    )


@dataclass
class Normalization:
    strain_mean: torch.Tensor
    strain_std: torch.Tensor
    parameter_mean: torch.Tensor
    parameter_std: torch.Tensor
    stress_mean: torch.Tensor
    stress_std: torch.Tensor
    plastic_scale: torch.Tensor
    backstress_scale: torch.Tensor
    peeq_scale: torch.Tensor

    def json_dict(self) -> dict[str, object]:
        return {name: value.detach().cpu().numpy().reshape(-1).tolist() for name, value in vars(self).items()}


def fit_normalization(bundle: DatasetBundle, train_mask: torch.Tensor) -> Normalization:
    strain_mean, strain_std = _safe_mean_std(bundle.strain[train_mask], (0, 1))
    parameter_mean, parameter_std = _safe_mean_std(bundle.parameters[train_mask], (0,))
    stress_mean, stress_std = _safe_mean_std(bundle.stress[train_mask], (0, 1))
    plastic_scale = bundle.plastic_strain[train_mask].abs().amax(dim=(0, 1), keepdim=True).clamp_min(1.0e-6)
    backstress_scale = bundle.backstress[train_mask].abs().amax(dim=(0, 1), keepdim=True).clamp_min(1.0e6)
    peeq_scale = bundle.peeq[train_mask].amax().reshape(1, 1).clamp_min(1.0e-5)
    return Normalization(strain_mean, strain_std, parameter_mean, parameter_std, stress_mean, stress_std, plastic_scale, backstress_scale, peeq_scale)


def normalized_inputs(bundle: DatasetBundle, norm: Normalization) -> torch.Tensor:
    strain = (bundle.strain - norm.strain_mean) / norm.strain_std
    parameters = (bundle.parameters - norm.parameter_mean) / norm.parameter_std
    repeated = parameters[:, None, :].expand(-1, strain.shape[1], -1)
    indicator = model_indicator(bundle)[:, None, :].expand(-1, strain.shape[1], -1)
    return torch.cat((strain, repeated, indicator), dim=-1)


class PointwiseMLP(nn.Module):
    def __init__(self, input_size: int, hidden: int = 96):
        super().__init__()
        self.network = nn.Sequential(
            nn.Linear(input_size, hidden), nn.SiLU(),
            nn.Linear(hidden, hidden), nn.SiLU(),
            nn.Linear(hidden, 6),
        )

    def forward(self, value: torch.Tensor) -> torch.Tensor:
        return self.network(value)


class RecurrentStress(nn.Module):
    def __init__(self, input_size: int, *, cell: str, hidden: int = 72):
        super().__init__()
        recurrent = nn.GRU if cell == "gru" else nn.LSTM
        self.recurrent = recurrent(input_size, hidden, num_layers=2, batch_first=True)
        self.output = nn.Linear(hidden, 6)

    def forward(self, value: torch.Tensor) -> torch.Tensor:
        hidden, _ = self.recurrent(value)
        return self.output(hidden)


class CausalBlock(nn.Module):
    def __init__(self, width: int, dilation: int):
        super().__init__()
        self.padding = 2 * dilation
        self.conv = nn.Conv1d(width, width, kernel_size=3, dilation=dilation, padding=self.padding)
        self.norm = nn.GroupNorm(1, width)

    def forward(self, value: torch.Tensor) -> torch.Tensor:
        updated = self.conv(value)
        updated = updated[..., : value.shape[-1]]
        return F.silu(self.norm(updated)) + value


class CausalTCN(nn.Module):
    def __init__(self, input_size: int, width: int = 72):
        super().__init__()
        self.input = nn.Conv1d(input_size, width, kernel_size=1)
        self.blocks = nn.Sequential(*(CausalBlock(width, dilation) for dilation in (1, 2, 4, 8)))
        self.output = nn.Conv1d(width, 6, kernel_size=1)

    def forward(self, value: torch.Tensor) -> torch.Tensor:
        sequence = value.transpose(1, 2)
        return self.output(self.blocks(self.input(sequence))).transpose(1, 2)


def dev5_to_voigt(value: torch.Tensor) -> torch.Tensor:
    xx, yy, xy, yz, xz = value.unbind(dim=-1)
    return torch.stack((xx, yy, -xx - yy, xy, yz, xz), dim=-1)


def hooke_stress(strain: torch.Tensor, plastic: torch.Tensor, parameters: torch.Tensor) -> torch.Tensor:
    elastic = strain - plastic
    young = parameters[:, None, 0]
    poisson = parameters[:, None, 1]
    shear = young / (2.0 * (1.0 + poisson))
    bulk = young / (3.0 * (1.0 - 2.0 * poisson))
    trace = elastic[..., 0] + elastic[..., 1] + elastic[..., 2]
    mean = trace / 3.0
    normal = 2.0 * shear[..., None] * (elastic[..., :3] - mean[..., None]) + bulk[..., None] * trace[..., None]
    shear_stress = 2.0 * shear[..., None] * elastic[..., 3:]
    return torch.cat((normal, shear_stress), dim=-1)


class PhysicsStateGRU(nn.Module):
    """Causal internal-state model with exact deviatoric PE and Hooke reconstruction."""

    def __init__(self, input_size: int, hidden: int = 80):
        super().__init__()
        self.recurrent = nn.GRU(input_size, hidden, num_layers=2, batch_first=True)
        self.state_head = nn.Linear(hidden, 11)

    def forward(
        self,
        normalized_input: torch.Tensor,
        strain: torch.Tensor,
        parameters: torch.Tensor,
        norm: Normalization,
    ) -> dict[str, torch.Tensor]:
        hidden, _ = self.recurrent(normalized_input)
        raw = self.state_head(hidden)
        plastic5 = raw[..., :5] * norm.plastic_scale[..., (0, 1, 3, 4, 5)]
        backstress5 = raw[..., 5:10] * norm.backstress_scale[..., (0, 1, 3, 4, 5)]
        plastic = dev5_to_voigt(plastic5)
        backstress = dev5_to_voigt(backstress5)
        increments = (
            F.softplus(raw[:, 1:, 10])
            * norm.peeq_scale.squeeze()
            / max(raw.shape[1] - 1, 1)
        )
        peeq = torch.cat(
            (
                torch.zeros_like(raw[:, :1, 10]),
                torch.cumsum(increments, dim=1),
            ),
            dim=1,
        )
        stress = hooke_stress(strain, plastic, parameters)
        return {"stress": stress, "plastic_strain": plastic, "backstress": backstress, "peeq": peeq}


def build_model(name: str, input_size: int) -> nn.Module:
    if name == "pointwise_mlp":
        return PointwiseMLP(input_size)
    if name == "gru":
        return RecurrentStress(input_size, cell="gru")
    if name == "lstm":
        return RecurrentStress(input_size, cell="lstm")
    if name == "causal_tcn":
        return CausalTCN(input_size)
    if name == "physics_state_gru":
        return PhysicsStateGRU(input_size)
    raise ValueError(name)


def voigt_mises(stress: torch.Tensor) -> torch.Tensor:
    mean = stress[..., :3].mean(dim=-1, keepdim=True)
    dev_normal = stress[..., :3] - mean
    square = (dev_normal**2).sum(dim=-1) + 2.0 * (stress[..., 3:] ** 2).sum(dim=-1)
    return torch.sqrt(torch.clamp(1.5 * square, min=0.0))


def predict(model: nn.Module, name: str, x: torch.Tensor, bundle: DatasetBundle, indices: torch.Tensor, norm: Normalization) -> dict[str, torch.Tensor]:
    if name == "physics_state_gru":
        return model(x[indices], bundle.strain[indices], bundle.parameters[indices], norm)
    normalized = model(x[indices])
    return {"stress": normalized * norm.stress_std + norm.stress_mean}


def physics_loss(predicted: dict[str, torch.Tensor], bundle: DatasetBundle, indices: torch.Tensor, norm: Normalization) -> torch.Tensor:
    target_stress = bundle.stress[indices]
    target_plastic = bundle.plastic_strain[indices]
    target_backstress = bundle.backstress[indices]
    target_peeq = bundle.peeq[indices]
    stress_loss = (((predicted["stress"] - target_stress) / norm.stress_std) ** 2).mean()
    plastic_loss = (((predicted["plastic_strain"] - target_plastic) / norm.plastic_scale) ** 2).mean()
    backstress_loss = (((predicted["backstress"] - target_backstress) / norm.backstress_scale) ** 2).mean()
    peeq_loss = (((predicted["peeq"] - target_peeq) / norm.peeq_scale) ** 2).mean()
    monotonic = (
        F.relu(predicted["peeq"][:, :-1] - predicted["peeq"][:, 1:]).mean()
        / norm.peeq_scale.squeeze()
    )
    parameters = bundle.parameters[indices]
    chaboche = model_indicator(bundle)[indices, 1][:, None]
    j2_radius = (
        parameters[:, 2][:, None]
        + parameters[:, 3][:, None] * predicted["peeq"]
    )
    chaboche_radius = parameters[:, 2][:, None] + parameters[:, 8][:, None] * (
        1.0 - torch.exp(-parameters[:, 9][:, None] * predicted["peeq"])
    )
    radius = (1.0 - chaboche) * j2_radius + chaboche * chaboche_radius
    shifted_mises = voigt_mises(predicted["stress"] - predicted["backstress"])
    plastic_mask = bundle.plastic_increment[indices] > 0.0
    yield_loss = (
        ((shifted_mises - radius) / radius.clamp_min(1.0))[plastic_mask] ** 2
    ).mean()
    return (
        stress_loss
        + 0.25 * plastic_loss
        + 0.08 * backstress_loss
        + 0.10 * peeq_loss
        + 0.05 * monotonic
        + 0.10 * yield_loss
    )


def train_one(
    name: str,
    bundle: DatasetBundle,
    split_mask: dict[str, torch.Tensor],
    norm: Normalization,
    *,
    epochs: int,
    batch_size: int,
    seed: int,
) -> tuple[nn.Module, list[dict[str, float]]]:
    torch.manual_seed(seed)
    random.seed(seed)
    x = normalized_inputs(bundle, norm)
    model = build_model(name, x.shape[-1])
    optimizer = torch.optim.AdamW(model.parameters(), lr=2.0e-3, weight_decay=1.0e-5)
    train_indices = torch.where(split_mask["train"])[0]
    validation_indices = torch.where(split_mask["validation"])[0]
    best_state = None
    best_validation = math.inf
    stale = 0
    history: list[dict[str, float]] = []
    for epoch in range(epochs):
        model.train()
        order = train_indices[torch.randperm(len(train_indices))]
        losses = []
        for start in range(0, len(order), batch_size):
            index = order[start : start + batch_size]
            optimizer.zero_grad(set_to_none=True)
            if name == "physics_state_gru":
                predicted = predict(model, name, x, bundle, index, norm)
                loss = physics_loss(predicted, bundle, index, norm)
            else:
                output = model(x[index])
                target = (bundle.stress[index] - norm.stress_mean) / norm.stress_std
                loss = F.mse_loss(output, target)
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
            optimizer.step()
            losses.append(float(loss.detach()))
        model.eval()
        with torch.no_grad():
            if name == "physics_state_gru":
                validation = float(physics_loss(predict(model, name, x, bundle, validation_indices, norm), bundle, validation_indices, norm))
            else:
                validation = float(F.mse_loss(model(x[validation_indices]), (bundle.stress[validation_indices] - norm.stress_mean) / norm.stress_std))
        history.append({"epoch": epoch + 1, "train_loss": float(np.mean(losses)), "validation_loss": validation})
        if validation < best_validation - 1.0e-6:
            best_validation = validation
            best_state = {key: value.detach().clone() for key, value in model.state_dict().items()}
            stale = 0
        else:
            stale += 1
        if stale >= 8 and epoch >= 14:
            break
    if best_state is None:
        raise RuntimeError("Training did not produce a checkpoint.")
    model.load_state_dict(best_state)
    return model, history


def _double_contract(stress: torch.Tensor, strain_increment: torch.Tensor) -> torch.Tensor:
    weights = torch.tensor((1.0, 1.0, 1.0, 2.0, 2.0, 2.0), dtype=stress.dtype)
    return (stress * strain_increment * weights).sum(dim=-1)


def evaluate(
    model: nn.Module,
    name: str,
    bundle: DatasetBundle,
    selected: torch.Tensor,
    norm: Normalization,
) -> tuple[dict[str, float], dict[str, torch.Tensor]]:
    x = normalized_inputs(bundle, norm)
    indices = torch.where(selected)[0]
    model.eval()
    started = time.perf_counter()
    with torch.no_grad():
        predicted = predict(model, name, x, bundle, indices, norm)
    elapsed = time.perf_counter() - started
    reference = bundle.stress[indices]
    error = predicted["stress"] - reference
    rmse = torch.sqrt((error**2).mean())
    mae = error.abs().mean()
    centered = reference - reference.mean()
    r2 = 1.0 - (error**2).sum() / (centered**2).sum().clamp_min(1.0)
    predicted_mises = voigt_mises(predicted["stress"])
    reference_mises = voigt_mises(reference)
    peak_error = ((predicted_mises.amax(dim=1) - reference_mises.amax(dim=1)).abs() / reference_mises.amax(dim=1).clamp_min(1.0)).mean()
    increments = bundle.strain[indices, 1:] - bundle.strain[indices, :-1]
    predicted_work = _double_contract(0.5 * (predicted["stress"][:, 1:] + predicted["stress"][:, :-1]), increments).sum(dim=1)
    reference_work = _double_contract(0.5 * (reference[:, 1:] + reference[:, :-1]), increments).sum(dim=1)
    work_error = ((predicted_work - reference_work).abs() / reference_work.abs().clamp_min(1.0)).mean()

    alpha = bundle.backstress[indices]
    shifted = predicted["stress"] - alpha
    shifted_mises = voigt_mises(shifted)
    params = bundle.parameters[indices]
    peeq = bundle.peeq[indices]
    indicator = model_indicator(bundle)[indices, 1][:, None]
    j2_radius = params[:, 2][:, None] + params[:, 3][:, None] * peeq
    chaboche_radius = params[:, 2][:, None] + params[:, 8][:, None] * (1.0 - torch.exp(-params[:, 9][:, None] * peeq))
    radius = (1.0 - indicator) * j2_radius + indicator * chaboche_radius
    plastic_mask = bundle.plastic_increment[indices] > 0.0
    yield_residual = ((shifted_mises - radius).abs() / radius.clamp_min(1.0))[plastic_mask].mean()

    decimated = torch.arange(0, bundle.strain.shape[1], 2)
    if decimated[-1] != bundle.strain.shape[1] - 1:
        decimated = torch.cat((decimated, torch.tensor([bundle.strain.shape[1] - 1])))
    with torch.no_grad():
        if name == "physics_state_gru":
            coarse = model(x[indices][:, decimated], bundle.strain[indices][:, decimated], bundle.parameters[indices], norm)["stress"]
        else:
            coarse = model(x[indices][:, decimated]) * norm.stress_std + norm.stress_mean
    resolution_rmse = torch.sqrt(((coarse - reference[:, decimated]) ** 2).mean())

    metrics = {
        "rmse_mpa": float(rmse / 1.0e6),
        "mae_mpa": float(mae / 1.0e6),
        "r2": float(r2),
        "mean_peak_mises_relative_error": float(peak_error),
        "mean_work_relative_error": float(work_error),
        "mean_yield_surface_relative_residual_using_reference_state": float(yield_residual),
        "decimated_121_state_rmse_mpa": float(resolution_rmse / 1.0e6),
        "inference_seconds": elapsed,
        "trajectory_count": int(len(indices)),
    }
    if name == "physics_state_gru":
        peeq_predicted = predicted["peeq"]
        metrics.update(
            plastic_strain_rmse=float(torch.sqrt(((predicted["plastic_strain"] - bundle.plastic_strain[indices]) ** 2).mean())),
            backstress_rmse_mpa=float(torch.sqrt(((predicted["backstress"] - bundle.backstress[indices]) ** 2).mean()) / 1.0e6),
            peeq_rmse=float(torch.sqrt(((peeq_predicted - bundle.peeq[indices]) ** 2).mean())),
            peeq_nonmonotone_fraction=float((peeq_predicted[:, 1:] < peeq_predicted[:, :-1]).float().mean()),
            maximum_plastic_strain_trace=float((predicted["plastic_strain"][..., :3].sum(dim=-1)).abs().max()),
        )
    return metrics, {**predicted, "indices": indices}


def _write_json(path: Path, value: object) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")


def train_suite(
    *,
    epochs: int = 35,
    batch_size: int = 32,
    seed: int = 20261001,
    protocols: tuple[str, ...] = tuple(PROTOCOLS),
    model_names: tuple[str, ...] = MODEL_NAMES,
) -> dict[str, object]:
    torch.set_num_threads(min(8, max(1, torch.get_num_threads())))
    bundle = load_dataset()
    ARTIFACT_ROOT.mkdir(parents=True, exist_ok=True)
    MODEL_ROOT.mkdir(parents=True, exist_ok=True)
    metrics_path = ARTIFACT_ROOT / "model_metrics.json"
    all_metrics: dict[str, object] = (
        json.loads(metrics_path.read_text(encoding="utf-8"))
        if metrics_path.exists()
        else {}
    )
    representative: dict[tuple[str, str], tuple[dict[str, torch.Tensor], torch.Tensor]] = {}
    started = time.perf_counter()
    for protocol_index, protocol in enumerate(protocols):
        split_field = PROTOCOLS[protocol]
        split_mask = masks(bundle, split_field)
        norm = fit_normalization(bundle, split_mask["train"])
        _write_json(MODEL_ROOT / f"{protocol}_normalization.json", {"protocol": protocol, "split_field": split_field, "parameter_names": PARAMETER_NAMES, "normalization": norm.json_dict()})
        for model_index, name in enumerate(model_names):
            print(f"training {protocol}/{name}", flush=True)
            model, history = train_one(name, bundle, split_mask, norm, epochs=epochs, batch_size=batch_size, seed=seed + 100 * protocol_index + model_index)
            metrics, prediction = evaluate(model, name, bundle, split_mask["test"], norm)
            parameter_count = sum(value.numel() for value in model.parameters())
            metrics["parameter_count"] = parameter_count
            metrics["epochs_completed"] = len(history)
            metrics["best_validation_loss"] = min(item["validation_loss"] for item in history)
            all_metrics.setdefault(protocol, {})[name] = metrics
            checkpoint = {
                "model_name": name,
                "protocol": protocol,
                "split_field": split_field,
                "input_size": int(normalized_inputs(bundle, norm).shape[-1]),
                "parameter_count": parameter_count,
                "state_dict": model.state_dict(),
                "normalization": norm.json_dict(),
                "parameter_names": PARAMETER_NAMES,
                "voigt_order": ("xx", "yy", "zz", "xy", "yz", "xz"),
                "strain_shear_convention": "tensor",
                "seed": seed + 100 * protocol_index + model_index,
            }
            torch.save(checkpoint, MODEL_ROOT / f"{protocol}_{name}.pt")
            _write_json(MODEL_ROOT / f"{protocol}_{name}_history.json", history)
            if protocol in {"id", "path_ood"} and name in {"gru", "physics_state_gru"}:
                representative[(protocol, name)] = (prediction, bundle.stress[prediction["indices"]])
            print(json.dumps({"protocol": protocol, "model": name, **metrics}, sort_keys=True), flush=True)

    _write_json(ARTIFACT_ROOT / "model_metrics.json", all_metrics)
    figure, axes = plt.subplots(1, 3, figsize=(13.5, 4.2), constrained_layout=True)
    for axis, protocol in zip(axes, PROTOCOLS, strict=True):
        values = [all_metrics[protocol][name]["rmse_mpa"] for name in MODEL_NAMES]
        axis.bar(range(len(values)), values, color=("#9ca3af", "#2563eb", "#7c3aed", "#0f766e", "#dc2626"))
        axis.set_xticks(range(len(values)), ("MLP", "GRU", "LSTM", "TCN", "Physics\nstate GRU"), rotation=25, ha="right")
        axis.set_ylabel("Stress RMSE (MPa)")
        axis.set_title(protocol.replace("_", " ").upper())
        axis.grid(axis="y", alpha=0.2)
    figure.savefig(ARTIFACT_ROOT / "model_protocol_comparison.png", dpi=190)
    plt.close(figure)

    summary = {
        "status": "completed",
        "dataset_sample_count": len(bundle.ids),
        "protocols": protocols,
        "models": model_names,
        "epochs_requested": epochs,
        "batch_size": batch_size,
        "seed": seed,
        "elapsed_seconds": time.perf_counter() - started,
        "metrics_path": str((ARTIFACT_ROOT / "model_metrics.json").relative_to(ROOT)),
        "model_directory": str(MODEL_ROOT.relative_to(ROOT)),
    }
    _write_json(ARTIFACT_ROOT / "training_summary.json", summary)
    print(json.dumps(summary, indent=2), flush=True)
    return summary


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--epochs", type=int, default=35)
    parser.add_argument("--batch-size", type=int, default=32)
    parser.add_argument("--seed", type=int, default=20261001)
    parser.add_argument("--protocols", nargs="+", choices=tuple(PROTOCOLS), default=tuple(PROTOCOLS))
    parser.add_argument("--models", nargs="+", choices=MODEL_NAMES, default=MODEL_NAMES)
    args = parser.parse_args()
    train_suite(
        epochs=args.epochs,
        batch_size=args.batch_size,
        seed=args.seed,
        protocols=tuple(args.protocols),
        model_names=tuple(args.models),
    )


if __name__ == "__main__":
    main()