sim-tools-mcp 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cooling_surrogate/LICENSE +21 -0
- cooling_surrogate/__init__.py +0 -0
- cooling_surrogate/checks.py +60 -0
- cooling_surrogate/data.py +176 -0
- cooling_surrogate/metrics.py +60 -0
- cooling_surrogate/model.py +138 -0
- cooling_surrogate/monitor.py +87 -0
- cooling_surrogate/physics.py +299 -0
- cooling_surrogate/service.py +149 -0
- sim_tools_mcp/__init__.py +1 -0
- sim_tools_mcp/__main__.py +3 -0
- sim_tools_mcp/model_v1/bundle.json +12 -0
- sim_tools_mcp/model_v1/model/model.json +24 -0
- sim_tools_mcp/model_v1/model/weights.pt +0 -0
- sim_tools_mcp/py.typed +0 -0
- sim_tools_mcp/server.py +160 -0
- sim_tools_mcp/tools.py +703 -0
- sim_tools_mcp-1.0.0.dist-info/METADATA +241 -0
- sim_tools_mcp-1.0.0.dist-info/RECORD +23 -0
- sim_tools_mcp-1.0.0.dist-info/WHEEL +5 -0
- sim_tools_mcp-1.0.0.dist-info/entry_points.txt +2 -0
- sim_tools_mcp-1.0.0.dist-info/licenses/LICENSE +21 -0
- sim_tools_mcp-1.0.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Zuhal Karadavut
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
File without changes
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Physics checks on a prediction. Each returns a boolean per case: True means the case violates it.
|
|
2
|
+
|
|
3
|
+
The same checks run in the gate (over a test set) and in the service (on every answer, before it is
|
|
4
|
+
returned). They need no solver run, only the inputs and the predicted outputs.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from . import physics
|
|
12
|
+
from .model import Prediction
|
|
13
|
+
|
|
14
|
+
TOL_K = 1.0 # temperature slack for bounds and monotonicity
|
|
15
|
+
TOL_ENERGY = 0.02 # energy balance slack, as a fraction of the heat the wall can give off
|
|
16
|
+
TOL_EJECT_K = 2.0 # mid-plane at the predicted cooling time vs the ejection temperature
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def within_bounds(pred: Prediction, case: physics.Case) -> np.ndarray:
|
|
20
|
+
"""Never colder than the mould or hotter than the melt."""
|
|
21
|
+
low = pred.field.min(axis=(1, 2)) < case.t_mould - TOL_K
|
|
22
|
+
high = pred.field.max(axis=(1, 2)) > case.t_melt + TOL_K
|
|
23
|
+
return low | high
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cools_monotonically(pred: Prediction, case: physics.Case) -> np.ndarray:
|
|
27
|
+
"""No point warms up between two output times (the wall only loses heat)."""
|
|
28
|
+
return np.diff(pred.field, axis=1).max(axis=(1, 2)) > TOL_K
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def coolest_at_face(pred: Prediction, case: physics.Case) -> np.ndarray:
|
|
32
|
+
"""At every time the temperature falls from the mid-plane towards the mould face."""
|
|
33
|
+
return np.diff(pred.field, axis=2).max(axis=(1, 2)) > TOL_K
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def energy_balance(pred: Prediction, case: physics.Case) -> np.ndarray:
|
|
37
|
+
"""Heat that left through the face equals the drop in stored enthalpy of the predicted profile."""
|
|
38
|
+
start = case.half * physics.enthalpy(case.t_melt, case.latent)
|
|
39
|
+
stored = physics.stored_heat(pred.field, case, physics.N_CELLS)
|
|
40
|
+
residual = np.abs(start[:, None] - stored - pred.heat) / physics.removable_heat(case)[:, None]
|
|
41
|
+
return residual.max(axis=1) > TOL_ENERGY
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def ejects_at_cooling_time(pred: Prediction, case: physics.Case) -> np.ndarray:
|
|
45
|
+
"""The predicted profile at the predicted cooling time has its mid-plane at the ejection temperature."""
|
|
46
|
+
return np.abs(pred.field[:, -1, 0] - physics.T_EJECT) > TOL_EJECT_K
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
CHECKS = {
|
|
50
|
+
"within_bounds": within_bounds,
|
|
51
|
+
"cools_monotonically": cools_monotonically,
|
|
52
|
+
"coolest_at_face": coolest_at_face,
|
|
53
|
+
"energy_balance": energy_balance,
|
|
54
|
+
"ejects_at_cooling_time": ejects_at_cooling_time,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def run_all(pred: Prediction, params: np.ndarray) -> dict[str, np.ndarray]:
|
|
59
|
+
case = physics.Case.from_params(params)
|
|
60
|
+
return {name: check(pred, case) for name, check in CHECKS.items()}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Datasets of solver runs, versioned by content.
|
|
2
|
+
|
|
3
|
+
A dataset is a folder `data/<version>/` with one sub-folder per split and a `manifest.json`. The
|
|
4
|
+
manifest records the recipe (sampling config and the SHA-256 of the solver and generator code) and
|
|
5
|
+
the SHA-256 of every array file. The version is derived from those file hashes, so two folders with
|
|
6
|
+
the same version hold the same bytes, and any change to the solver or the sampling gives a new one.
|
|
7
|
+
Loading a split checks the hashes first.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import shutil
|
|
15
|
+
import time
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
from scipy.stats import qmc
|
|
21
|
+
|
|
22
|
+
from . import physics
|
|
23
|
+
|
|
24
|
+
ARRAYS = ("inputs", "t_cool", "field", "heat")
|
|
25
|
+
|
|
26
|
+
# The training box. Everything the surrogate learns comes from inside it.
|
|
27
|
+
TRAIN_BOX: dict[str, tuple[float, float]] = {
|
|
28
|
+
"melt_temp_c": (200.0, 260.0),
|
|
29
|
+
"mould_temp_c": (20.0, 60.0),
|
|
30
|
+
"thickness_mm": (1.0, 3.0),
|
|
31
|
+
"diffusivity_mm2_s": (0.08, 0.12),
|
|
32
|
+
"htc_w_m2k": (1500.0, 4000.0),
|
|
33
|
+
"latent_heat_kj_kg": (0.0, 80.0),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
# Out-of-distribution groups: one parameter leaves the box, the others stay inside it.
|
|
37
|
+
OOD_SHIFTS: dict[str, tuple[str, tuple[float, float]]] = {
|
|
38
|
+
"thicker_wall": ("thickness_mm", (3.0, 5.0)),
|
|
39
|
+
"hotter_melt": ("melt_temp_c", (260.0, 300.0)),
|
|
40
|
+
"warmer_mould": ("mould_temp_c", (60.0, 80.0)),
|
|
41
|
+
"weaker_contact": ("htc_w_m2k", (600.0, 1500.0)),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
_CODE_FILES = ("physics.py", "data.py")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def box_arrays(box: dict[str, tuple[float, float]]) -> tuple[np.ndarray, np.ndarray]:
|
|
48
|
+
lo = np.array([box[name][0] for name in physics.PARAM_NAMES])
|
|
49
|
+
hi = np.array([box[name][1] for name in physics.PARAM_NAMES])
|
|
50
|
+
return lo, hi
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def sha256_file(path: Path) -> str:
|
|
54
|
+
digest = hashlib.sha256()
|
|
55
|
+
with open(path, "rb") as fh:
|
|
56
|
+
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
|
57
|
+
digest.update(chunk)
|
|
58
|
+
return digest.hexdigest()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def code_hash() -> str:
|
|
62
|
+
"""SHA-256 over the solver and generator source, line endings normalised."""
|
|
63
|
+
digest = hashlib.sha256()
|
|
64
|
+
here = Path(__file__).parent
|
|
65
|
+
for name in _CODE_FILES:
|
|
66
|
+
digest.update(name.encode())
|
|
67
|
+
digest.update((here / name).read_bytes().replace(b"\r\n", b"\n"))
|
|
68
|
+
return digest.hexdigest()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _canonical(obj: object) -> bytes:
|
|
72
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def sample_inputs(config: dict) -> dict[str, np.ndarray]:
|
|
76
|
+
"""Parameter sets for every split. Training uses a Latin hypercube; the others plain uniform draws."""
|
|
77
|
+
lo, hi = box_arrays(TRAIN_BOX)
|
|
78
|
+
seed = int(config["seed"])
|
|
79
|
+
lhs = qmc.LatinHypercube(d=lo.size, seed=seed)
|
|
80
|
+
splits = {"train": lo + (hi - lo) * lhs.random(int(config["n_train"]))}
|
|
81
|
+
rng = np.random.default_rng(seed + 1)
|
|
82
|
+
splits["val"] = lo + (hi - lo) * rng.random((int(config["n_val"]), lo.size))
|
|
83
|
+
splits["test"] = lo + (hi - lo) * rng.random((int(config["n_test"]), lo.size))
|
|
84
|
+
n_ood = int(config["n_ood_per_shift"])
|
|
85
|
+
for group, (name, (a, b)) in OOD_SHIFTS.items():
|
|
86
|
+
x = lo + (hi - lo) * rng.random((n_ood, lo.size))
|
|
87
|
+
x[:, physics.PARAM_NAMES.index(name)] = rng.uniform(a, b, n_ood)
|
|
88
|
+
splits[f"ood_{group}"] = x
|
|
89
|
+
return splits
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def generate(config: dict, data_root: Path, log=print) -> Path:
|
|
93
|
+
"""Run the solver over every split, write the arrays and the manifest. Returns the dataset folder.
|
|
94
|
+
|
|
95
|
+
If a dataset with the same recipe already exists and its hashes check out, it is reused.
|
|
96
|
+
"""
|
|
97
|
+
recipe = {"sampling": config, "code_sha256": code_hash(), "box": TRAIN_BOX, "ood_shifts": OOD_SHIFTS}
|
|
98
|
+
recipe_hash = hashlib.sha256(_canonical(recipe)).hexdigest()
|
|
99
|
+
data_root.mkdir(parents=True, exist_ok=True)
|
|
100
|
+
for manifest_path in sorted(data_root.glob("*/manifest.json")):
|
|
101
|
+
manifest = json.loads(manifest_path.read_text())
|
|
102
|
+
if manifest.get("recipe_sha256") == recipe_hash:
|
|
103
|
+
verify(manifest_path.parent)
|
|
104
|
+
log(f"dataset {manifest['version']} already built from this recipe, hashes verified")
|
|
105
|
+
return manifest_path.parent
|
|
106
|
+
|
|
107
|
+
staging = data_root / f".staging-{recipe_hash[:12]}"
|
|
108
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
109
|
+
files: dict[str, dict] = {}
|
|
110
|
+
seconds: dict[str, float] = {}
|
|
111
|
+
for split, inputs in sample_inputs(config).items():
|
|
112
|
+
start = time.perf_counter()
|
|
113
|
+
sol = physics.solve(inputs)
|
|
114
|
+
seconds[split] = round(time.perf_counter() - start, 2)
|
|
115
|
+
log(f" {split}: {inputs.shape[0]} solver runs in {seconds[split]:.1f} s")
|
|
116
|
+
folder = staging / split
|
|
117
|
+
folder.mkdir(parents=True)
|
|
118
|
+
arrays = {"inputs": inputs, "t_cool": sol.t_cool, "field": sol.field, "heat": sol.heat}
|
|
119
|
+
for name in ARRAYS:
|
|
120
|
+
path = folder / f"{name}.npy"
|
|
121
|
+
np.save(path, np.ascontiguousarray(arrays[name], dtype=np.float64))
|
|
122
|
+
files[f"{split}/{name}.npy"] = {"sha256": sha256_file(path), "shape": list(arrays[name].shape)}
|
|
123
|
+
|
|
124
|
+
content_hash = hashlib.sha256(_canonical({k: v["sha256"] for k, v in files.items()})).hexdigest()
|
|
125
|
+
version = f"ds-{content_hash[:12]}"
|
|
126
|
+
manifest = {
|
|
127
|
+
"version": version,
|
|
128
|
+
"content_sha256": content_hash,
|
|
129
|
+
"recipe_sha256": recipe_hash,
|
|
130
|
+
"recipe": recipe,
|
|
131
|
+
"solver": {
|
|
132
|
+
"n_cells": physics.N_CELLS,
|
|
133
|
+
"dfo": physics.DFO,
|
|
134
|
+
"steps_to_eject": physics.STEPS_TO_EJECT,
|
|
135
|
+
"fractions": physics.FRACTIONS.tolist(),
|
|
136
|
+
"t_eject_c": physics.T_EJECT,
|
|
137
|
+
},
|
|
138
|
+
"splits": {s: int(np.load(staging / s / "inputs.npy").shape[0]) for s in sample_inputs(config)},
|
|
139
|
+
"files": files,
|
|
140
|
+
"solver_seconds": seconds,
|
|
141
|
+
}
|
|
142
|
+
(staging / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
|
143
|
+
target = data_root / version
|
|
144
|
+
shutil.rmtree(target, ignore_errors=True)
|
|
145
|
+
staging.rename(target)
|
|
146
|
+
return target
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def verify(dataset_dir: Path) -> dict:
|
|
150
|
+
"""Check every file against the manifest. Raises on any mismatch; returns the manifest."""
|
|
151
|
+
manifest = json.loads((dataset_dir / "manifest.json").read_text())
|
|
152
|
+
for rel, meta in manifest["files"].items():
|
|
153
|
+
actual = sha256_file(dataset_dir / rel)
|
|
154
|
+
if actual != meta["sha256"]:
|
|
155
|
+
raise ValueError(f"{dataset_dir.name}/{rel}: SHA-256 {actual[:12]} does not match the manifest")
|
|
156
|
+
content = hashlib.sha256(_canonical({k: v["sha256"] for k, v in manifest["files"].items()})).hexdigest()
|
|
157
|
+
if f"ds-{content[:12]}" != manifest["version"]:
|
|
158
|
+
raise ValueError(f"{dataset_dir.name}: the file hashes do not add up to version {manifest['version']}")
|
|
159
|
+
return manifest
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass(frozen=True)
|
|
163
|
+
class Split:
|
|
164
|
+
inputs: np.ndarray # (B, 6)
|
|
165
|
+
t_cool: np.ndarray # (B,)
|
|
166
|
+
field: np.ndarray # (B, F, N)
|
|
167
|
+
heat: np.ndarray # (B, F)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def load_split(dataset_dir: Path, split: str) -> Split:
|
|
171
|
+
arrays = {name: np.load(dataset_dir / split / f"{name}.npy") for name in ARRAYS}
|
|
172
|
+
return Split(**arrays)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def splits_of(manifest: dict, prefix: str = "") -> list[str]:
|
|
176
|
+
return [s for s in manifest["splits"] if s.startswith(prefix)]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Per-case errors against the solver, and the intervals reported around them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from scipy.stats import norm
|
|
7
|
+
|
|
8
|
+
from . import physics
|
|
9
|
+
from .data import Split
|
|
10
|
+
from .model import Prediction
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def errors(pred: Prediction, truth: Split) -> dict[str, np.ndarray]:
|
|
14
|
+
"""One value per case."""
|
|
15
|
+
case = physics.Case.from_params(truth.inputs)
|
|
16
|
+
diff = pred.field - truth.field
|
|
17
|
+
return {
|
|
18
|
+
"t_cool_rel_error": np.abs(pred.t_cool - truth.t_cool) / truth.t_cool,
|
|
19
|
+
"field_rmse_k": np.sqrt(np.mean(diff**2, axis=(1, 2))),
|
|
20
|
+
"field_max_error_k": np.abs(diff).max(axis=(1, 2)),
|
|
21
|
+
"heat_error_frac": np.abs(pred.heat - truth.heat).max(axis=1) / physics.removable_heat(case),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def p95(values: np.ndarray, axis: int | None = None) -> np.ndarray:
|
|
26
|
+
return np.percentile(values, 95, axis=axis)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def bootstrap(values: np.ndarray, stat: str, n_boot: int, seed: int, level: float = 0.95) -> dict:
|
|
30
|
+
"""Point estimate and percentile-bootstrap interval of the mean or the 95th percentile."""
|
|
31
|
+
fn = {"mean": np.mean, "p95": p95}[stat]
|
|
32
|
+
rng = np.random.default_rng(seed)
|
|
33
|
+
idx = rng.integers(0, len(values), size=(n_boot, len(values)))
|
|
34
|
+
boots = fn(values[idx], axis=1)
|
|
35
|
+
alpha = (1.0 - level) / 2.0
|
|
36
|
+
return {
|
|
37
|
+
"value": float(fn(values)),
|
|
38
|
+
"low": float(np.quantile(boots, alpha)),
|
|
39
|
+
"high": float(np.quantile(boots, 1.0 - alpha)),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def wilson(failures: int, n: int, level: float = 0.95) -> dict:
|
|
44
|
+
"""Wilson score interval for a rate (here: the share of cases that violate a check)."""
|
|
45
|
+
z = norm.ppf(1.0 - (1.0 - level) / 2.0)
|
|
46
|
+
p = failures / n
|
|
47
|
+
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
|
|
48
|
+
half = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
|
|
49
|
+
return {"value": p, "low": float(max(0.0, centre - half)), "high": float(min(1.0, centre + half)), "n": n}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def summarise(errs: dict[str, np.ndarray], n_boot: int, seed: int) -> dict:
|
|
53
|
+
return {
|
|
54
|
+
"n": len(errs["t_cool_rel_error"]),
|
|
55
|
+
"t_cool_rel_error_mean": bootstrap(errs["t_cool_rel_error"], "mean", n_boot, seed),
|
|
56
|
+
"t_cool_rel_error_p95": bootstrap(errs["t_cool_rel_error"], "p95", n_boot, seed),
|
|
57
|
+
"field_rmse_k_mean": bootstrap(errs["field_rmse_k"], "mean", n_boot, seed),
|
|
58
|
+
"field_max_error_k_p95": bootstrap(errs["field_max_error_k"], "p95", n_boot, seed),
|
|
59
|
+
"heat_error_frac_mean": bootstrap(errs["heat_error_frac"], "mean", n_boot, seed),
|
|
60
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""The surrogate: a small MLP from the six process parameters to the solver's outputs.
|
|
2
|
+
|
|
3
|
+
Targets are scaled so that the network never has to learn units:
|
|
4
|
+
* cooling time as log(seconds), standardised;
|
|
5
|
+
* the profiles as theta = (T - T_mould) / (T_melt - T_mould), which runs from 1 (melt) to 0 (mould);
|
|
6
|
+
* the heat removed as a fraction of the heat a wall can give off between melt and mould temperature.
|
|
7
|
+
The conversion back to physical units uses the inputs, so bounds such as 'never colder than the
|
|
8
|
+
mould' are easy to express but are not forced by the architecture; the gate checks them.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import warnings
|
|
15
|
+
from dataclasses import asdict, dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import torch
|
|
20
|
+
from torch import nn
|
|
21
|
+
|
|
22
|
+
from . import data, physics
|
|
23
|
+
|
|
24
|
+
N_FRACTIONS = physics.FRACTIONS.size
|
|
25
|
+
N_NODES = physics.N_CELLS + 1
|
|
26
|
+
N_OUT = 1 + N_FRACTIONS * N_NODES + N_FRACTIONS
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class ModelMeta:
|
|
31
|
+
"""Everything needed to rebuild and use a saved model, stored next to its weights."""
|
|
32
|
+
|
|
33
|
+
hidden: int
|
|
34
|
+
depth: int
|
|
35
|
+
box_lo: list[float]
|
|
36
|
+
box_hi: list[float]
|
|
37
|
+
log_t_mean: float
|
|
38
|
+
log_t_std: float
|
|
39
|
+
dataset_version: str
|
|
40
|
+
quantized: bool = False
|
|
41
|
+
|
|
42
|
+
def save(self, folder: Path) -> None:
|
|
43
|
+
(folder / "model.json").write_text(json.dumps(asdict(self), indent=2) + "\n")
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def load(cls, folder: Path) -> ModelMeta:
|
|
47
|
+
return cls(**json.loads((folder / "model.json").read_text()))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Surrogate(nn.Module):
|
|
51
|
+
def __init__(self, hidden: int, depth: int):
|
|
52
|
+
super().__init__()
|
|
53
|
+
layers: list[nn.Module] = []
|
|
54
|
+
width = len(physics.PARAM_NAMES)
|
|
55
|
+
for _ in range(depth):
|
|
56
|
+
layers += [nn.Linear(width, hidden), nn.SiLU()]
|
|
57
|
+
width = hidden
|
|
58
|
+
layers.append(nn.Linear(width, N_OUT))
|
|
59
|
+
self.net = nn.Sequential(*layers)
|
|
60
|
+
|
|
61
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
62
|
+
return self.net(x)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def scale_inputs(params: np.ndarray, meta: ModelMeta) -> np.ndarray:
|
|
66
|
+
lo, hi = np.asarray(meta.box_lo), np.asarray(meta.box_hi)
|
|
67
|
+
return 2.0 * (params - lo) / (hi - lo) - 1.0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def make_targets(split: data.Split, meta: ModelMeta) -> np.ndarray:
|
|
71
|
+
case = physics.Case.from_params(split.inputs)
|
|
72
|
+
log_t = (np.log(split.t_cool) - meta.log_t_mean) / meta.log_t_std
|
|
73
|
+
span = (case.t_melt - case.t_mould)[:, None, None]
|
|
74
|
+
theta = (split.field - case.t_mould[:, None, None]) / span
|
|
75
|
+
heat = split.heat / physics.removable_heat(case)[:, None]
|
|
76
|
+
return np.concatenate([log_t[:, None], theta.reshape(len(theta), -1), heat], axis=1)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class Prediction:
|
|
81
|
+
t_cool: np.ndarray # (B,) s
|
|
82
|
+
field: np.ndarray # (B, F, N) C
|
|
83
|
+
heat: np.ndarray # (B, F) J/m^2
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def to_physical(raw: np.ndarray, params: np.ndarray, meta: ModelMeta) -> Prediction:
|
|
87
|
+
case = physics.Case.from_params(params)
|
|
88
|
+
t_cool = np.exp(raw[:, 0] * meta.log_t_std + meta.log_t_mean)
|
|
89
|
+
theta = raw[:, 1 : 1 + N_FRACTIONS * N_NODES].reshape(-1, N_FRACTIONS, N_NODES)
|
|
90
|
+
field = case.t_mould[:, None, None] + theta * (case.t_melt - case.t_mould)[:, None, None]
|
|
91
|
+
heat = raw[:, 1 + N_FRACTIONS * N_NODES :] * physics.removable_heat(case)[:, None]
|
|
92
|
+
return Prediction(t_cool=t_cool, field=field, heat=heat)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def predict(model: nn.Module, meta: ModelMeta, params: np.ndarray) -> Prediction:
|
|
96
|
+
params = np.atleast_2d(np.asarray(params, dtype=np.float64))
|
|
97
|
+
x = torch.as_tensor(scale_inputs(params, meta), dtype=torch.float32)
|
|
98
|
+
with torch.inference_mode():
|
|
99
|
+
raw = model(x).double().numpy()
|
|
100
|
+
return to_physical(raw, params, meta)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def quantize_int8(model: nn.Module, hidden_only: bool = False, per_channel: bool = False) -> nn.Module:
|
|
104
|
+
"""Dynamic int8 quantisation: int8 weights, activations quantised on the fly in every call.
|
|
105
|
+
|
|
106
|
+
The default (every Linear layer, one scale per weight tensor) is the registered int8 version.
|
|
107
|
+
`hidden_only` keeps the output layer in float32; `per_channel` gives each output row its own scale.
|
|
108
|
+
|
|
109
|
+
torch.ao.quantization is deprecated in favour of torchao, but still ships with torch 2.15 and
|
|
110
|
+
runs on any CPU without extra packages; the warnings are silenced here and noted in the README.
|
|
111
|
+
"""
|
|
112
|
+
with warnings.catch_warnings():
|
|
113
|
+
warnings.simplefilter("ignore")
|
|
114
|
+
from torch.ao.quantization import default_dynamic_qconfig, per_channel_dynamic_qconfig, quantize_dynamic
|
|
115
|
+
|
|
116
|
+
qconfig = per_channel_dynamic_qconfig if per_channel else default_dynamic_qconfig
|
|
117
|
+
linear = [name for name, mod in model.named_modules() if isinstance(mod, nn.Linear)]
|
|
118
|
+
if hidden_only:
|
|
119
|
+
linear = linear[:-1]
|
|
120
|
+
return quantize_dynamic(model, {name: qconfig for name in linear}, dtype=torch.qint8)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def save(model: nn.Module, meta: ModelMeta, folder: Path) -> None:
|
|
124
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
125
|
+
torch.save(model.state_dict(), folder / "weights.pt")
|
|
126
|
+
meta.save(folder)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def load(folder: Path) -> tuple[nn.Module, ModelMeta]:
|
|
130
|
+
meta = ModelMeta.load(folder)
|
|
131
|
+
model = Surrogate(meta.hidden, meta.depth)
|
|
132
|
+
if meta.quantized:
|
|
133
|
+
model = quantize_int8(model)
|
|
134
|
+
with warnings.catch_warnings():
|
|
135
|
+
warnings.simplefilter("ignore")
|
|
136
|
+
model.load_state_dict(torch.load(folder / "weights.pt", weights_only=True))
|
|
137
|
+
model.eval()
|
|
138
|
+
return model, meta
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Monitoring: flag inputs outside the training box, and measure live error from the request log.
|
|
2
|
+
|
|
3
|
+
The service calls `out_of_box` on every request. Offline, `report` reads the service's request log
|
|
4
|
+
and answers three questions:
|
|
5
|
+
* how much traffic falls outside what the model was trained on, and along which parameter;
|
|
6
|
+
* how far off the surrogate is on the traffic it did answer (a sample is re-run with the solver);
|
|
7
|
+
* how far off it would have been on the traffic it did not answer (the service computes the
|
|
8
|
+
surrogate's answer for flagged requests too, logs it, and returns the solver's).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
from collections import Counter
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from . import metrics, physics
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def out_of_box(params: np.ndarray, lo: np.ndarray, hi: np.ndarray) -> list[list[str]]:
|
|
23
|
+
"""For each case, the names of the parameters outside [lo, hi]."""
|
|
24
|
+
params = np.atleast_2d(params)
|
|
25
|
+
outside = (params < lo) | (params > hi)
|
|
26
|
+
return [[physics.PARAM_NAMES[j] for j in np.flatnonzero(row)] for row in outside]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def read_log(path: Path) -> list[dict]:
|
|
30
|
+
with open(path, encoding="utf-8") as fh:
|
|
31
|
+
return [json.loads(line) for line in fh if line.strip()]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def report(log_path: Path, sample_size: int, seed: int, n_boot: int, alerts_policy: dict) -> dict:
|
|
35
|
+
records = read_log(log_path)
|
|
36
|
+
n = len(records)
|
|
37
|
+
served = Counter(r["source"] for r in records)
|
|
38
|
+
reasons = Counter(r["fallback_reason"] for r in records if r["fallback_reason"])
|
|
39
|
+
by_feature = Counter(f for r in records for f in r["out_of_box"])
|
|
40
|
+
ood_rate = metrics.wilson(sum(bool(r["out_of_box"]) for r in records), n)
|
|
41
|
+
|
|
42
|
+
# Shadow evaluation: re-run the solver on a sample of the answers the surrogate gave.
|
|
43
|
+
answered = [r for r in records if r["source"] == "surrogate"]
|
|
44
|
+
rng = np.random.default_rng(seed)
|
|
45
|
+
pick = rng.choice(len(answered), size=min(sample_size, len(answered)), replace=False)
|
|
46
|
+
sample = [answered[i] for i in sorted(pick)]
|
|
47
|
+
shadow: dict = {"sampled": len(sample)}
|
|
48
|
+
if sample:
|
|
49
|
+
params = np.array([[r["inputs"][k] for k in physics.PARAM_NAMES] for r in sample])
|
|
50
|
+
truth = physics.solve(params).t_cool
|
|
51
|
+
err = np.abs(np.array([r["t_cool_s"] for r in sample]) - truth) / truth
|
|
52
|
+
shadow["t_cool_rel_error_mean"] = metrics.bootstrap(err, "mean", n_boot, seed)
|
|
53
|
+
shadow["t_cool_rel_error_p95"] = metrics.bootstrap(err, "p95", n_boot, seed)
|
|
54
|
+
|
|
55
|
+
# Fallbacks: the solver answered; the logged surrogate value shows the error that was avoided.
|
|
56
|
+
avoided: dict = {}
|
|
57
|
+
for reason in sorted(reasons):
|
|
58
|
+
rows = [r for r in records if r["fallback_reason"] == reason]
|
|
59
|
+
err = np.array([abs(r["surrogate_t_cool_s"] - r["t_cool_s"]) / r["t_cool_s"] for r in rows])
|
|
60
|
+
avoided[reason] = {
|
|
61
|
+
"n": len(rows),
|
|
62
|
+
"t_cool_rel_error_mean": metrics.bootstrap(err, "mean", n_boot, seed),
|
|
63
|
+
"t_cool_rel_error_p95": metrics.bootstrap(err, "p95", n_boot, seed),
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
alerts = []
|
|
67
|
+
if ood_rate["low"] > alerts_policy["max_out_of_box_rate"]:
|
|
68
|
+
alerts.append(
|
|
69
|
+
f"out-of-box traffic {100 * ood_rate['value']:.1f} % (95 % CI from {100 * ood_rate['low']:.1f} %) "
|
|
70
|
+
f"is above {100 * alerts_policy['max_out_of_box_rate']:.0f} %; most often outside: "
|
|
71
|
+
+ ", ".join(f"{k} ({v})" for k, v in by_feature.most_common(3))
|
|
72
|
+
)
|
|
73
|
+
if sample and shadow["t_cool_rel_error_p95"]["low"] > alerts_policy["max_shadow_t_cool_rel_error_p95"]:
|
|
74
|
+
alerts.append("live cooling-time error on answered traffic is above the gate threshold")
|
|
75
|
+
|
|
76
|
+
latency = {src: float(np.median([r["latency_ms"] for r in records if r["source"] == src])) for src in served}
|
|
77
|
+
return {
|
|
78
|
+
"requests": n,
|
|
79
|
+
"served_by": dict(served),
|
|
80
|
+
"fallback_reasons": dict(reasons),
|
|
81
|
+
"out_of_box_rate": ood_rate,
|
|
82
|
+
"out_of_box_by_feature": dict(by_feature.most_common()),
|
|
83
|
+
"median_latency_ms": latency,
|
|
84
|
+
"shadow_on_answered": shadow,
|
|
85
|
+
"surrogate_error_avoided_by_fallback": avoided,
|
|
86
|
+
"alerts": alerts,
|
|
87
|
+
}
|