SQuADDS ML API 2: squadds ec4414d6, registry 1dbf099a
Browse files- Dockerfile +1 -1
- app.py +5 -0
- bundle.lock.json +2 -2
- squadds_ml_api/api.py +15 -0
- src/squadds/ml/capacitance/__init__.py +2 -2
- src/squadds/ml/capacitance/_core/SOURCES.json +6 -6
- src/squadds/ml/capacitance/_core/_tlsq/embed/proxy.py +102 -3
- src/squadds/ml/capacitance/_core/fastprior_pkg.py +9 -3
- src/squadds/ml/capacitance/_core/paper.py +72 -2
- src/squadds/ml/capacitance/_runtime.py +1 -1
- src/squadds/ml/capacitance/benchmark.py +3 -1
- src/squadds/ml/capacitance/contribute.py +12 -8
- src/squadds/ml/capacitance/dataset.py +7 -7
- src/squadds/ml/capacitance/manifest.json +1 -1
- src/squadds/ml/capacitance/models.py +1 -1
- src/squadds/ml/capacitance/predictor.py +21 -2
- src/squadds/ml/capacitance/priors.py +3 -3
- src/squadds/ml/capacitance/qc.py +2 -2
- src/squadds/ml/capacitance/serving.py +3 -1
- src/squadds/ml/capacitance/slurm.py +1 -1
- src/squadds/ml/capacitance/train.py +9 -4
- src/squadds/ml/capacitance/training_data.py +12 -12
- src/squadds/ml/client.py +6 -2
- tests/test_v1.py +4 -0
Dockerfile
CHANGED
|
@@ -7,7 +7,7 @@ RUN useradd -m -u 1000 user
|
|
| 7 |
USER user
|
| 8 |
ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH PYTHONUNBUFFERED=1 PYTHONPATH=/home/user/app/src \
|
| 9 |
KERAS_BACKEND=torch NUMBA_CPU_NAME=generic NUMBA_CACHE_DIR=/home/user/app/numba_cache \
|
| 10 |
-
SQUADDS_ML_API_EXIT_ON_LOAD_FAILURE=1
|
| 11 |
WORKDIR /home/user/app
|
| 12 |
COPY --chown=user requirements.txt .
|
| 13 |
RUN pip install --no-cache-dir --user -r requirements.txt
|
|
|
|
| 7 |
USER user
|
| 8 |
ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH PYTHONUNBUFFERED=1 PYTHONPATH=/home/user/app/src \
|
| 9 |
KERAS_BACKEND=torch NUMBA_CPU_NAME=generic NUMBA_CACHE_DIR=/home/user/app/numba_cache \
|
| 10 |
+
SQUADDS_ML_API_EXIT_ON_LOAD_FAILURE=1 OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 MKL_NUM_THREADS=2
|
| 11 |
WORKDIR /home/user/app
|
| 12 |
COPY --chown=user requirements.txt .
|
| 13 |
RUN pip install --no-cache-dir --user -r requirements.txt
|
app.py
CHANGED
|
@@ -1,7 +1,12 @@
|
|
| 1 |
import logging
|
|
|
|
| 2 |
from pathlib import Path
|
| 3 |
|
|
|
|
|
|
|
| 4 |
from squadds_ml_api.api import create_app
|
| 5 |
|
|
|
|
|
|
|
| 6 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
| 7 |
app = create_app(Path(__file__).resolve().parent)
|
|
|
|
| 1 |
import logging
|
| 2 |
+
import os
|
| 3 |
from pathlib import Path
|
| 4 |
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
from squadds_ml_api.api import create_app
|
| 8 |
|
| 9 |
+
torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", 2)))
|
| 10 |
+
|
| 11 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
| 12 |
app = create_app(Path(__file__).resolve().parent)
|
bundle.lock.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
{
|
| 2 |
-
"built_at": "2026-11-
|
| 3 |
"squadds": {
|
| 4 |
-
"commit": "
|
| 5 |
"dirty": false,
|
| 6 |
"dirty_files": []
|
| 7 |
},
|
|
|
|
| 1 |
{
|
| 2 |
+
"built_at": "2026-11-15T23:34:38+00:00",
|
| 3 |
"squadds": {
|
| 4 |
+
"commit": "ec4414d630e6499c749f4e986d5ade887bc2001d",
|
| 5 |
"dirty": false,
|
| 6 |
"dirty_files": []
|
| 7 |
},
|
squadds_ml_api/api.py
CHANGED
|
@@ -29,6 +29,7 @@ from .usage import Usage, keyed
|
|
| 29 |
log = logging.getLogger("squadds_ml_api")
|
| 30 |
SERVICE = "SQuADDS ML API"
|
| 31 |
MB = 2**20
|
|
|
|
| 32 |
REFUSAL = {400: "invalid_input", 422: "invalid_input", 401: "auth", 403: "auth", 404: "unknown_model", 413: "size",
|
| 33 |
429: "rate_limited", 503: "unavailable"}
|
| 34 |
|
|
@@ -406,6 +407,7 @@ def create_app(root: Path, registry_file: Path | None = None, load: bool = True)
|
|
| 406 |
raise ApiError(400, "invalid_input", "inputs.file_base64 is not valid base64", model_id) from exc
|
| 407 |
if not isinstance(options, dict):
|
| 408 |
raise ApiError(422, "validation_error", "options must be an object", model_id)
|
|
|
|
| 409 |
if data is not None and len(data) > max_bytes:
|
| 410 |
raise ApiError(413, "too_large", f"file larger than {max_bytes // MB} MB", model_id)
|
| 411 |
out = await run_in_threadpool(run_predict, m, inputs, options, data)
|
|
@@ -473,5 +475,18 @@ def create_app(root: Path, registry_file: Path | None = None, load: bool = True)
|
|
| 473 |
return app
|
| 474 |
|
| 475 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
def jsonable(x):
|
| 477 |
return json.loads(json.dumps(x, default=str))
|
|
|
|
| 29 |
log = logging.getLogger("squadds_ml_api")
|
| 30 |
SERVICE = "SQuADDS ML API"
|
| 31 |
MB = 2**20
|
| 32 |
+
MIN_THICKNESS_UM = 1.0
|
| 33 |
REFUSAL = {400: "invalid_input", 422: "invalid_input", 401: "auth", 403: "auth", 404: "unknown_model", 413: "size",
|
| 34 |
429: "rate_limited", 503: "unavailable"}
|
| 35 |
|
|
|
|
| 407 |
raise ApiError(400, "invalid_input", "inputs.file_base64 is not valid base64", model_id) from exc
|
| 408 |
if not isinstance(options, dict):
|
| 409 |
raise ApiError(422, "validation_error", "options must be an object", model_id)
|
| 410 |
+
check_thickness(m, inputs)
|
| 411 |
if data is not None and len(data) > max_bytes:
|
| 412 |
raise ApiError(413, "too_large", f"file larger than {max_bytes // MB} MB", model_id)
|
| 413 |
out = await run_in_threadpool(run_predict, m, inputs, options, data)
|
|
|
|
| 475 |
return app
|
| 476 |
|
| 477 |
|
| 478 |
+
def check_thickness(m: Model, inputs) -> None:
|
| 479 |
+
"""Capacitance models: substrates thinner than MIN_THICKNESS_UM are refused before any solve."""
|
| 480 |
+
if m.spec.get("family") != "planar_capacitance" or not isinstance(inputs, dict) or inputs.get("thickness_um") is None:
|
| 481 |
+
return
|
| 482 |
+
try:
|
| 483 |
+
t = float(inputs["thickness_um"])
|
| 484 |
+
except (TypeError, ValueError):
|
| 485 |
+
return
|
| 486 |
+
if not t >= MIN_THICKNESS_UM:
|
| 487 |
+
raise ApiError(400, "invalid_input", f"thickness_um must be at least {MIN_THICKNESS_UM:g} (got {inputs['thickness_um']!r}); "
|
| 488 |
+
"the models are tested on substrates of 10-1000 um", m.id)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
def jsonable(x):
|
| 492 |
return json.loads(json.dumps(x, default=str))
|
src/squadds/ml/capacitance/__init__.py
CHANGED
|
@@ -4,7 +4,7 @@
|
|
| 4 |
res = CapacitancePredictor(load_model("flagship")).predict("chip.gds")
|
| 5 |
res.names, res.matrix_fF, res.to_sim_results()
|
| 6 |
|
| 7 |
-
Models: ``flagship`` (the default) and ``fast``, both trained on all data. Physics priors: ``
|
| 8 |
"""
|
| 9 |
|
| 10 |
from __future__ import annotations
|
|
@@ -21,7 +21,7 @@ _EXPORTS = {
|
|
| 21 |
"list_models": "models",
|
| 22 |
"load_model": "models",
|
| 23 |
"PriorResult": "priors",
|
| 24 |
-
"
|
| 25 |
"optimized_physics_prior": "priors",
|
| 26 |
"prepare_layout": "_runtime",
|
| 27 |
"inspect_layout": "_runtime",
|
|
|
|
| 4 |
res = CapacitancePredictor(load_model("flagship")).predict("chip.gds")
|
| 5 |
res.names, res.matrix_fF, res.to_sim_results()
|
| 6 |
|
| 7 |
+
Models: ``flagship`` (the default) and ``fast``, both trained on all data. Physics priors: ``physics_prior`` and ``optimized_physics_prior``.
|
| 8 |
"""
|
| 9 |
|
| 10 |
from __future__ import annotations
|
|
|
|
| 21 |
"list_models": "models",
|
| 22 |
"load_model": "models",
|
| 23 |
"PriorResult": "priors",
|
| 24 |
+
"physics_prior": "priors",
|
| 25 |
"optimized_physics_prior": "priors",
|
| 26 |
"prepare_layout": "_runtime",
|
| 27 |
"inspect_layout": "_runtime",
|
src/squadds/ml/capacitance/_core/SOURCES.json
CHANGED
|
@@ -33,8 +33,8 @@
|
|
| 33 |
},
|
| 34 |
"paper.py": {
|
| 35 |
"source": "deploy/geomgnn/src/geomgnn/paper.py",
|
| 36 |
-
"source_sha256": "
|
| 37 |
-
"sha256": "
|
| 38 |
"rewrites": [
|
| 39 |
{
|
| 40 |
"pattern": "from tlsq_infer\\.layout import prepare",
|
|
@@ -112,8 +112,8 @@
|
|
| 112 |
},
|
| 113 |
"fastprior_pkg.py": {
|
| 114 |
"source": "deploy/geomgnn/src/geomgnn/fastprior_pkg.py",
|
| 115 |
-
"source_sha256": "
|
| 116 |
-
"sha256": "
|
| 117 |
"rewrites": [
|
| 118 |
{
|
| 119 |
"pattern": "from geomgnn\\._tlsq",
|
|
@@ -289,8 +289,8 @@
|
|
| 289 |
},
|
| 290 |
"_tlsq/embed/proxy.py": {
|
| 291 |
"source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/proxy.py",
|
| 292 |
-
"source_sha256": "
|
| 293 |
-
"sha256": "
|
| 294 |
"rewrites": [],
|
| 295 |
"upstream": {
|
| 296 |
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/proxy.py",
|
|
|
|
| 33 |
},
|
| 34 |
"paper.py": {
|
| 35 |
"source": "deploy/geomgnn/src/geomgnn/paper.py",
|
| 36 |
+
"source_sha256": "ff85b10abc4d520f86b7d84bcfdc9ea02dd9cf6b140b3858ae170bbca0393020",
|
| 37 |
+
"sha256": "26c5fa3618b76f1a0a3e589a3ed5b1113f549494280c06a5b4cf7a92dc4ce42d",
|
| 38 |
"rewrites": [
|
| 39 |
{
|
| 40 |
"pattern": "from tlsq_infer\\.layout import prepare",
|
|
|
|
| 112 |
},
|
| 113 |
"fastprior_pkg.py": {
|
| 114 |
"source": "deploy/geomgnn/src/geomgnn/fastprior_pkg.py",
|
| 115 |
+
"source_sha256": "4fff680f35cb8b098de6c9b1b6fc55780064362ffc829bb47bf69a77454ce38a",
|
| 116 |
+
"sha256": "258d28da16e7cdbe5e74e1b1875e6e11ed2dda8c0be63f20178348053efd6175",
|
| 117 |
"rewrites": [
|
| 118 |
{
|
| 119 |
"pattern": "from geomgnn\\._tlsq",
|
|
|
|
| 289 |
},
|
| 290 |
"_tlsq/embed/proxy.py": {
|
| 291 |
"source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/proxy.py",
|
| 292 |
+
"source_sha256": "f87a0f1614ca93b73aac0747d0acdafbd9b8c243f69c68c98d8919e158a57b28",
|
| 293 |
+
"sha256": "f87a0f1614ca93b73aac0747d0acdafbd9b8c243f69c68c98d8919e158a57b28",
|
| 294 |
"rewrites": [],
|
| 295 |
"upstream": {
|
| 296 |
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/proxy.py",
|
src/squadds/ml/capacitance/_core/_tlsq/embed/proxy.py
CHANGED
|
@@ -17,6 +17,7 @@ from __future__ import annotations
|
|
| 17 |
import os
|
| 18 |
import queue
|
| 19 |
import threading
|
|
|
|
| 20 |
from concurrent.futures import ThreadPoolExecutor
|
| 21 |
from functools import partial
|
| 22 |
|
|
@@ -440,8 +441,97 @@ def _near_pairs(c, hm):
|
|
| 440 |
|
| 441 |
|
| 442 |
SUBSTRATE = {"model": "slab_open", "t_um": 350.0} # MoM Green's function (PRIOR_SCHEME.md 14.6): "slab_open" (default since 2026-10-10: 350 um substrate, vacuum below), "halfspace" (released models' priors), "slab_pec"
|
| 443 |
-
_IMG_CACHE:
|
| 444 |
_IMG_GRID: dict = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
|
| 446 |
|
| 447 |
class substrate:
|
|
@@ -474,7 +564,9 @@ def _image_correction(d, eps_r: float, exact: bool = False):
|
|
| 474 |
if m == "halfspace":
|
| 475 |
return None
|
| 476 |
key = (m, float(SUBSTRATE["t_um"]), float(eps_r))
|
| 477 |
-
if key
|
|
|
|
|
|
|
| 478 |
K, t = (eps_r - 1) / (eps_r + 1), float(SUBSTRATE["t_um"])
|
| 479 |
n = np.arange(1, 400)
|
| 480 |
nmax = int(np.argmax(K ** (2 * n) < 1e-4)) + 1
|
|
@@ -486,13 +578,20 @@ def _image_correction(d, eps_r: float, exact: bool = False):
|
|
| 486 |
w, D = np.r_[w, total - w.sum()], np.r_[2 * n * t, 2 * (nmax + 1) * t]
|
| 487 |
du = t / 1000
|
| 488 |
u = np.arange(0.0, 1e5 + 2 * du, du)
|
| 489 |
-
T =
|
|
|
|
|
|
|
|
|
|
| 490 |
_IMG_CACHE[key] = (du, T, w, D)
|
|
|
|
| 491 |
du, T = _IMG_CACHE[key][:2]
|
| 492 |
if exact:
|
| 493 |
w, D = _IMG_CACHE[key][2:]
|
| 494 |
d2 = np.asarray(d, float) ** 2
|
| 495 |
return sum(wn / np.sqrt(d2 + Dn * Dn) for wn, Dn in zip(w, D))
|
|
|
|
|
|
|
|
|
|
| 496 |
if key not in _IMG_GRID:
|
| 497 |
_IMG_GRID[key] = du * np.arange(len(T))
|
| 498 |
return np.interp(d, _IMG_GRID[key], T)
|
|
|
|
| 17 |
import os
|
| 18 |
import queue
|
| 19 |
import threading
|
| 20 |
+
from collections import OrderedDict
|
| 21 |
from concurrent.futures import ThreadPoolExecutor
|
| 22 |
from functools import partial
|
| 23 |
|
|
|
|
| 441 |
|
| 442 |
|
| 443 |
SUBSTRATE = {"model": "slab_open", "t_um": 350.0} # MoM Green's function (PRIOR_SCHEME.md 14.6): "slab_open" (default since 2026-10-10: 350 um substrate, vacuum below), "halfspace" (released models' priors), "slab_pec"
|
| 444 |
+
_IMG_CACHE: OrderedDict = OrderedDict() # LRU of image tables (model, t_um, eps_r) -> (du, T, w, D)
|
| 445 |
_IMG_GRID: dict = {}
|
| 446 |
+
_IMG_KEEP = (4, 512 << 20) # at most 4 tables and 512 MB (the newest is always kept)
|
| 447 |
+
_INTERP: dict = {}
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _img_evict():
|
| 451 |
+
while len(_IMG_CACHE) > 1 and (len(_IMG_CACHE) > _IMG_KEEP[0] or sum(v[1].nbytes for v in _IMG_CACHE.values())
|
| 452 |
+
+ sum(g.nbytes for g in _IMG_GRID.values()) > _IMG_KEEP[1]):
|
| 453 |
+
_IMG_GRID.pop(_IMG_CACHE.popitem(last=False)[0], None)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
try: # compiled np.interp on the uniform image table (_interp_uniform)
|
| 457 |
+
import numba as _nb
|
| 458 |
+
from numba.core import types as _nbt
|
| 459 |
+
from numba.extending import intrinsic as _intrinsic
|
| 460 |
+
|
| 461 |
+
@_intrinsic
|
| 462 |
+
def _fma(typingctx, a, b, c):
|
| 463 |
+
def gen(context, builder, sig, args):
|
| 464 |
+
return builder.fma(*args)
|
| 465 |
+
return _nbt.float64(_nbt.float64, _nbt.float64, _nbt.float64), gen
|
| 466 |
+
|
| 467 |
+
@_nb.njit(nogil=True, cache=True)
|
| 468 |
+
def _interp_run(x, du, fp, out, fused):
|
| 469 |
+
"""numpy's arr_interp on xp_j = du * j: the index by division, corrected with numpy's comparisons, then numpy's slope
|
| 470 |
+
and slope * (x - xp_j) + fp_j, plain or fused (fma) as this numpy build's C compiler does it."""
|
| 471 |
+
n = fp.shape[0]
|
| 472 |
+
last = du * (n - 1)
|
| 473 |
+
for i in range(x.shape[0]):
|
| 474 |
+
v = x[i]
|
| 475 |
+
if v != v:
|
| 476 |
+
out[i] = v
|
| 477 |
+
continue
|
| 478 |
+
if v > last:
|
| 479 |
+
out[i] = fp[n - 1]
|
| 480 |
+
continue
|
| 481 |
+
if v < 0.0:
|
| 482 |
+
out[i] = fp[0]
|
| 483 |
+
continue
|
| 484 |
+
j = min(int(v / du), n - 1)
|
| 485 |
+
while j > 0 and du * j > v:
|
| 486 |
+
j -= 1
|
| 487 |
+
while j < n - 1 and du * (j + 1) <= v:
|
| 488 |
+
j += 1
|
| 489 |
+
xj = du * j
|
| 490 |
+
if j == n - 1 or xj == v:
|
| 491 |
+
out[i] = fp[j]
|
| 492 |
+
continue
|
| 493 |
+
x1 = du * (j + 1)
|
| 494 |
+
s = (fp[j + 1] - fp[j]) / (x1 - xj)
|
| 495 |
+
r = _fma(s, v - xj, fp[j]) if fused else s * (v - xj) + fp[j]
|
| 496 |
+
if r != r:
|
| 497 |
+
r = _fma(s, v - x1, fp[j + 1]) if fused else s * (v - x1) + fp[j + 1]
|
| 498 |
+
if r != r and fp[j] == fp[j + 1]:
|
| 499 |
+
r = fp[j]
|
| 500 |
+
out[i] = r
|
| 501 |
+
except ImportError:
|
| 502 |
+
_interp_run = None
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def _interp_uniform(d, du, T):
|
| 506 |
+
"""np.interp(d, du * arange(len(T)), T), bit for bit: the compiled kernel (plain or fused multiply-add, whichever matches this
|
| 507 |
+
numpy build) when a probe at first use matches np.interp bit for bit, else None (the caller uses np.interp)."""
|
| 508 |
+
if "fn" not in _INTERP:
|
| 509 |
+
_INTERP["fn"] = None
|
| 510 |
+
if _interp_run is not None:
|
| 511 |
+
try:
|
| 512 |
+
rng, ok = np.random.default_rng(0), []
|
| 513 |
+
for fp in (rng.normal(size=4096), T): # a rough table tells the two apart, then the real one
|
| 514 |
+
xp = du * np.arange(len(fp))
|
| 515 |
+
x = np.concatenate([rng.uniform(-1, 1.01 * xp[-1], 50000), rng.uniform(0, 64 * du, 20000), xp[rng.integers(0, len(fp), 2000)],
|
| 516 |
+
np.nextafter(xp[rng.integers(1, len(fp), 2000)], 0), xp[[0, -1]], [np.nan, np.inf, 1e300]])
|
| 517 |
+
ref, got = np.interp(x, xp, fp).tobytes(), []
|
| 518 |
+
for fused in (False, True):
|
| 519 |
+
y = np.empty_like(x)
|
| 520 |
+
_interp_run(x, du, fp, y, fused)
|
| 521 |
+
got.append(y.tobytes())
|
| 522 |
+
ok.append([g == ref for g in got])
|
| 523 |
+
if ok[0][0] != ok[0][1] and ok[1][ok[0][1]]:
|
| 524 |
+
_INTERP["fn"] = ok[0][1]
|
| 525 |
+
except Exception: # noqa: BLE001 (llvm.fma or the compile unavailable: np.interp)
|
| 526 |
+
pass
|
| 527 |
+
fused = _INTERP["fn"]
|
| 528 |
+
d = np.asarray(d, float)
|
| 529 |
+
if fused is None or d.ndim == 0:
|
| 530 |
+
return None
|
| 531 |
+
x = np.ascontiguousarray(d)
|
| 532 |
+
out = np.empty(x.shape)
|
| 533 |
+
_interp_run(x.reshape(-1), du, T, out.reshape(-1), fused)
|
| 534 |
+
return out
|
| 535 |
|
| 536 |
|
| 537 |
class substrate:
|
|
|
|
| 564 |
if m == "halfspace":
|
| 565 |
return None
|
| 566 |
key = (m, float(SUBSTRATE["t_um"]), float(eps_r))
|
| 567 |
+
if key in _IMG_CACHE:
|
| 568 |
+
_IMG_CACHE.move_to_end(key)
|
| 569 |
+
else:
|
| 570 |
K, t = (eps_r - 1) / (eps_r + 1), float(SUBSTRATE["t_um"])
|
| 571 |
n = np.arange(1, 400)
|
| 572 |
nmax = int(np.argmax(K ** (2 * n) < 1e-4)) + 1
|
|
|
|
| 578 |
w, D = np.r_[w, total - w.sum()], np.r_[2 * n * t, 2 * (nmax + 1) * t]
|
| 579 |
du = t / 1000
|
| 580 |
u = np.arange(0.0, 1e5 + 2 * du, du)
|
| 581 |
+
T = np.empty(len(u))
|
| 582 |
+
for i in range(0, len(u), 1 << 18): # row blocks: the same sums, without len(u) x images temporaries (~8 GB at 10 um)
|
| 583 |
+
ub = u[i:i + (1 << 18)]
|
| 584 |
+
T[i:i + len(ub)] = (w[None, :] / np.sqrt(ub[:, None] ** 2 + D[None, :] ** 2)).sum(1)
|
| 585 |
_IMG_CACHE[key] = (du, T, w, D)
|
| 586 |
+
_img_evict()
|
| 587 |
du, T = _IMG_CACHE[key][:2]
|
| 588 |
if exact:
|
| 589 |
w, D = _IMG_CACHE[key][2:]
|
| 590 |
d2 = np.asarray(d, float) ** 2
|
| 591 |
return sum(wn / np.sqrt(d2 + Dn * Dn) for wn, Dn in zip(w, D))
|
| 592 |
+
out = _interp_uniform(d, du, T)
|
| 593 |
+
if out is not None:
|
| 594 |
+
return out
|
| 595 |
if key not in _IMG_GRID:
|
| 596 |
_IMG_GRID[key] = du * np.arange(len(T))
|
| 597 |
return np.interp(d, _IMG_GRID[key], T)
|
src/squadds/ml/capacitance/_core/fastprior_pkg.py
CHANGED
|
@@ -823,7 +823,7 @@ def _mixed_chol(A, B):
|
|
| 823 |
try:
|
| 824 |
cf = cho_factor(A.astype(np.float32, order="F"), lower=True, overwrite_a=True, check_finite=False)
|
| 825 |
except np.linalg.LinAlgError:
|
| 826 |
-
return _ORIG["chol_solve"](A, B)
|
| 827 |
B = np.asfortranarray(B, dtype=float)
|
| 828 |
X = cho_solve(cf, B.astype(np.float32), check_finite=False).astype(float)
|
| 829 |
bn = np.linalg.norm(B, axis=0)
|
|
@@ -832,7 +832,7 @@ def _mixed_chol(A, B):
|
|
| 832 |
if (np.linalg.norm(R, axis=0) <= CFG["refine_tol"] * bn).all():
|
| 833 |
return X
|
| 834 |
X += cho_solve(cf, R.astype(np.float32), check_finite=False)
|
| 835 |
-
return _ORIG["chol_solve"](A, B)
|
| 836 |
|
| 837 |
|
| 838 |
def _chol_solve(A, B):
|
|
@@ -845,7 +845,13 @@ def _chol_solve(A, B):
|
|
| 845 |
|
| 846 |
def _sym_solve(A, B):
|
| 847 |
if not isinstance(A, _Dev):
|
| 848 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 849 |
if A.t.shape[0] > FROZEN_DENSE_MAX:
|
| 850 |
return _gpu_chol(A, B)
|
| 851 |
try:
|
|
|
|
| 823 |
try:
|
| 824 |
cf = cho_factor(A.astype(np.float32, order="F"), lower=True, overwrite_a=True, check_finite=False)
|
| 825 |
except np.linalg.LinAlgError:
|
| 826 |
+
return _ORIG["chol_solve"](A.copy(order="F"), B)
|
| 827 |
B = np.asfortranarray(B, dtype=float)
|
| 828 |
X = cho_solve(cf, B.astype(np.float32), check_finite=False).astype(float)
|
| 829 |
bn = np.linalg.norm(B, axis=0)
|
|
|
|
| 832 |
if (np.linalg.norm(R, axis=0) <= CFG["refine_tol"] * bn).all():
|
| 833 |
return X
|
| 834 |
X += cho_solve(cf, R.astype(np.float32), check_finite=False)
|
| 835 |
+
return _ORIG["chol_solve"](A.copy(order="F"), B)
|
| 836 |
|
| 837 |
|
| 838 |
def _chol_solve(A, B):
|
|
|
|
| 845 |
|
| 846 |
def _sym_solve(A, B):
|
| 847 |
if not isinstance(A, _Dev):
|
| 848 |
+
if "mixed" not in STATE["components"]:
|
| 849 |
+
return _ORIG["sym_solve"](A, B)
|
| 850 |
+
try: # = _ORIG["sym_solve"] without its copy of A: _mixed_chol only reads A (its float64 fallbacks copy it)
|
| 851 |
+
return _mixed_chol(A, B)
|
| 852 |
+
except np.linalg.LinAlgError:
|
| 853 |
+
from scipy.linalg import solve
|
| 854 |
+
return solve(A, B, lower=True, assume_a="sym", overwrite_a=True, check_finite=False)
|
| 855 |
if A.t.shape[0] > FROZEN_DENSE_MAX:
|
| 856 |
return _gpu_chol(A, B)
|
| 857 |
try:
|
src/squadds/ml/capacitance/_core/paper.py
CHANGED
|
@@ -19,6 +19,7 @@ import hashlib
|
|
| 19 |
import json
|
| 20 |
import os
|
| 21 |
import time
|
|
|
|
| 22 |
from pathlib import Path
|
| 23 |
|
| 24 |
import numpy as np
|
|
@@ -186,13 +187,82 @@ def apply_stack(reg, a, threads=2):
|
|
| 186 |
A._thread_limits(threads)
|
| 187 |
|
| 188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
def solve_levels(sc, levels, threads=2, stack=None) -> tuple[dict, dict]:
|
| 190 |
"""Positive-mutual prior matrices P = -C at each level under the installed stack (the statements of
|
| 191 |
geomgnn.api.predict_scene's prior loop, any level list); stack = (eps_r, thickness_um) of the substrate the prior is solved at
|
| 192 |
-
(default the scene's, i.e. the training stack).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
from ._tlsq.embed.fastprior_loc import micro_mom_loc
|
| 194 |
from . import levelpar
|
| 195 |
-
eps_r, t_um = stack or (sc.stack["substrate_eps_r"], sc.stack["substrate_thickness_um"])
|
| 196 |
if levelpar.enabled(sc, levels, threads): # the levels concurrently (spawned workers, same stack and statements)
|
| 197 |
return levelpar.solve(sc, list(levels), threads, ALPHA, (eps_r, t_um))
|
| 198 |
proxy.NUM_THREADS = threads
|
|
|
|
| 19 |
import json
|
| 20 |
import os
|
| 21 |
import time
|
| 22 |
+
from collections import OrderedDict
|
| 23 |
from pathlib import Path
|
| 24 |
|
| 25 |
import numpy as np
|
|
|
|
| 187 |
A._thread_limits(threads)
|
| 188 |
|
| 189 |
|
| 190 |
+
_LEVELS: OrderedDict = OrderedDict() # solved prior levels: (layout, level, substrate, stack) -> P; TLSQ_PRIOR_LEVEL_CACHE_MB (0 = off)
|
| 191 |
+
_MESHES: OrderedDict = OrderedDict() # the prior's window meshes (geometry and lattice only, no substrate), same bound
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def _geom_hash(geoms) -> str:
|
| 195 |
+
import shapely
|
| 196 |
+
h = hashlib.sha256()
|
| 197 |
+
for g in geoms:
|
| 198 |
+
h.update(shapely.to_wkb(g))
|
| 199 |
+
h.update(b"|")
|
| 200 |
+
return h.hexdigest()
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _level_key(sc, threads, eps_r, t_um) -> tuple:
|
| 204 |
+
return (_geom_hash([c.geom for c in sc.conductors]), float(eps_r), float(t_um), int(threads), ALPHA, A._STATE["prior_impl"],
|
| 205 |
+
repr(A._STATE.get("stack")), repr(A._STATE.get("pr")))
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _put(cache, k, v, cap) -> None:
|
| 209 |
+
cache[k] = v
|
| 210 |
+
nb = lambda x: sum(a.nbytes for a in (x if isinstance(x, tuple) else (x,)) if isinstance(a, np.ndarray)) # noqa: E731
|
| 211 |
+
while len(cache) > 1 and sum(nb(x) for x in cache.values()) > cap:
|
| 212 |
+
cache.popitem(last=False)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _memo_mesh(f, cap):
|
| 216 |
+
"""f(metals, *args) -> mesh arrays, memoised on the metals' WKB and the arguments; hits return copies."""
|
| 217 |
+
def g(metals, *args, **kw):
|
| 218 |
+
k = (f.__module__, f.__name__, _geom_hash(metals), repr(args), repr(sorted(kw.items())))
|
| 219 |
+
v = _MESHES.get(k)
|
| 220 |
+
if v is None:
|
| 221 |
+
v = tuple(x.copy() if isinstance(x, np.ndarray) else x for x in f(metals, *args, **kw))
|
| 222 |
+
_put(_MESHES, k, v, cap)
|
| 223 |
+
else:
|
| 224 |
+
_MESHES.move_to_end(k)
|
| 225 |
+
return tuple(x.copy() if isinstance(x, np.ndarray) else x for x in v)
|
| 226 |
+
return g
|
| 227 |
+
|
| 228 |
+
|
| 229 |
def solve_levels(sc, levels, threads=2, stack=None) -> tuple[dict, dict]:
|
| 230 |
"""Positive-mutual prior matrices P = -C at each level under the installed stack (the statements of
|
| 231 |
geomgnn.api.predict_scene's prior loop, any level list); stack = (eps_r, thickness_um) of the substrate the prior is solved at
|
| 232 |
+
(default the scene's, i.e. the training stack). With TLSQ_PRIOR_LEVEL_CACHE_MB > 0 every solved level is kept (LRU, bounded
|
| 233 |
+
in MB) and reused by any later call with the same layout, level, substrate and prior stack (tiers sharing a level), and the
|
| 234 |
+
window meshes are reused across substrates (same layout and level)."""
|
| 235 |
+
eps_r, t_um = stack or (sc.stack["substrate_eps_r"], sc.stack["substrate_thickness_um"])
|
| 236 |
+
cap = float(os.environ.get("TLSQ_PRIOR_LEVEL_CACHE_MB", "0")) * 2**20
|
| 237 |
+
key = _level_key(sc, threads, eps_r, t_um) if cap > 0 and levels else None
|
| 238 |
+
out, tm = {}, {}
|
| 239 |
+
for p in levels if key else ():
|
| 240 |
+
v = _LEVELS.get(key + (float(p),))
|
| 241 |
+
if v is not None:
|
| 242 |
+
_LEVELS.move_to_end(key + (float(p),))
|
| 243 |
+
out[p], tm[f"{p:g}"] = v.copy(), 0.0
|
| 244 |
+
todo = [p for p in levels if p not in out]
|
| 245 |
+
if todo:
|
| 246 |
+
from ._tlsq.embed import fastprior_loc as FL
|
| 247 |
+
from . import priorv2
|
| 248 |
+
hooks = [(m, n, getattr(m, n)) for m, n in ((priorv2, "_mesh"), (FL, "mesh_local"))] if key else []
|
| 249 |
+
try:
|
| 250 |
+
for m, n, f in hooks:
|
| 251 |
+
setattr(m, n, _memo_mesh(f, cap))
|
| 252 |
+
P, t = _solve_levels(sc, todo, threads, eps_r, t_um)
|
| 253 |
+
finally:
|
| 254 |
+
for m, n, f in hooks:
|
| 255 |
+
setattr(m, n, f)
|
| 256 |
+
out.update(P)
|
| 257 |
+
tm.update(t)
|
| 258 |
+
for p in todo if key else ():
|
| 259 |
+
_put(_LEVELS, key + (float(p),), P[p].copy(), cap)
|
| 260 |
+
return {p: out[p] for p in levels}, {f"{p:g}": tm[f"{p:g}"] for p in levels}
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _solve_levels(sc, levels, threads, eps_r, t_um) -> tuple[dict, dict]:
|
| 264 |
from ._tlsq.embed.fastprior_loc import micro_mom_loc
|
| 265 |
from . import levelpar
|
|
|
|
| 266 |
if levelpar.enabled(sc, levels, threads): # the levels concurrently (spawned workers, same stack and statements)
|
| 267 |
return levelpar.solve(sc, list(levels), threads, ALPHA, (eps_r, t_um))
|
| 268 |
proxy.NUM_THREADS = threads
|
src/squadds/ml/capacitance/_runtime.py
CHANGED
|
@@ -137,7 +137,7 @@ def machine() -> str:
|
|
| 137 |
except Exception: # noqa: BLE001
|
| 138 |
pass
|
| 139 |
elif Path("/proc/cpuinfo").exists():
|
| 140 |
-
for line in Path("/proc/cpuinfo").read_text().splitlines():
|
| 141 |
if line.startswith("model name"):
|
| 142 |
cpu = line.split(":", 1)[1].strip()
|
| 143 |
break
|
|
|
|
| 137 |
except Exception: # noqa: BLE001
|
| 138 |
pass
|
| 139 |
elif Path("/proc/cpuinfo").exists():
|
| 140 |
+
for line in Path("/proc/cpuinfo").read_text(encoding="utf-8").splitlines():
|
| 141 |
if line.startswith("model name"):
|
| 142 |
cpu = line.split(":", 1)[1].strip()
|
| 143 |
break
|
src/squadds/ml/capacitance/benchmark.py
CHANGED
|
@@ -236,7 +236,9 @@ def _guard(split, maintainer, keys, models, ledger_dir, model_id):
|
|
| 236 |
try:
|
| 237 |
fd = os.open(lp, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
| 238 |
except FileExistsError:
|
| 239 |
-
raise PermissionError(
|
|
|
|
|
|
|
| 240 |
with os.fdopen(fd, "w") as f:
|
| 241 |
f.write(json.dumps(dict(time=time.strftime("%Y-%m-%dT%H:%M:%S%z"), layouts=len(keys))))
|
| 242 |
return lp
|
|
|
|
| 236 |
try:
|
| 237 |
fd = os.open(lp, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
| 238 |
except FileExistsError:
|
| 239 |
+
raise PermissionError(
|
| 240 |
+
f"model {model_id} was already scored on test ({lp.read_text(encoding='utf-8').strip()})"
|
| 241 |
+
) from None
|
| 242 |
with os.fdopen(fd, "w") as f:
|
| 243 |
f.write(json.dumps(dict(time=time.strftime("%Y-%m-%dT%H:%M:%S%z"), layouts=len(keys))))
|
| 244 |
return lp
|
src/squadds/ml/capacitance/contribute.py
CHANGED
|
@@ -133,14 +133,14 @@ def load_manifest(path) -> dict:
|
|
| 133 |
p = Path(path) / "manifest.yaml"
|
| 134 |
if not p.exists():
|
| 135 |
raise FileNotFoundError(f"{p} not found (copy the template manifest.yaml)")
|
| 136 |
-
return _yaml().safe_load(p.read_text()) or {}
|
| 137 |
|
| 138 |
|
| 139 |
def read_designs(path) -> list[dict]:
|
| 140 |
p = Path(path) / "designs.csv"
|
| 141 |
if not p.exists():
|
| 142 |
raise FileNotFoundError(f"{p} not found (copy the template designs.csv)")
|
| 143 |
-
with open(p, newline="") as f:
|
| 144 |
return [
|
| 145 |
{k.strip(): (v or "").strip() for k, v in r.items() if k}
|
| 146 |
for r in csv.DictReader(line for line in f if not line.lstrip().startswith("#"))
|
|
@@ -194,7 +194,7 @@ def read_sim(sim_dir, unit: str = "fF") -> dict:
|
|
| 194 |
if conv is not None:
|
| 195 |
out["convergence"] = Q.read_conv(conv)
|
| 196 |
if (d / "run.json").exists():
|
| 197 |
-
out["run"] = json.loads((d / "run.json").read_text())
|
| 198 |
return out
|
| 199 |
|
| 200 |
|
|
@@ -297,7 +297,7 @@ def validate_capacitance_contribution(
|
|
| 297 |
|
| 298 |
def _finish(rep: Q.QCReport, report_path) -> Q.QCReport:
|
| 299 |
if report_path is not None:
|
| 300 |
-
Path(report_path).write_text(rep.to_markdown("Validation report"))
|
| 301 |
return rep
|
| 302 |
|
| 303 |
|
|
@@ -319,7 +319,7 @@ def _validate_design(root: Path, row: dict, unit, layer_map, gname, check_prior,
|
|
| 319 |
return r
|
| 320 |
nets = None
|
| 321 |
if (root / "nets" / f"{d}.json").exists():
|
| 322 |
-
nets = json.loads((root / "nets" / f"{d}.json").read_text())
|
| 323 |
g = Q.gds_qc(gp, layer_map, nets, subject="gds")
|
| 324 |
r.extend(g, "gds")
|
| 325 |
if "n_conductors" in g.info:
|
|
@@ -423,7 +423,7 @@ def contribute_capacitance(
|
|
| 423 |
rel = p.relative_to(root).as_posix()
|
| 424 |
if p.name == "run.json":
|
| 425 |
fxr: list[str] = []
|
| 426 |
-
data = json.dumps(_scrub(json.loads(p.read_text()), rel, fxr), indent=1).encode()
|
| 427 |
ops.append(CommitOperationAdd(path_in_repo=f"{folder}/{rel}", path_or_fileobj=data))
|
| 428 |
else:
|
| 429 |
ops.append(CommitOperationAdd(path_in_repo=f"{folder}/{rel}", path_or_fileobj=str(p)))
|
|
@@ -457,7 +457,11 @@ def _model_meta(root: Path) -> dict:
|
|
| 457 |
for n in MODEL_META_FILES:
|
| 458 |
p = root / n
|
| 459 |
if p.exists():
|
| 460 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
return {}
|
| 462 |
|
| 463 |
|
|
@@ -612,7 +616,7 @@ def contribute_model(
|
|
| 612 |
if hf is not None:
|
| 613 |
try:
|
| 614 |
p = hf.hf_hub_download(repo_id=registry_repo, repo_type="dataset", filename=ZOO_FILE)
|
| 615 |
-
zoo = _yaml().safe_load(Path(p).read_text()) or zoo
|
| 616 |
except Exception as e: # noqa: BLE001
|
| 617 |
if "404" not in str(e) and "EntryNotFound" not in type(e).__name__ and "not found" not in str(e).lower():
|
| 618 |
raise
|
|
|
|
| 133 |
p = Path(path) / "manifest.yaml"
|
| 134 |
if not p.exists():
|
| 135 |
raise FileNotFoundError(f"{p} not found (copy the template manifest.yaml)")
|
| 136 |
+
return _yaml().safe_load(p.read_text(encoding="utf-8")) or {}
|
| 137 |
|
| 138 |
|
| 139 |
def read_designs(path) -> list[dict]:
|
| 140 |
p = Path(path) / "designs.csv"
|
| 141 |
if not p.exists():
|
| 142 |
raise FileNotFoundError(f"{p} not found (copy the template designs.csv)")
|
| 143 |
+
with open(p, newline="", encoding="utf-8") as f:
|
| 144 |
return [
|
| 145 |
{k.strip(): (v or "").strip() for k, v in r.items() if k}
|
| 146 |
for r in csv.DictReader(line for line in f if not line.lstrip().startswith("#"))
|
|
|
|
| 194 |
if conv is not None:
|
| 195 |
out["convergence"] = Q.read_conv(conv)
|
| 196 |
if (d / "run.json").exists():
|
| 197 |
+
out["run"] = json.loads((d / "run.json").read_text(encoding="utf-8"))
|
| 198 |
return out
|
| 199 |
|
| 200 |
|
|
|
|
| 297 |
|
| 298 |
def _finish(rep: Q.QCReport, report_path) -> Q.QCReport:
|
| 299 |
if report_path is not None:
|
| 300 |
+
Path(report_path).write_text(rep.to_markdown("Validation report"), encoding="utf-8")
|
| 301 |
return rep
|
| 302 |
|
| 303 |
|
|
|
|
| 319 |
return r
|
| 320 |
nets = None
|
| 321 |
if (root / "nets" / f"{d}.json").exists():
|
| 322 |
+
nets = json.loads((root / "nets" / f"{d}.json").read_text(encoding="utf-8"))
|
| 323 |
g = Q.gds_qc(gp, layer_map, nets, subject="gds")
|
| 324 |
r.extend(g, "gds")
|
| 325 |
if "n_conductors" in g.info:
|
|
|
|
| 423 |
rel = p.relative_to(root).as_posix()
|
| 424 |
if p.name == "run.json":
|
| 425 |
fxr: list[str] = []
|
| 426 |
+
data = json.dumps(_scrub(json.loads(p.read_text(encoding="utf-8")), rel, fxr), indent=1).encode()
|
| 427 |
ops.append(CommitOperationAdd(path_in_repo=f"{folder}/{rel}", path_or_fileobj=data))
|
| 428 |
else:
|
| 429 |
ops.append(CommitOperationAdd(path_in_repo=f"{folder}/{rel}", path_or_fileobj=str(p)))
|
|
|
|
| 457 |
for n in MODEL_META_FILES:
|
| 458 |
p = root / n
|
| 459 |
if p.exists():
|
| 460 |
+
return (
|
| 461 |
+
_yaml().safe_load(p.read_text(encoding="utf-8"))
|
| 462 |
+
if p.suffix == ".yaml"
|
| 463 |
+
else json.loads(p.read_text(encoding="utf-8"))
|
| 464 |
+
)
|
| 465 |
return {}
|
| 466 |
|
| 467 |
|
|
|
|
| 616 |
if hf is not None:
|
| 617 |
try:
|
| 618 |
p = hf.hf_hub_download(repo_id=registry_repo, repo_type="dataset", filename=ZOO_FILE)
|
| 619 |
+
zoo = _yaml().safe_load(Path(p).read_text(encoding="utf-8")) or zoo
|
| 620 |
except Exception as e: # noqa: BLE001
|
| 621 |
if "404" not in str(e) and "EntryNotFound" not in type(e).__name__ and "not found" not in str(e).lower():
|
| 622 |
raise
|
src/squadds/ml/capacitance/dataset.py
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
No ``[ml]`` dependency: this module needs pandas, pyarrow and huggingface_hub (all core SQuADDS dependencies), so
|
| 4 |
``from squadds.ml.capacitance.dataset import PlanarCapacitanceDB`` works on a plain ``pip install squadds``.
|
| 5 |
|
| 6 |
-
db = PlanarCapacitanceDB() # HF repo
|
| 7 |
db = PlanarCapacitanceDB(local_dir="/path/to/SQuADDS_PlanarCapacitance") # or env SQUADDS_PLANAR_CAP_DATA
|
| 8 |
ids = db.designs(family="interdigital", split="val").design_id[:5]
|
| 9 |
db.labels(ids) # {design_id: N x N Maxwell matrix (pandas DataFrame, fF, ground first)}
|
|
@@ -29,8 +29,8 @@ from squadds.datasets.planar_capacitance_schema import (
|
|
| 29 |
)
|
| 30 |
|
| 31 |
ENV_VAR = "SQUADDS_PLANAR_CAP_DATA"
|
| 32 |
-
# pinned HF commit of REPO_ID (2026-11-
|
| 33 |
-
DATASET_REVISION = "
|
| 34 |
|
| 35 |
TABLE_GLOBS = {
|
| 36 |
"designs": "data/designs/*.parquet",
|
|
@@ -41,7 +41,7 @@ TABLE_GLOBS = {
|
|
| 41 |
"geometric_embedding_nodes": "data/geometric_embedding/nodes-*.parquet",
|
| 42 |
"geometric_embedding_edges": "data/geometric_embedding/edges-*.parquet",
|
| 43 |
"geometric_embedding_globals": "data/geometric_embedding/globals-*.parquet",
|
| 44 |
-
"
|
| 45 |
"optimized_physics_prior": "data/optimized_physics_prior/*.parquet",
|
| 46 |
"model_input": "data/model_input/*.parquet",
|
| 47 |
}
|
|
@@ -82,7 +82,7 @@ class PlanarCapacitanceDB:
|
|
| 82 |
``"main"`` for the latest; ignored with a local directory.
|
| 83 |
local_dir: a local copy of the repo (same layout as on HF). Default: env ``SQUADDS_PLANAR_CAP_DATA``, else HF.
|
| 84 |
repo_id: HF dataset repo (default ``SQuADDS/SQuADDS_PlanarCapacitance``).
|
| 85 |
-
token: HF token
|
| 86 |
"""
|
| 87 |
|
| 88 |
def __init__(self, revision: str | None = None, local_dir=None, repo_id: str = REPO_ID, token: str | None = None):
|
|
@@ -231,9 +231,9 @@ class PlanarCapacitanceDB:
|
|
| 231 |
df = self.read(table, design_ids=design_ids)
|
| 232 |
return {k: long_to_matrix(g, value, "i", "j") for k, g in df.groupby("design_id", sort=False)}
|
| 233 |
|
| 234 |
-
def
|
| 235 |
"""Single thin-film MoM solve at p = 0.375 as N x N Maxwell matrices (fF, ground first)."""
|
| 236 |
-
return self._prior("
|
| 237 |
|
| 238 |
def optimized_physics_prior(self, design_ids, value: str = "C_R_fF") -> dict[str, pd.DataFrame]:
|
| 239 |
"""C^R = R(1.5, 3) on the corrected stack as N x N Maxwell matrices (``value="mutual_1p5_fF"`` / ``"mutual_3_fF"``
|
|
|
|
| 3 |
No ``[ml]`` dependency: this module needs pandas, pyarrow and huggingface_hub (all core SQuADDS dependencies), so
|
| 4 |
``from squadds.ml.capacitance.dataset import PlanarCapacitanceDB`` works on a plain ``pip install squadds``.
|
| 5 |
|
| 6 |
+
db = PlanarCapacitanceDB() # HF repo
|
| 7 |
db = PlanarCapacitanceDB(local_dir="/path/to/SQuADDS_PlanarCapacitance") # or env SQUADDS_PLANAR_CAP_DATA
|
| 8 |
ids = db.designs(family="interdigital", split="val").design_id[:5]
|
| 9 |
db.labels(ids) # {design_id: N x N Maxwell matrix (pandas DataFrame, fF, ground first)}
|
|
|
|
| 29 |
)
|
| 30 |
|
| 31 |
ENV_VAR = "SQUADDS_PLANAR_CAP_DATA"
|
| 32 |
+
# pinned HF commit of REPO_ID (2026-11-14: coarse prior table renamed physics_prior); revision="main" for the latest
|
| 33 |
+
DATASET_REVISION = "c79953313874e9c116ca2f39a414d92025d18484"
|
| 34 |
|
| 35 |
TABLE_GLOBS = {
|
| 36 |
"designs": "data/designs/*.parquet",
|
|
|
|
| 41 |
"geometric_embedding_nodes": "data/geometric_embedding/nodes-*.parquet",
|
| 42 |
"geometric_embedding_edges": "data/geometric_embedding/edges-*.parquet",
|
| 43 |
"geometric_embedding_globals": "data/geometric_embedding/globals-*.parquet",
|
| 44 |
+
"physics_prior": "data/physics_prior/*.parquet",
|
| 45 |
"optimized_physics_prior": "data/optimized_physics_prior/*.parquet",
|
| 46 |
"model_input": "data/model_input/*.parquet",
|
| 47 |
}
|
|
|
|
| 82 |
``"main"`` for the latest; ignored with a local directory.
|
| 83 |
local_dir: a local copy of the repo (same layout as on HF). Default: env ``SQUADDS_PLANAR_CAP_DATA``, else HF.
|
| 84 |
repo_id: HF dataset repo (default ``SQuADDS/SQuADDS_PlanarCapacitance``).
|
| 85 |
+
token: HF token (default: the logged-in token, if any).
|
| 86 |
"""
|
| 87 |
|
| 88 |
def __init__(self, revision: str | None = None, local_dir=None, repo_id: str = REPO_ID, token: str | None = None):
|
|
|
|
| 231 |
df = self.read(table, design_ids=design_ids)
|
| 232 |
return {k: long_to_matrix(g, value, "i", "j") for k, g in df.groupby("design_id", sort=False)}
|
| 233 |
|
| 234 |
+
def physics_prior(self, design_ids, value: str = "C_fF") -> dict[str, pd.DataFrame]:
|
| 235 |
"""Single thin-film MoM solve at p = 0.375 as N x N Maxwell matrices (fF, ground first)."""
|
| 236 |
+
return self._prior("physics_prior", design_ids, value)
|
| 237 |
|
| 238 |
def optimized_physics_prior(self, design_ids, value: str = "C_R_fF") -> dict[str, pd.DataFrame]:
|
| 239 |
"""C^R = R(1.5, 3) on the corrected stack as N x N Maxwell matrices (``value="mutual_1p5_fF"`` / ``"mutual_3_fF"``
|
src/squadds/ml/capacitance/manifest.json
CHANGED
|
@@ -27,7 +27,7 @@
|
|
| 27 |
"mode": "exact_compiled",
|
| 28 |
"module_sha256": "1a0bdcb71500c7f11e63238afe531c18caabd5c9f6f7aaa73d9b7dcd0ad61f8c",
|
| 29 |
"farfield_sha256": "6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836",
|
| 30 |
-
"speed_package_sha256": "
|
| 31 |
"value_changing_approved": "user 2026-10-17 (v2m, gnn_models.GNN); user 2026-10-20: adopted arm (b) of agents/farfield (substrate dipole for far pairs in different ground pockets; pre-declared rule met, agents/farfield/RESULTS.md; adoption agents/farfield/ADOPTION.md)",
|
| 32 |
"speed_approved": "user 2026-10-17 (gnn_models.GNN)",
|
| 33 |
"previous": "corrected_halfspace"
|
|
|
|
| 27 |
"mode": "exact_compiled",
|
| 28 |
"module_sha256": "1a0bdcb71500c7f11e63238afe531c18caabd5c9f6f7aaa73d9b7dcd0ad61f8c",
|
| 29 |
"farfield_sha256": "6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836",
|
| 30 |
+
"speed_package_sha256": "4fff680f35cb8b098de6c9b1b6fc55780064362ffc829bb47bf69a77454ce38a",
|
| 31 |
"value_changing_approved": "user 2026-10-17 (v2m, gnn_models.GNN); user 2026-10-20: adopted arm (b) of agents/farfield (substrate dipole for far pairs in different ground pockets; pre-declared rule met, agents/farfield/RESULTS.md; adoption agents/farfield/ADOPTION.md)",
|
| 32 |
"speed_approved": "user 2026-10-17 (gnn_models.GNN)",
|
| 33 |
"previous": "corrected_halfspace"
|
src/squadds/ml/capacitance/models.py
CHANGED
|
@@ -17,7 +17,7 @@ from pathlib import Path
|
|
| 17 |
from ._runtime import TRAIN_EPS_R
|
| 18 |
|
| 19 |
ENV_MODELS = "SQUADDS_CAPML_MODELS"
|
| 20 |
-
MANIFEST = json.loads((Path(__file__).with_name("manifest.json")).read_text())
|
| 21 |
_SHA_MEMO: dict = {}
|
| 22 |
|
| 23 |
|
|
|
|
| 17 |
from ._runtime import TRAIN_EPS_R
|
| 18 |
|
| 19 |
ENV_MODELS = "SQUADDS_CAPML_MODELS"
|
| 20 |
+
MANIFEST = json.loads((Path(__file__).with_name("manifest.json")).read_text(encoding="utf-8"))
|
| 21 |
_SHA_MEMO: dict = {}
|
| 22 |
|
| 23 |
|
src/squadds/ml/capacitance/predictor.py
CHANGED
|
@@ -26,6 +26,8 @@ from .result import CapacitanceResult, physical_checks, physical_warning
|
|
| 26 |
_EMB: OrderedDict = OrderedDict()
|
| 27 |
_PRI: OrderedDict = OrderedDict()
|
| 28 |
_CACHE_SIZE = [int(os.environ.get("SQUADDS_CAPML_CACHE", "32"))]
|
|
|
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
@contextlib.contextmanager
|
|
@@ -59,6 +61,21 @@ def _warn(msg: str) -> None:
|
|
| 59 |
def clear_cache() -> None:
|
| 60 |
_EMB.clear()
|
| 61 |
_PRI.clear()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
def _get(c: OrderedDict, k):
|
|
@@ -71,10 +88,12 @@ def _get(c: OrderedDict, k):
|
|
| 71 |
def _put(c: OrderedDict, k, v) -> None:
|
| 72 |
if _CACHE_SIZE[0] <= 0:
|
| 73 |
return
|
|
|
|
| 74 |
c[k] = v
|
| 75 |
c.move_to_end(k)
|
| 76 |
-
|
| 77 |
-
|
|
|
|
| 78 |
|
| 79 |
|
| 80 |
def _stack_record(a: dict) -> tuple[dict | None, str | None]:
|
|
|
|
| 26 |
_EMB: OrderedDict = OrderedDict()
|
| 27 |
_PRI: OrderedDict = OrderedDict()
|
| 28 |
_CACHE_SIZE = [int(os.environ.get("SQUADDS_CAPML_CACHE", "32"))]
|
| 29 |
+
_CACHE_BYTES = [int(os.environ.get("SQUADDS_CAPML_CACHE_BYTES", str(2**30)))] # per cache
|
| 30 |
+
_NBYTES: dict = {} # id(cache) -> {key: estimated bytes}
|
| 31 |
|
| 32 |
|
| 33 |
@contextlib.contextmanager
|
|
|
|
| 61 |
def clear_cache() -> None:
|
| 62 |
_EMB.clear()
|
| 63 |
_PRI.clear()
|
| 64 |
+
_NBYTES.clear()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _nbytes(v) -> int:
|
| 68 |
+
"""Estimated memory of a cached value: arrays / tensors by nbytes, containers and Python objects by sys.getsizeof."""
|
| 69 |
+
import sys
|
| 70 |
+
|
| 71 |
+
nb = getattr(v, "nbytes", None)
|
| 72 |
+
if isinstance(nb, int):
|
| 73 |
+
return nb
|
| 74 |
+
if isinstance(v, dict):
|
| 75 |
+
return sys.getsizeof(v) + sum(_nbytes(k) + _nbytes(x) for k, x in v.items())
|
| 76 |
+
if isinstance(v, (list, tuple, set)):
|
| 77 |
+
return sys.getsizeof(v) + sum(_nbytes(x) for x in v)
|
| 78 |
+
return sys.getsizeof(v)
|
| 79 |
|
| 80 |
|
| 81 |
def _get(c: OrderedDict, k):
|
|
|
|
| 88 |
def _put(c: OrderedDict, k, v) -> None:
|
| 89 |
if _CACHE_SIZE[0] <= 0:
|
| 90 |
return
|
| 91 |
+
nb = _NBYTES.setdefault(id(c), {})
|
| 92 |
c[k] = v
|
| 93 |
c.move_to_end(k)
|
| 94 |
+
nb[k] = _nbytes(v)
|
| 95 |
+
while c and (len(c) > _CACHE_SIZE[0] or sum(nb.values()) > _CACHE_BYTES[0]):
|
| 96 |
+
nb.pop(c.popitem(last=False)[0], None)
|
| 97 |
|
| 98 |
|
| 99 |
def _stack_record(a: dict) -> tuple[dict | None, str | None]:
|
src/squadds/ml/capacitance/priors.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""Physics priors: thin-film method-of-moments capacitance matrices of a layout (no learned parameter).
|
| 2 |
|
| 3 |
-
- ``
|
| 4 |
- ``optimized_physics_prior``: C^R = R(1.5, 3) = exp(2 log C(3) - log C(1.5)), entry by entry, the physics prior of the paper
|
| 5 |
model and of the flagship model.
|
| 6 |
|
|
@@ -142,7 +142,7 @@ def _result(kind, layout, levels, combine, threads, eps_r, thickness_um, prepare
|
|
| 142 |
)
|
| 143 |
|
| 144 |
|
| 145 |
-
def
|
| 146 |
layout,
|
| 147 |
threads: int = 2,
|
| 148 |
eps_r: float = RT.TRAIN_EPS_R,
|
|
@@ -154,7 +154,7 @@ def coarse_physics_prior(
|
|
| 154 |
from ._core import x1_core as X
|
| 155 |
|
| 156 |
return _result(
|
| 157 |
-
"
|
| 158 |
layout,
|
| 159 |
[0.375],
|
| 160 |
lambda P: X.to_maxwell(P[0.375]),
|
|
|
|
| 1 |
"""Physics priors: thin-film method-of-moments capacitance matrices of a layout (no learned parameter).
|
| 2 |
|
| 3 |
+
- ``physics_prior``: one solve at p = 0.375 panels per gap (the paper's cheap-physics comparator).
|
| 4 |
- ``optimized_physics_prior``: C^R = R(1.5, 3) = exp(2 log C(3) - log C(1.5)), entry by entry, the physics prior of the paper
|
| 5 |
model and of the flagship model.
|
| 6 |
|
|
|
|
| 142 |
)
|
| 143 |
|
| 144 |
|
| 145 |
+
def physics_prior(
|
| 146 |
layout,
|
| 147 |
threads: int = 2,
|
| 148 |
eps_r: float = RT.TRAIN_EPS_R,
|
|
|
|
| 154 |
from ._core import x1_core as X
|
| 155 |
|
| 156 |
return _result(
|
| 157 |
+
"physics_prior p=0.375",
|
| 158 |
layout,
|
| 159 |
[0.375],
|
| 160 |
lambda P: X.to_maxwell(P[0.375]),
|
src/squadds/ml/capacitance/qc.py
CHANGED
|
@@ -172,7 +172,7 @@ def read_cap_matrix(path) -> dict:
|
|
| 172 |
"""Q3D ``cap_matrix.csv`` (one row per adaptive pass; ``C(a,b) [unit]`` columns in any unit, also the ``*1e15`` header)
|
| 173 |
-> ``{"names" (G first, then first appearance), "passes" [(pass index, N x N fF)], "units", "freq_GHz"}``. Incomplete rows
|
| 174 |
(pre-allocated passes) are kept as NaN matrices and skipped by the QC."""
|
| 175 |
-
rows = [r for r in csv.reader(open(path)) if r]
|
| 176 |
if not rows:
|
| 177 |
raise ValueError(f"{path}: empty file")
|
| 178 |
hdr, data = rows[0], rows[1:]
|
|
@@ -224,7 +224,7 @@ def read_cap_matrix(path) -> dict:
|
|
| 224 |
|
| 225 |
def read_conv(path) -> dict:
|
| 226 |
"""Q3D ``.conv`` convergence file -> pass history, passes completed, delta target and final delta (%)."""
|
| 227 |
-
t = Path(path).read_text()
|
| 228 |
|
| 229 |
def g(k, f=float):
|
| 230 |
m = re.search(rf"{k}\s*:\s*(\S+)", t)
|
|
|
|
| 172 |
"""Q3D ``cap_matrix.csv`` (one row per adaptive pass; ``C(a,b) [unit]`` columns in any unit, also the ``*1e15`` header)
|
| 173 |
-> ``{"names" (G first, then first appearance), "passes" [(pass index, N x N fF)], "units", "freq_GHz"}``. Incomplete rows
|
| 174 |
(pre-allocated passes) are kept as NaN matrices and skipped by the QC."""
|
| 175 |
+
rows = [r for r in csv.reader(open(path, encoding="utf-8")) if r]
|
| 176 |
if not rows:
|
| 177 |
raise ValueError(f"{path}: empty file")
|
| 178 |
hdr, data = rows[0], rows[1:]
|
|
|
|
| 224 |
|
| 225 |
def read_conv(path) -> dict:
|
| 226 |
"""Q3D ``.conv`` convergence file -> pass history, passes completed, delta target and final delta (%)."""
|
| 227 |
+
t = Path(path).read_text(encoding="utf-8")
|
| 228 |
|
| 229 |
def g(k, f=float):
|
| 230 |
m = re.search(rf"{k}\s*:\s*(\S+)", t)
|
src/squadds/ml/capacitance/serving.py
CHANGED
|
@@ -102,7 +102,9 @@ class Adapter:
|
|
| 102 |
raise ValueError(f"could not read this layout: {exc}") from exc
|
| 103 |
prepare_s = time.perf_counter() - t
|
| 104 |
if len(lay.names) > self.max_conductors:
|
| 105 |
-
raise TooLarge(
|
|
|
|
|
|
|
| 106 |
res = self.predictor.predict(lay, eps_r=p.eps_r, thickness_um=p.thickness_um)
|
| 107 |
tm = res.timing_s
|
| 108 |
meta = {
|
|
|
|
| 102 |
raise ValueError(f"could not read this layout: {exc}") from exc
|
| 103 |
prepare_s = time.perf_counter() - t
|
| 104 |
if len(lay.names) > self.max_conductors:
|
| 105 |
+
raise TooLarge(
|
| 106 |
+
f"{len(lay.names)} conductors found; this server takes at most {self.max_conductors} plus ground"
|
| 107 |
+
)
|
| 108 |
res = self.predictor.predict(lay, eps_r=p.eps_r, thickness_um=p.thickness_um)
|
| 109 |
tm = res.timing_s
|
| 110 |
meta = {
|
src/squadds/ml/capacitance/slurm.py
CHANGED
|
@@ -78,6 +78,6 @@ def write_slurm_array(
|
|
| 78 |
]
|
| 79 |
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 80 |
log_dir.mkdir(parents=True, exist_ok=True)
|
| 81 |
-
out_path.write_text("\n".join(lines))
|
| 82 |
out_path.chmod(0o755)
|
| 83 |
return out_path
|
|
|
|
| 78 |
]
|
| 79 |
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 80 |
log_dir.mkdir(parents=True, exist_ok=True)
|
| 81 |
+
out_path.write_text("\n".join(lines), encoding="utf-8")
|
| 82 |
out_path.chmod(0o755)
|
| 83 |
return out_path
|
src/squadds/ml/capacitance/train.py
CHANGED
|
@@ -13,6 +13,9 @@ aarch64 on the GH200 node, CPU, 2 threads, its torch and numpy); a run is expect
|
|
| 13 |
that environment. Other machines, thread counts, devices or library versions drift slightly (gate iii: numpy alone moves
|
| 14 |
the trajectory). The checkpoint records ``environment``, ``release_environment_match`` and the differences
|
| 15 |
(``release_environment_diff``); ``bit_identical_to_release`` is kept as an alias of ``release_environment_match``.
|
|
|
|
|
|
|
|
|
|
| 16 |
"""
|
| 17 |
|
| 18 |
from __future__ import annotations
|
|
@@ -152,7 +155,7 @@ def fit(
|
|
| 152 |
out = Path(out_dir)
|
| 153 |
out.mkdir(parents=True, exist_ok=False)
|
| 154 |
root = Path(shard_dir)
|
| 155 |
-
schema = json.loads((root / "schema.json").read_text())
|
| 156 |
ds = [dict(np.load(p, allow_pickle=False)) for p in sorted(root.glob("n*.npz"))]
|
| 157 |
if not ds:
|
| 158 |
raise FileNotFoundError(f"no n*.npz shards in {root}")
|
|
@@ -332,9 +335,9 @@ def fit(
|
|
| 332 |
|
| 333 |
rep = score(ck, root, split="val", threads=threads, name=f"{arm} seed {seed}")
|
| 334 |
rep.by_family.to_csv(out / "metrics.csv", index=False)
|
| 335 |
-
(out / "val_score.json").write_text(json.dumps(rep.to_dict(), indent=1))
|
| 336 |
run["val"] = rep.headline()
|
| 337 |
-
(out / "run.json").write_text(json.dumps(run, indent=1))
|
| 338 |
if verbose:
|
| 339 |
print("DONE", arm, seed, f"{train_s:.1f} s", run.get("val", ""), flush=True)
|
| 340 |
return run
|
|
@@ -603,7 +606,9 @@ def fit_in_family(
|
|
| 603 |
)
|
| 604 |
report.to_csv(out / "cv_report.csv", index=False)
|
| 605 |
pd.concat([f.assign(candidate=a) for a, f in L.items()]).to_csv(out / "cv_layouts.csv", index=False)
|
| 606 |
-
(out / "decision.json").write_text(
|
|
|
|
|
|
|
| 607 |
return InFamilyResult(chosen, model, report, decision, str(out), timing)
|
| 608 |
|
| 609 |
|
|
|
|
| 13 |
that environment. Other machines, thread counts, devices or library versions drift slightly (gate iii: numpy alone moves
|
| 14 |
the trajectory). The checkpoint records ``environment``, ``release_environment_match`` and the differences
|
| 15 |
(``release_environment_diff``); ``bit_identical_to_release`` is kept as an alias of ``release_environment_match``.
|
| 16 |
+
On CPU with ``threads > 1`` the training step sums some terms in an order that depends on thread timing, so on a busy
|
| 17 |
+
machine two runs of the same seed can differ in the last bits and then drift apart. ``threads=1`` (or
|
| 18 |
+
``torch.use_deterministic_algorithms(True)``) gives the same weights on every run on one machine.
|
| 19 |
"""
|
| 20 |
|
| 21 |
from __future__ import annotations
|
|
|
|
| 155 |
out = Path(out_dir)
|
| 156 |
out.mkdir(parents=True, exist_ok=False)
|
| 157 |
root = Path(shard_dir)
|
| 158 |
+
schema = json.loads((root / "schema.json").read_text(encoding="utf-8"))
|
| 159 |
ds = [dict(np.load(p, allow_pickle=False)) for p in sorted(root.glob("n*.npz"))]
|
| 160 |
if not ds:
|
| 161 |
raise FileNotFoundError(f"no n*.npz shards in {root}")
|
|
|
|
| 335 |
|
| 336 |
rep = score(ck, root, split="val", threads=threads, name=f"{arm} seed {seed}")
|
| 337 |
rep.by_family.to_csv(out / "metrics.csv", index=False)
|
| 338 |
+
(out / "val_score.json").write_text(json.dumps(rep.to_dict(), indent=1), encoding="utf-8")
|
| 339 |
run["val"] = rep.headline()
|
| 340 |
+
(out / "run.json").write_text(json.dumps(run, indent=1), encoding="utf-8")
|
| 341 |
if verbose:
|
| 342 |
print("DONE", arm, seed, f"{train_s:.1f} s", run.get("val", ""), flush=True)
|
| 343 |
return run
|
|
|
|
| 606 |
)
|
| 607 |
report.to_csv(out / "cv_report.csv", index=False)
|
| 608 |
pd.concat([f.assign(candidate=a) for a, f in L.items()]).to_csv(out / "cv_layouts.csv", index=False)
|
| 609 |
+
(out / "decision.json").write_text(
|
| 610 |
+
json.dumps(dict(decision=decision, timing=timing), indent=1, default=str), encoding="utf-8"
|
| 611 |
+
)
|
| 612 |
return InFamilyResult(chosen, model, report, decision, str(out), timing)
|
| 613 |
|
| 614 |
|
src/squadds/ml/capacitance/training_data.py
CHANGED
|
@@ -44,7 +44,7 @@ def base_schema() -> dict:
|
|
| 44 |
from ._core import paper as PA
|
| 45 |
from .models import MANIFEST
|
| 46 |
|
| 47 |
-
s = json.loads((Path(__file__).with_name("_core") / "schema_p2d.json").read_text())
|
| 48 |
st = MANIFEST["prior_stacks"]["corrected"]
|
| 49 |
return {
|
| 50 |
"nodekeys": list(s["nodekeys"]),
|
|
@@ -75,7 +75,7 @@ def sha256_file(p) -> str:
|
|
| 75 |
|
| 76 |
# ---------------------------------------------------------------------------------------------------------------- shards
|
| 77 |
def read_schema(shard_dir) -> dict:
|
| 78 |
-
return json.loads((Path(shard_dir) / "schema.json").read_text())
|
| 79 |
|
| 80 |
|
| 81 |
def shard_files(shard_dir) -> list[Path]:
|
|
@@ -99,7 +99,7 @@ def read_shards(shard_dir) -> list[dict]:
|
|
| 99 |
def read_names(shard_dir) -> dict:
|
| 100 |
"""{key: net names (G first)} of a shard dir built here (``names.json``); {} for shards without it."""
|
| 101 |
p = Path(shard_dir) / "names.json"
|
| 102 |
-
return json.loads(p.read_text()) if p.exists() else {}
|
| 103 |
|
| 104 |
|
| 105 |
def shard_summary(shard_dir) -> dict:
|
|
@@ -147,12 +147,12 @@ def write_shards(rows: list[dict], out_dir, schema: dict, extra: dict | None = N
|
|
| 147 |
np.savez_compressed(out / f"n{n:03d}.npz", **z)
|
| 148 |
names = {r["key"]: list(r["names"]) for r in rows if r.get("names") is not None}
|
| 149 |
if names:
|
| 150 |
-
(out / "names.json").write_text(json.dumps(names))
|
| 151 |
s = dict(schema)
|
| 152 |
s["shard_sha256"] = {p.name: sha256_file(p) for p in sorted(out.glob("n*.npz"))}
|
| 153 |
if extra:
|
| 154 |
s.update(extra)
|
| 155 |
-
(out / "schema.json").write_text(json.dumps(s, indent=1))
|
| 156 |
return out
|
| 157 |
|
| 158 |
|
|
@@ -185,10 +185,10 @@ def subset_shards(src, out_dir, train_keys=None, val_keys=None, keep=None) -> Pa
|
|
| 185 |
s = read_schema(src)
|
| 186 |
s["shard_sha256"] = {p.name: sha256_file(p) for p in sorted(out.glob("n*.npz"))}
|
| 187 |
s["subset_of"] = str(src)
|
| 188 |
-
(out / "schema.json").write_text(json.dumps(s, indent=1))
|
| 189 |
names = read_names(src)
|
| 190 |
if names:
|
| 191 |
-
(out / "names.json").write_text(json.dumps({k: v for k, v in names.items() if k in found}))
|
| 192 |
return out
|
| 193 |
|
| 194 |
|
|
@@ -255,10 +255,10 @@ def merge_shards(
|
|
| 255 |
"user_split": user_split,
|
| 256 |
"all_split": all_split,
|
| 257 |
}
|
| 258 |
-
(out / "schema.json").write_text(json.dumps(s, indent=1))
|
| 259 |
names = {**read_names(base_dir), **read_names(user_dir)}
|
| 260 |
if names:
|
| 261 |
-
(out / "names.json").write_text(json.dumps(names))
|
| 262 |
return out
|
| 263 |
|
| 264 |
|
|
@@ -267,7 +267,7 @@ def read_q3d_csv(path) -> tuple[list[str], np.ndarray, dict]:
|
|
| 267 |
"""Q3D ``cap_matrix.csv`` (one row per adaptive pass, columns ``C(a,b) [unit]``, also the ``C(a,b)*1e15 [pF]`` re-export)
|
| 268 |
-> (net names, Maxwell matrix in fF of the last complete pass, info). Names: G first, then the file's order of first
|
| 269 |
appearance."""
|
| 270 |
-
rows = [r for r in csv.reader(open(path)) if r]
|
| 271 |
hdr, data = rows[0], rows[1:]
|
| 272 |
cols, order = {}, []
|
| 273 |
for j, h in enumerate(hdr):
|
|
@@ -411,7 +411,7 @@ def design_json_names(gds) -> list[str] | None:
|
|
| 411 |
if not p.is_file():
|
| 412 |
return None
|
| 413 |
try:
|
| 414 |
-
q = json.loads(p.read_text())["ansys_gds"]["q3d_signal"]
|
| 415 |
a2n = {v["assignment"]: k for k, v in q["nets"].items()}
|
| 416 |
order = sorted(q["mapping_polygons"], key=lambda k: int(k.rsplit("_", 1)[-1]))
|
| 417 |
names = [a2n[q["mapping_polygons"][k]] for k in order]
|
|
@@ -686,7 +686,7 @@ def build_shards(
|
|
| 686 |
}
|
| 687 |
out = write_shards(rows, out_dir, schema, extra={"build": {k: v for k, v in build.items() if k != "refused"}})
|
| 688 |
build["designs"] = {r["key"]: r["info"] for r in rows}
|
| 689 |
-
(out / "build.json").write_text(json.dumps(build, indent=1, default=str))
|
| 690 |
return {"out_dir": str(out), "layouts": len(rows), "refused": refused, "seconds": build["seconds"]}
|
| 691 |
|
| 692 |
|
|
|
|
| 44 |
from ._core import paper as PA
|
| 45 |
from .models import MANIFEST
|
| 46 |
|
| 47 |
+
s = json.loads((Path(__file__).with_name("_core") / "schema_p2d.json").read_text(encoding="utf-8"))
|
| 48 |
st = MANIFEST["prior_stacks"]["corrected"]
|
| 49 |
return {
|
| 50 |
"nodekeys": list(s["nodekeys"]),
|
|
|
|
| 75 |
|
| 76 |
# ---------------------------------------------------------------------------------------------------------------- shards
|
| 77 |
def read_schema(shard_dir) -> dict:
|
| 78 |
+
return json.loads((Path(shard_dir) / "schema.json").read_text(encoding="utf-8"))
|
| 79 |
|
| 80 |
|
| 81 |
def shard_files(shard_dir) -> list[Path]:
|
|
|
|
| 99 |
def read_names(shard_dir) -> dict:
|
| 100 |
"""{key: net names (G first)} of a shard dir built here (``names.json``); {} for shards without it."""
|
| 101 |
p = Path(shard_dir) / "names.json"
|
| 102 |
+
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else {}
|
| 103 |
|
| 104 |
|
| 105 |
def shard_summary(shard_dir) -> dict:
|
|
|
|
| 147 |
np.savez_compressed(out / f"n{n:03d}.npz", **z)
|
| 148 |
names = {r["key"]: list(r["names"]) for r in rows if r.get("names") is not None}
|
| 149 |
if names:
|
| 150 |
+
(out / "names.json").write_text(json.dumps(names), encoding="utf-8")
|
| 151 |
s = dict(schema)
|
| 152 |
s["shard_sha256"] = {p.name: sha256_file(p) for p in sorted(out.glob("n*.npz"))}
|
| 153 |
if extra:
|
| 154 |
s.update(extra)
|
| 155 |
+
(out / "schema.json").write_text(json.dumps(s, indent=1), encoding="utf-8")
|
| 156 |
return out
|
| 157 |
|
| 158 |
|
|
|
|
| 185 |
s = read_schema(src)
|
| 186 |
s["shard_sha256"] = {p.name: sha256_file(p) for p in sorted(out.glob("n*.npz"))}
|
| 187 |
s["subset_of"] = str(src)
|
| 188 |
+
(out / "schema.json").write_text(json.dumps(s, indent=1), encoding="utf-8")
|
| 189 |
names = read_names(src)
|
| 190 |
if names:
|
| 191 |
+
(out / "names.json").write_text(json.dumps({k: v for k, v in names.items() if k in found}), encoding="utf-8")
|
| 192 |
return out
|
| 193 |
|
| 194 |
|
|
|
|
| 255 |
"user_split": user_split,
|
| 256 |
"all_split": all_split,
|
| 257 |
}
|
| 258 |
+
(out / "schema.json").write_text(json.dumps(s, indent=1), encoding="utf-8")
|
| 259 |
names = {**read_names(base_dir), **read_names(user_dir)}
|
| 260 |
if names:
|
| 261 |
+
(out / "names.json").write_text(json.dumps(names), encoding="utf-8")
|
| 262 |
return out
|
| 263 |
|
| 264 |
|
|
|
|
| 267 |
"""Q3D ``cap_matrix.csv`` (one row per adaptive pass, columns ``C(a,b) [unit]``, also the ``C(a,b)*1e15 [pF]`` re-export)
|
| 268 |
-> (net names, Maxwell matrix in fF of the last complete pass, info). Names: G first, then the file's order of first
|
| 269 |
appearance."""
|
| 270 |
+
rows = [r for r in csv.reader(open(path, encoding="utf-8")) if r]
|
| 271 |
hdr, data = rows[0], rows[1:]
|
| 272 |
cols, order = {}, []
|
| 273 |
for j, h in enumerate(hdr):
|
|
|
|
| 411 |
if not p.is_file():
|
| 412 |
return None
|
| 413 |
try:
|
| 414 |
+
q = json.loads(p.read_text(encoding="utf-8"))["ansys_gds"]["q3d_signal"]
|
| 415 |
a2n = {v["assignment"]: k for k, v in q["nets"].items()}
|
| 416 |
order = sorted(q["mapping_polygons"], key=lambda k: int(k.rsplit("_", 1)[-1]))
|
| 417 |
names = [a2n[q["mapping_polygons"][k]] for k in order]
|
|
|
|
| 686 |
}
|
| 687 |
out = write_shards(rows, out_dir, schema, extra={"build": {k: v for k, v in build.items() if k != "refused"}})
|
| 688 |
build["designs"] = {r["key"]: r["info"] for r in rows}
|
| 689 |
+
(out / "build.json").write_text(json.dumps(build, indent=1, default=str), encoding="utf-8")
|
| 690 |
return {"out_dir": str(out), "layouts": len(rows), "refused": refused, "seconds": build["seconds"]}
|
| 691 |
|
| 692 |
|
src/squadds/ml/client.py
CHANGED
|
@@ -66,9 +66,13 @@ def predict(
|
|
| 66 |
|
| 67 |
url = f"{_url(base_url)}/v1/models/{model_id}/predict"
|
| 68 |
if file is None:
|
| 69 |
-
r = requests.post(
|
|
|
|
|
|
|
| 70 |
else:
|
| 71 |
data = Path(file).read_bytes() if isinstance(file, (str, os.PathLike)) else bytes(file)
|
| 72 |
form = {"inputs": json.dumps(inputs or {}), "options": json.dumps(options or {})}
|
| 73 |
-
r = requests.post(
|
|
|
|
|
|
|
| 74 |
return _json(r)
|
|
|
|
| 66 |
|
| 67 |
url = f"{_url(base_url)}/v1/models/{model_id}/predict"
|
| 68 |
if file is None:
|
| 69 |
+
r = requests.post(
|
| 70 |
+
url, json={"inputs": inputs or {}, "options": options or {}}, headers=_headers(token), timeout=timeout
|
| 71 |
+
)
|
| 72 |
else:
|
| 73 |
data = Path(file).read_bytes() if isinstance(file, (str, os.PathLike)) else bytes(file)
|
| 74 |
form = {"inputs": json.dumps(inputs or {}), "options": json.dumps(options or {})}
|
| 75 |
+
r = requests.post(
|
| 76 |
+
url, files={"file": ("layout.gds", data)}, data=form, headers=_headers(token), timeout=timeout
|
| 77 |
+
)
|
| 78 |
return _json(r)
|
tests/test_v1.py
CHANGED
|
@@ -134,6 +134,10 @@ def test_error_envelope(client, gated_client, auth):
|
|
| 134 |
err(gated_client.post(cap, json={"inputs": {"file_base64": "%%%"}}, headers=auth), 400, "invalid_input")
|
| 135 |
err(gated_client.post(cap, json={"inputs": {"eps_r": "high"}}, headers=auth), 422, "validation_error")
|
| 136 |
err(gated_client.post(cap, files={"file": ("x.gds", b"not a gds")}, headers=auth), 400, "invalid_input")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
|
| 139 |
def test_batch_and_scaled(client):
|
|
|
|
| 134 |
err(gated_client.post(cap, json={"inputs": {"file_base64": "%%%"}}, headers=auth), 400, "invalid_input")
|
| 135 |
err(gated_client.post(cap, json={"inputs": {"eps_r": "high"}}, headers=auth), 422, "validation_error")
|
| 136 |
err(gated_client.post(cap, files={"file": ("x.gds", b"not a gds")}, headers=auth), 400, "invalid_input")
|
| 137 |
+
for t in (0.5, 0, -3, "0.2"):
|
| 138 |
+
e = err(gated_client.post(cap, files={"file": ("x.gds", gds)}, data={"inputs": json.dumps({"thickness_um": t})}, headers=auth),
|
| 139 |
+
400, "invalid_input")
|
| 140 |
+
assert "at least 1" in e["message"], e
|
| 141 |
|
| 142 |
|
| 143 |
def test_batch_and_scaled(client):
|