v4 flagship Space (3 tiers) from registry v1 (earlier contents: 906bc45ae05c)
Browse files- .dockerignore +2 -0
- Dockerfile +12 -0
- README.md +10 -5
- app.py +6 -0
- geomgnn/SOURCES.json +48 -16
- geomgnn/_tlsq/uge/blocks.py +382 -5
- geomgnn/_tlsq/uge/graph.py +24 -9
- geomgnn/_tlsq/uge/localtok.py +38 -11
- geomgnn/_tlsq/uge/nnk.py +341 -0
- geomgnn/api.py +26 -4
- geomgnn/app_flagship.py +15 -6
- geomgnn/app_paper.py +10 -6
- geomgnn/infer.py +2 -1
- geomgnn/learned_prior.py +5 -2
- geomgnn/levelpar.py +95 -0
- geomgnn/overlap.py +80 -0
- geomgnn/paper.py +42 -3
- geomgnn/respcache.py +59 -0
- geomgnn/winpool.py +137 -0
- geomgnn/x1_core.py +3 -1
- registry.yaml +10 -1
- warm.py +10 -0
.dockerignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numba_cache
|
| 2 |
+
__pycache__
|
Dockerfile
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Docker variant (agents/embedspeed, scripts/embedspeed/make_docker_space.py): numba cache baked at build time.
|
| 2 |
+
FROM python:3.12-slim
|
| 3 |
+
RUN useradd -m -u 1000 user
|
| 4 |
+
USER user
|
| 5 |
+
ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH NUMBA_CPU_NAME=generic NUMBA_CACHE_DIR=/home/user/app/numba_cache \
|
| 6 |
+
GRADIO_SERVER_NAME=0.0.0.0 PORT=7860 PYTHONUNBUFFERED=1
|
| 7 |
+
WORKDIR /home/user/app
|
| 8 |
+
COPY --chown=user requirements.txt .
|
| 9 |
+
RUN pip install --no-cache-dir --user -r requirements.txt "gradio==6.29.1"
|
| 10 |
+
COPY --chown=user . .
|
| 11 |
+
RUN TLSQ_NUM_THREADS=2 python warm.py
|
| 12 |
+
CMD ["python", "app.py"]
|
README.md
CHANGED
|
@@ -3,9 +3,8 @@ title: Planar Capacitance Model
|
|
| 3 |
emoji: 🔌
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: gray
|
| 6 |
-
sdk:
|
| 7 |
-
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
short_description: 'Maxwell capacitance of planar layouts: 3 tiers'
|
|
@@ -84,5 +83,11 @@ r = c.predict(handle_file("layout.gds"), "1/0", "1/10", 0, "Si (cryogenic, train
|
|
| 84 |
print(r["names"], r["matrix_fF"], r["timing_s"]["total_s"])
|
| 85 |
```
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
emoji: 🔌
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: gray
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
short_description: 'Maxwell capacitance of planar layouts: 3 tiers'
|
|
|
|
| 83 |
print(r["names"], r["matrix_fF"], r["timing_s"]["total_s"])
|
| 84 |
```
|
| 85 |
|
| 86 |
+
Speed: the pair vectors of every tier use far-sample decimation (blocks of 64 boundary samples farther than 100 µm from the other
|
| 87 |
+
conductor are represented by one sample); on the paper's 4,608 validation layouts and the 1-, 5- and 9-qubit lattices it ties
|
| 88 |
+
the exact embedding under the paper's tie rule, and it cuts the embedding time of a 100-qubit chip 2.6x. To reproduce the paper's
|
| 89 |
+
numbers exactly use the paper Space, which keeps the exact embedding.
|
| 90 |
+
|
| 91 |
+
Privacy: uploads are held in memory only while the Space is running, to speed up repeat requests; nothing is written to
|
| 92 |
+
permanent storage. No analytics, no file names or geometry in the logs. Hugging Face keeps ordinary web access logs under its
|
| 93 |
+
own policy.
|
app.py
CHANGED
|
@@ -11,6 +11,12 @@ if platform.machine() in ("x86_64", "AMD64"): # OpenBLAS SkylakeX Cholesky kern
|
|
| 11 |
os.environ.setdefault("OPENBLAS_CORETYPE", "Haswell")
|
| 12 |
os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
|
| 13 |
os.environ.setdefault("NUMBA_CACHE_DIR", os.path.join(os.environ.get("TMPDIR", "/tmp"), "numba_cache")) # writable on the Space
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
os.environ.pop("TLSQ_GNN_PRIOR_MODE", None) # every tier names its own solver mode (registry flagship_hub.prior_stacks)
|
| 15 |
|
| 16 |
HERE = Path(__file__).resolve().parent
|
|
|
|
| 11 |
os.environ.setdefault("OPENBLAS_CORETYPE", "Haswell")
|
| 12 |
os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
|
| 13 |
os.environ.setdefault("NUMBA_CACHE_DIR", os.path.join(os.environ.get("TMPDIR", "/tmp"), "numba_cache")) # writable on the Space
|
| 14 |
+
# Speed (agents/embedspeed): in-memory LRU of finished responses and the per-body embedding cache on /tmp, both size-bounded
|
| 15 |
+
# (uploads are held only while the Space runs; nothing is written to permanent storage).
|
| 16 |
+
os.environ.setdefault("TLSQ_RESPONSE_CACHE", "64")
|
| 17 |
+
os.environ.setdefault("TLSQ_RESPONSE_CACHE_MB", "1024")
|
| 18 |
+
os.environ.setdefault("TLSQ_EMBED_CACHE", os.path.join(os.environ.get("TMPDIR", "/tmp"), "tlsq_embed_cache"))
|
| 19 |
+
os.environ.setdefault("TLSQ_EMBED_CACHE_MB", "1024")
|
| 20 |
os.environ.pop("TLSQ_GNN_PRIOR_MODE", None) # every tier names its own solver mode (registry flagship_hub.prior_stacks)
|
| 21 |
|
| 22 |
HERE = Path(__file__).resolve().parent
|
geomgnn/SOURCES.json
CHANGED
|
@@ -45,23 +45,31 @@
|
|
| 45 |
"rewrites": []
|
| 46 |
},
|
| 47 |
"_tlsq/uge/blocks.py": {
|
| 48 |
-
"source": "/Users/shanto/
|
| 49 |
-
"source_sha256": "
|
| 50 |
-
"sha256": "
|
| 51 |
-
"rewrites": []
|
|
|
|
|
|
|
|
|
|
| 52 |
},
|
| 53 |
"_tlsq/uge/graph.py": {
|
| 54 |
-
"source": "/Users/shanto/
|
| 55 |
-
"source_sha256": "
|
| 56 |
-
"sha256": "
|
| 57 |
-
"rewrites": []
|
|
|
|
|
|
|
|
|
|
| 58 |
},
|
| 59 |
"_tlsq/uge/localtok.py": {
|
| 60 |
-
"source": "/Users/shanto/
|
| 61 |
-
"source_sha256": "
|
| 62 |
-
"sha256": "
|
| 63 |
"rewrites": [],
|
| 64 |
-
"note": "byte-identical to the stage
|
|
|
|
|
|
|
| 65 |
},
|
| 66 |
"_tlsq/uge/proxies.py": {
|
| 67 |
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/proxies.py",
|
|
@@ -84,7 +92,7 @@
|
|
| 84 |
"infer.py": {
|
| 85 |
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/infer.py",
|
| 86 |
"source_sha256": "f1829b165b1c1abac5e9e8b6e9ccda8bcf91f977c331ee4b408615455e902d09",
|
| 87 |
-
"sha256": "
|
| 88 |
"rewrites": [
|
| 89 |
[
|
| 90 |
"W=Path(__file__).resolve().parent;sys.path.insert(0,str(W/'vendor'))",
|
|
@@ -117,8 +125,17 @@
|
|
| 117 |
[
|
| 118 |
" from tlsq.embed.fastprior_loc import micro_mom_loc",
|
| 119 |
" from ._tlsq.embed.fastprior_loc import micro_mom_loc"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
]
|
| 121 |
-
]
|
|
|
|
| 122 |
},
|
| 123 |
"fastmom.py": {
|
| 124 |
"source": "/Users/shanto/LFL/tl_squadds/scripts/geomfast/fastmom.py",
|
|
@@ -174,7 +191,7 @@
|
|
| 174 |
"x1_core.py": {
|
| 175 |
"source": "/Users/shanto/LFL/tl_squadds/scripts/v4test/x1_core.py",
|
| 176 |
"source_sha256": "f4ee1cb4074eb7a3dc019072722f36d58a320d6bf711af3c66c7a5cbc96499cc",
|
| 177 |
-
"sha256": "
|
| 178 |
"rewrites": [
|
| 179 |
[
|
| 180 |
" from train_mf import build",
|
|
@@ -183,9 +200,24 @@
|
|
| 183 |
[
|
| 184 |
" import lp_surrogate as S",
|
| 185 |
" from . import lp_surrogate as S"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
]
|
| 187 |
],
|
| 188 |
-
"note": "X1 shared model code (multifid forward, Richardson c0, to_maxwell); paper Space arms; vendored 2026-10-19, import lines rewritten"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
}
|
| 190 |
}
|
| 191 |
}
|
|
|
|
| 45 |
"rewrites": []
|
| 46 |
},
|
| 47 |
"_tlsq/uge/blocks.py": {
|
| 48 |
+
"source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/blocks.py",
|
| 49 |
+
"source_sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c",
|
| 50 |
+
"sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c",
|
| 51 |
+
"rewrites": [],
|
| 52 |
+
"note": "agents/embedspeed (2026-10-20): the training-source copy src/tlsq/uge (byte-identical). Exact batched embedding, numba NN kernel, edge table, numex / far-decimation / cache modes; in the default bitwise mode every feature is bit-identical to the frozen stage file (deploy/tests/test_embed_parity.py, tests/test_embed_parity_src.py, deploy/tests/test_embed_regression.py).",
|
| 53 |
+
"frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/blocks.py",
|
| 54 |
+
"frozen_stage_sha256": "c58313f167f7df0ef0de6b321ab6b7214a661aef10b461e2bf90a60999fb4632"
|
| 55 |
},
|
| 56 |
"_tlsq/uge/graph.py": {
|
| 57 |
+
"source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/graph.py",
|
| 58 |
+
"source_sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa",
|
| 59 |
+
"sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa",
|
| 60 |
+
"rewrites": [],
|
| 61 |
+
"note": "agents/embedspeed (2026-10-20): the training-source copy src/tlsq/uge (byte-identical). Exact batched embedding, numba NN kernel, edge table, numex / far-decimation / cache modes; in the default bitwise mode every feature is bit-identical to the frozen stage file (deploy/tests/test_embed_parity.py, tests/test_embed_parity_src.py, deploy/tests/test_embed_regression.py).",
|
| 62 |
+
"frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/graph.py",
|
| 63 |
+
"frozen_stage_sha256": "aeb8c58cf6c1d2169eab8a58fba362634d7489f3414f260a9fc55a02048217ee"
|
| 64 |
},
|
| 65 |
"_tlsq/uge/localtok.py": {
|
| 66 |
+
"source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/localtok.py",
|
| 67 |
+
"source_sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd",
|
| 68 |
+
"sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd",
|
| 69 |
"rewrites": [],
|
| 70 |
+
"note": "agents/embedspeed (2026-10-20): the training-source copy src/tlsq/uge (byte-identical). Exact batched embedding, numba NN kernel, edge table, numex / far-decimation / cache modes; in the default bitwise mode every feature is bit-identical to the frozen stage file (deploy/tests/test_embed_parity.py, tests/test_embed_parity_src.py, deploy/tests/test_embed_regression.py).",
|
| 71 |
+
"frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/localtok.py",
|
| 72 |
+
"frozen_stage_sha256": "8b47bd454353709a29ad996243d0f8b4b0d94991ee43715145af41a912dd9319"
|
| 73 |
},
|
| 74 |
"_tlsq/uge/proxies.py": {
|
| 75 |
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/proxies.py",
|
|
|
|
| 92 |
"infer.py": {
|
| 93 |
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/infer.py",
|
| 94 |
"source_sha256": "f1829b165b1c1abac5e9e8b6e9ccda8bcf91f977c331ee4b408615455e902d09",
|
| 95 |
+
"sha256": "cee37e8ed6f229363801b9a8118aea9dfb4ce5f476e6e2d8ff13cfa734e87b96",
|
| 96 |
"rewrites": [
|
| 97 |
[
|
| 98 |
"W=Path(__file__).resolve().parent;sys.path.insert(0,str(W/'vendor'))",
|
|
|
|
| 125 |
[
|
| 126 |
" from tlsq.embed.fastprior_loc import micro_mom_loc",
|
| 127 |
" from ._tlsq.embed.fastprior_loc import micro_mom_loc"
|
| 128 |
+
],
|
| 129 |
+
[
|
| 130 |
+
"from ._tlsq.uge.graph import scene_graph\n",
|
| 131 |
+
"from ._tlsq.uge.graph import scene_graph\nfrom ._tlsq.uge.blocks import edge_matrix\n"
|
| 132 |
+
],
|
| 133 |
+
[
|
| 134 |
+
"E=np.array([[row['edges'][tuple(p)][k] for k in ek] for p in pairs],np.float32)[None]",
|
| 135 |
+
"E=edge_matrix(row['edges'],ek,n)[None]"
|
| 136 |
]
|
| 137 |
+
],
|
| 138 |
+
"note": "agents/embedspeed: E from edge_matrix (array edge table or the dicts; same float32 values)."
|
| 139 |
},
|
| 140 |
"fastmom.py": {
|
| 141 |
"source": "/Users/shanto/LFL/tl_squadds/scripts/geomfast/fastmom.py",
|
|
|
|
| 191 |
"x1_core.py": {
|
| 192 |
"source": "/Users/shanto/LFL/tl_squadds/scripts/v4test/x1_core.py",
|
| 193 |
"source_sha256": "f4ee1cb4074eb7a3dc019072722f36d58a320d6bf711af3c66c7a5cbc96499cc",
|
| 194 |
+
"sha256": "0a4be5ec3b8819bdc6d6314775c7f8acf46f4a54569d975011726ec1912c5100",
|
| 195 |
"rewrites": [
|
| 196 |
[
|
| 197 |
" from train_mf import build",
|
|
|
|
| 200 |
[
|
| 201 |
" import lp_surrogate as S",
|
| 202 |
" from . import lp_surrogate as S"
|
| 203 |
+
],
|
| 204 |
+
[
|
| 205 |
+
"import numpy as np\n",
|
| 206 |
+
"import numpy as np\n\nfrom ._tlsq.uge.blocks import edge_matrix\n"
|
| 207 |
+
],
|
| 208 |
+
[
|
| 209 |
+
" E = np.array([[row['edges'][tuple(p)][k] for k in ek] for p in pairs], np.float32).reshape(len(pairs), len(ek))",
|
| 210 |
+
" E = edge_matrix(row['edges'], ek, n)"
|
| 211 |
]
|
| 212 |
],
|
| 213 |
+
"note": "X1 shared model code (multifid forward, Richardson c0, to_maxwell); paper Space arms; vendored 2026-10-19, import lines rewritten agents/embedspeed: E from edge_matrix (same float32 values)."
|
| 214 |
+
},
|
| 215 |
+
"_tlsq/uge/nnk.py": {
|
| 216 |
+
"source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/nnk.py",
|
| 217 |
+
"source_sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84",
|
| 218 |
+
"sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84",
|
| 219 |
+
"rewrites": [],
|
| 220 |
+
"note": "agents/embedspeed (2026-10-20): the training-source copy src/tlsq/uge (byte-identical). Exact batched embedding, numba NN kernel, edge table, numex / far-decimation / cache modes; in the default bitwise mode every feature is bit-identical to the frozen stage file (deploy/tests/test_embed_parity.py, tests/test_embed_parity_src.py, deploy/tests/test_embed_regression.py)."
|
| 221 |
}
|
| 222 |
}
|
| 223 |
}
|
geomgnn/_tlsq/uge/blocks.py
CHANGED
|
@@ -3,11 +3,18 @@ physical units (log µm, ratios) so that nothing is fitted to a dataset."""
|
|
| 3 |
|
| 4 |
from __future__ import annotations
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import numpy as np
|
| 7 |
import shapely
|
| 8 |
from scipy.special import ellipk
|
| 9 |
from scipy.spatial import cKDTree
|
| 10 |
|
|
|
|
| 11 |
from ..embed.proxy import _nthreads
|
| 12 |
from ..geometry import fourier_descriptors, sample_boundary, shape_metrics
|
| 13 |
from .scene import Scene
|
|
@@ -131,6 +138,376 @@ def edge_features(scene: Scene, i: int, j: int, bpts: dict, widths: dict) -> dic
|
|
| 131 |
return f
|
| 132 |
|
| 133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
def global_features(scene: Scene) -> dict:
|
| 135 |
st = scene.stack
|
| 136 |
n_sig = sum(c.role == "signal" for c in scene.conductors)
|
|
@@ -141,9 +518,9 @@ def global_features(scene: Scene) -> dict:
|
|
| 141 |
|
| 142 |
|
| 143 |
def boundary_points(scene: Scene) -> tuple[dict, dict]:
|
| 144 |
-
|
| 145 |
-
for i, c in enumerate(scene.conductors):
|
| 146 |
g = region(scene, i)
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
| 3 |
|
| 4 |
from __future__ import annotations
|
| 5 |
|
| 6 |
+
import hashlib
|
| 7 |
+
import os
|
| 8 |
+
import pickle
|
| 9 |
+
from collections.abc import Mapping
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
import numpy as np
|
| 13 |
import shapely
|
| 14 |
from scipy.special import ellipk
|
| 15 |
from scipy.spatial import cKDTree
|
| 16 |
|
| 17 |
+
from .. import geometry as _geometry
|
| 18 |
from ..embed.proxy import _nthreads
|
| 19 |
from ..geometry import fourier_descriptors, sample_boundary, shape_metrics
|
| 20 |
from .scene import Scene
|
|
|
|
| 138 |
return f
|
| 139 |
|
| 140 |
|
| 141 |
+
TREE_LEAFSIZE = 32 # nearest distances do not depend on the leaf size (cKDTree's own distance arithmetic); 32 is fastest
|
| 142 |
+
NN_KERNEL: dict = {"on": os.environ.get("TLSQ_NN_KERNEL", "1") == "1"} # numba exact NN (nnk.py), probe-verified
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _tree(P: np.ndarray):
|
| 146 |
+
"""Nearest-sample structure of one conductor: the numba kernel when its probe reproduces cKDTree here, else cKDTree."""
|
| 147 |
+
if NN_KERNEL["on"]:
|
| 148 |
+
try:
|
| 149 |
+
from . import nnk
|
| 150 |
+
except ImportError:
|
| 151 |
+
nnk = None
|
| 152 |
+
if nnk is not None and nnk.available():
|
| 153 |
+
return nnk.Tree(P)
|
| 154 |
+
return cKDTree(P, leafsize=TREE_LEAFSIZE)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _dist(tree, X: np.ndarray) -> np.ndarray:
|
| 158 |
+
return tree.query(X)[0] if isinstance(tree, cKDTree) else tree.dist(X)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
_EDGES_HI = np.r_[SEP_EDGES_UM[:-1], np.nextafter(SEP_EDGES_UM[-1], np.inf)] # np.histogram: last bin closed
|
| 162 |
+
_CHUNK = 1 << 20 # distances per task (rows x samples)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _dir_stats(X: np.ndarray, trees: list, bs: list, w1: float, widths: dict) -> tuple:
|
| 166 |
+
"""edge_features' per-direction statistics of the samples X of one conductor against each conductor in bs (all signal,
|
| 167 |
+
or the ground alone): minimum distance, histogram counts, the three moment sums and the conformal sum. The same
|
| 168 |
+
element-wise operations and pairwise row sums as edge_features (bit-identical)."""
|
| 169 |
+
nb = len(bs)
|
| 170 |
+
D = np.empty((nb, len(X)))
|
| 171 |
+
for r, b in enumerate(bs):
|
| 172 |
+
D[r] = _dist(trees[b], X)
|
| 173 |
+
dmin = D.min(1)
|
| 174 |
+
k = np.searchsorted(_EDGES_HI, D, side="right")
|
| 175 |
+
k += (12 * np.arange(nb))[:, None]
|
| 176 |
+
cnt = np.bincount(k.ravel(), minlength=12 * nb).reshape(nb, 12)[:, 1:11]
|
| 177 |
+
del k
|
| 178 |
+
dd = np.maximum(D, 0.05, out=D)
|
| 179 |
+
mom = np.stack([np.sum(STEP_UM * dd ** (-p), axis=1) for p in MOMENTS], 1)
|
| 180 |
+
w2 = np.array([widths[b] for b in bs])[:, None]
|
| 181 |
+
if np.isinf(w1):
|
| 182 |
+
mm = dd / (dd + w2)
|
| 183 |
+
elif np.isinf(w2).any():
|
| 184 |
+
mm = dd / (dd + w1)
|
| 185 |
+
else:
|
| 186 |
+
mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2))
|
| 187 |
+
cps = np.sum(STEP_UM * _kratio(mm), axis=1)
|
| 188 |
+
return dmin, cnt, mom, cps
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# "bitwise" (default; training / reproduction): every feature bit-identical to the published code. "numex" (numerically exact;
|
| 192 |
+
# inference): node features and signal-signal directions computed once per class of translated copies (same shape to 1e-6
|
| 193 |
+
# um, same offset) and shared; values differ from bitwise in the last bits only (agents/embedspeed/RESULTS.md).
|
| 194 |
+
EMBED_MODE: dict = {"mode": os.environ.get("TLSQ_EMBED_MODE", "bitwise")}
|
| 195 |
+
FAR_DECIMATION: dict = {"k": 0, "d_far": 100.0}
|
| 196 |
+
# Edge storage: False (default; training) = a dict per pair; True (inference) = EdgeTable, one float64 array per key.
|
| 197 |
+
EDGE_TABLE: dict = {"on": os.environ.get("TLSQ_EDGE_TABLE", "0") == "1"}
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class EdgeTable(Mapping):
|
| 201 |
+
"""Read-only complete-graph edges: pairs i < j in combinations order, one float64 column per key (same values as the
|
| 202 |
+
dict per pair; `npcols` are returned as numpy float64, the others as Python floats). table[(i, j)] builds that pair's
|
| 203 |
+
dict on request; matrix(keys) gives the (P, len(keys)) array without building any dict."""
|
| 204 |
+
|
| 205 |
+
def __init__(self, n: int, cols: dict, npcols=()):
|
| 206 |
+
self.n, self.cols, self.npcols = n, cols, frozenset(npcols)
|
| 207 |
+
|
| 208 |
+
def _r(self, p) -> int:
|
| 209 |
+
i, j = int(p[0]), int(p[1])
|
| 210 |
+
if not 0 <= i < j < self.n:
|
| 211 |
+
raise KeyError(p)
|
| 212 |
+
return i * (2 * self.n - i - 1) // 2 + j - i - 1
|
| 213 |
+
|
| 214 |
+
def __getitem__(self, p) -> dict:
|
| 215 |
+
r = self._r(p)
|
| 216 |
+
return {k: (v[r] if k in self.npcols else float(v[r])) for k, v in self.cols.items()}
|
| 217 |
+
|
| 218 |
+
def __iter__(self):
|
| 219 |
+
return ((i, j) for i in range(self.n) for j in range(i + 1, self.n))
|
| 220 |
+
|
| 221 |
+
def __len__(self) -> int:
|
| 222 |
+
return self.n * (self.n - 1) // 2
|
| 223 |
+
|
| 224 |
+
def matrix(self, keys, dtype=np.float32) -> np.ndarray:
|
| 225 |
+
if not len(self):
|
| 226 |
+
return np.zeros((0, len(keys)), dtype)
|
| 227 |
+
return np.stack([self.cols[k] for k in keys], 1).astype(dtype)
|
| 228 |
+
|
| 229 |
+
def with_cols(self, new: dict, drop=(), npcols=()) -> "EdgeTable":
|
| 230 |
+
cols = {k: v for k, v in self.cols.items() if k not in drop}
|
| 231 |
+
return EdgeTable(self.n, {**cols, **new}, (self.npcols | frozenset(npcols)) - frozenset(drop))
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def edge_matrix(edges, keys, n: int, dtype=np.float32) -> np.ndarray:
|
| 235 |
+
"""(P, len(keys)) array of the edge features (pairs i < j): the table's columns, or the per-pair dicts as before."""
|
| 236 |
+
if isinstance(edges, EdgeTable):
|
| 237 |
+
return edges.matrix(keys, dtype)
|
| 238 |
+
pairs = [(i, j) for i in range(n) for j in range(i + 1, n)]
|
| 239 |
+
return np.array([[edges[p][k] for k in keys] for p in pairs], dtype).reshape(len(pairs), len(keys)) # approximation arm (agents/embedspeed/PROTOCOL.md Part A); k = 0: exact
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _dir_stats_far(X: np.ndarray, trees: list, bs: list, w1: float, widths: dict) -> tuple:
|
| 243 |
+
"""Approximate _dir_stats (block decimation of PRIOR_SCHEME.md 14.3.1): blocks of k consecutive samples of a whose first
|
| 244 |
+
sample is farther than d_far from b are represented by that sample with weight k (the last block by its size). Distances
|
| 245 |
+
per row (far representatives, then the near samples), statistics for the whole chunk at once (weighted sums)."""
|
| 246 |
+
k, r = FAR_DECIMATION["k"], FAR_DECIMATION["d_far"]
|
| 247 |
+
rep = np.arange(0, len(X), k)
|
| 248 |
+
size = np.diff(np.r_[rep, len(X)])
|
| 249 |
+
nb = len(bs)
|
| 250 |
+
Xr = X[rep]
|
| 251 |
+
ds, ws, rows = [], [], []
|
| 252 |
+
for row, b in enumerate(bs):
|
| 253 |
+
d_rep = _dist(trees[b], Xr)
|
| 254 |
+
far = d_rep > r
|
| 255 |
+
if far.all():
|
| 256 |
+
d, wq = d_rep, size.astype(float)
|
| 257 |
+
else:
|
| 258 |
+
near = np.repeat(~far, size)
|
| 259 |
+
d = np.r_[d_rep[far], _dist(trees[b], X[near])]
|
| 260 |
+
wq = np.r_[size[far].astype(float), np.ones(int(near.sum()))]
|
| 261 |
+
ds.append(d)
|
| 262 |
+
ws.append(wq)
|
| 263 |
+
rows.append(np.full(len(d), row))
|
| 264 |
+
d, wq, rid = np.concatenate(ds), np.concatenate(ws), np.concatenate(rows)
|
| 265 |
+
starts = np.r_[0, np.cumsum([len(x) for x in ds])[:-1]]
|
| 266 |
+
dmin = np.minimum.reduceat(d, starts)
|
| 267 |
+
kb = np.searchsorted(_EDGES_HI, d, side="right")
|
| 268 |
+
cnt = np.rint(np.bincount(rid * 12 + kb, weights=wq, minlength=12 * nb)).astype(np.int64).reshape(nb, 12)[:, 1:11]
|
| 269 |
+
dd = np.maximum(d, 0.05)
|
| 270 |
+
mom = np.stack([np.bincount(rid, weights=STEP_UM * wq * dd ** (-p), minlength=nb) for p in MOMENTS], 1)
|
| 271 |
+
w2 = np.array([widths[b] for b in bs])[rid]
|
| 272 |
+
if np.isinf(w1):
|
| 273 |
+
mm = dd / (dd + w2)
|
| 274 |
+
elif np.isinf(w2).any():
|
| 275 |
+
mm = dd / (dd + w1)
|
| 276 |
+
else:
|
| 277 |
+
mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2))
|
| 278 |
+
cps = np.bincount(rid, weights=STEP_UM * wq * _kratio(mm), minlength=nb)
|
| 279 |
+
return dmin, cnt, mom, cps
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _pmap(fn, items: list, threads: int) -> list:
|
| 283 |
+
if threads < 2 or len(items) < 2:
|
| 284 |
+
return [fn(x) for x in items]
|
| 285 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 286 |
+
|
| 287 |
+
with ThreadPoolExecutor(threads, thread_name_prefix="tlsq-edges") as ex:
|
| 288 |
+
return list(ex.map(fn, items))
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
# Optional persistent cache (exact): per-body node features and per-direction pair statistics, keyed by the body's region
|
| 292 |
+
# (WKB) and role, under a key of this code, the parameters and the machine / library versions (a value is reused only where
|
| 293 |
+
# this machine would recompute it bit for bit). Off unless TLSQ_EMBED_CACHE (or EMBED_CACHE["dir"]) names a directory.
|
| 294 |
+
EMBED_CACHE: dict = {"dir": os.environ.get("TLSQ_EMBED_CACHE") or None}
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _code_key() -> str:
|
| 298 |
+
import platform
|
| 299 |
+
|
| 300 |
+
import scipy
|
| 301 |
+
|
| 302 |
+
h = hashlib.sha256()
|
| 303 |
+
for f in (__file__, _geometry.__file__):
|
| 304 |
+
h.update(Path(f).read_bytes())
|
| 305 |
+
h.update(repr((platform.machine(), platform.system(), np.__version__, scipy.__version__, shapely.__version__, STEP_UM,
|
| 306 |
+
SEP_EDGES_UM.tolist(), MOMENTS, TREE_LEAFSIZE, TOKEN_VARIANT["name"], EMBED_MODE["mode"],
|
| 307 |
+
NN_KERNEL["on"])).encode())
|
| 308 |
+
return h.hexdigest()[:24]
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def body_keys(scene: Scene) -> list:
|
| 312 |
+
return [hashlib.sha256(c.role.encode() + shapely.to_wkb(region(scene, i))).hexdigest()[:32]
|
| 313 |
+
for i, c in enumerate(scene.conductors)]
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class _Cache:
|
| 317 |
+
def __init__(self, root):
|
| 318 |
+
self.d = Path(root) / _code_key()
|
| 319 |
+
for sub in ("dir", "node"):
|
| 320 |
+
(self.d / sub).mkdir(parents=True, exist_ok=True)
|
| 321 |
+
|
| 322 |
+
def _put(self, path: Path, write):
|
| 323 |
+
tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
|
| 324 |
+
with open(tmp, "wb") as fh:
|
| 325 |
+
write(fh)
|
| 326 |
+
os.replace(tmp, path)
|
| 327 |
+
|
| 328 |
+
def nodes(self, keys: list) -> dict:
|
| 329 |
+
out = {}
|
| 330 |
+
for i, k in enumerate(keys):
|
| 331 |
+
p = self.d / "node" / f"{k}.pkl"
|
| 332 |
+
if p.exists():
|
| 333 |
+
out[i] = pickle.loads(p.read_bytes())
|
| 334 |
+
return out
|
| 335 |
+
|
| 336 |
+
def put_node(self, key: str, f: dict):
|
| 337 |
+
self._put(self.d / "node" / f"{key}.pkl", lambda fh: pickle.dump(f, fh, protocol=5))
|
| 338 |
+
|
| 339 |
+
def rows(self, ka: str):
|
| 340 |
+
p = self.d / "dir" / f"{ka}.npz"
|
| 341 |
+
if not p.exists():
|
| 342 |
+
return None
|
| 343 |
+
z = np.load(p)
|
| 344 |
+
return {str(k): r for r, k in enumerate(z["keys"])}, z["dmin"], z["cnt"], z["mom"], z["cps"]
|
| 345 |
+
|
| 346 |
+
def put_rows(self, ka: str, keys: list, dmin, cnt, mom, cps):
|
| 347 |
+
old = self.rows(ka)
|
| 348 |
+
if old is not None:
|
| 349 |
+
idx, *arr = old
|
| 350 |
+
ks = set(keys)
|
| 351 |
+
extra = [r for k, r in idx.items() if k not in ks]
|
| 352 |
+
keys = list(keys) + [k for k, r in idx.items() if k not in ks]
|
| 353 |
+
dmin, cnt, mom, cps = (np.concatenate([x, y[extra]]) for x, y in zip((dmin, cnt, mom, cps), arr))
|
| 354 |
+
self._put(self.d / "dir" / f"{ka}.npz",
|
| 355 |
+
lambda fh: np.savez(fh, keys=np.array(keys), dmin=dmin, cnt=cnt, mom=mom, cps=cps))
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def trim(self):
|
| 359 |
+
"""Size bound (TLSQ_EMBED_CACHE_MB): the least recently written entries are removed down to 80 % of the bound."""
|
| 360 |
+
mb = os.environ.get("TLSQ_EMBED_CACHE_MB")
|
| 361 |
+
if not mb:
|
| 362 |
+
return
|
| 363 |
+
lim = float(mb) * 2**20
|
| 364 |
+
files = [e for sub in ("dir", "node") for e in os.scandir(self.d / sub) if e.is_file()]
|
| 365 |
+
tot = sum(e.stat().st_size for e in files)
|
| 366 |
+
if tot <= lim:
|
| 367 |
+
return
|
| 368 |
+
for e in sorted(files, key=lambda e: e.stat().st_mtime):
|
| 369 |
+
if tot <= 0.8 * lim:
|
| 370 |
+
break
|
| 371 |
+
try:
|
| 372 |
+
tot -= e.stat().st_size
|
| 373 |
+
os.remove(e.path)
|
| 374 |
+
except OSError:
|
| 375 |
+
pass
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _cache():
|
| 379 |
+
return _Cache(EMBED_CACHE["dir"]) if EMBED_CACHE["dir"] else None
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def shape_classes(scene: Scene, bpts: dict | None = None) -> tuple:
|
| 383 |
+
"""Translation classes of the signal bodies (numex mode): class id per conductor (-1 = ground, its own class) from the
|
| 384 |
+
coordinates relative to the bounding-box corner rounded to 1e-6 um and the ring structure, and, with bpts, from the
|
| 385 |
+
boundary samples relative to that corner rounded to 1e-9 um (a translated copy can get one sample more or fewer when a
|
| 386 |
+
ring length is a multiple of the step); integer origins (1e-6 um)."""
|
| 387 |
+
ids, cid, org = {}, np.full(scene.n, -1), np.zeros((scene.n, 2), np.int64)
|
| 388 |
+
for i, c in enumerate(scene.conductors):
|
| 389 |
+
if c.role == "ground":
|
| 390 |
+
continue
|
| 391 |
+
g = region(scene, i)
|
| 392 |
+
o = np.array(g.bounds[:2])
|
| 393 |
+
rings = [len(r.coords) for q in getattr(g, "geoms", [g]) for r in (q.exterior, *q.interiors)]
|
| 394 |
+
h = hashlib.sha1(repr((c.role, g.geom_type, rings)).encode() + (np.round(shapely.get_coordinates(g) - o, 6) + 0.0).tobytes())
|
| 395 |
+
if bpts is not None:
|
| 396 |
+
h.update((np.round(bpts[i] - o, 9) + 0.0).tobytes())
|
| 397 |
+
cid[i] = ids.setdefault(h.hexdigest(), len(ids))
|
| 398 |
+
org[i] = np.rint(o * 1e6).astype(np.int64)
|
| 399 |
+
return cid, org
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def node_features_all(scene: Scene, keys: list | None = None) -> list:
|
| 403 |
+
"""[node_features(scene, i) for every conductor], threads over the conductors, reusing the persistent cache (numex:
|
| 404 |
+
once per translation class)."""
|
| 405 |
+
c = _cache()
|
| 406 |
+
keys = keys if keys is not None or c is None else body_keys(scene)
|
| 407 |
+
hit = c.nodes(keys) if c else {}
|
| 408 |
+
miss = [i for i in range(scene.n) if i not in hit]
|
| 409 |
+
rep = {}
|
| 410 |
+
if EMBED_MODE["mode"] == "numex":
|
| 411 |
+
cid = shape_classes(scene)[0]
|
| 412 |
+
first = {}
|
| 413 |
+
rep = {i: first.setdefault(cid[i], i) for i in miss if cid[i] >= 0}
|
| 414 |
+
rep = {i: r for i, r in rep.items() if r != i}
|
| 415 |
+
new = dict(zip([i for i in miss if i not in rep], _pmap(lambda i: node_features(scene, i), [i for i in miss if i not in rep], _nthreads())))
|
| 416 |
+
new.update({i: dict(new[r]) for i, r in rep.items()})
|
| 417 |
+
if c:
|
| 418 |
+
for i, f in new.items():
|
| 419 |
+
c.put_node(keys[i], f)
|
| 420 |
+
c.trim()
|
| 421 |
+
return [hit[i] if i in hit else new[i] for i in range(scene.n)]
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def edge_features_all(scene: Scene, bpts: dict, widths: dict, keys: list | None = None) -> dict:
|
| 425 |
+
"""{(i, j): edge_features(scene, i, j, bpts, widths)} for every pair i < j, bit-identical, batched: one k-d tree per
|
| 426 |
+
conductor, every direction a -> b as rows of one distance array per (a, chunk of b), threads over the chunks (the
|
| 427 |
+
queries and ufuncs release the GIL); directions found in the persistent cache are not recomputed."""
|
| 428 |
+
n = scene.n
|
| 429 |
+
pairs = [(i, j) for i in range(n) for j in range(i + 1, n)]
|
| 430 |
+
if TOKEN_VARIANT["name"] != "exact" or n < 2:
|
| 431 |
+
return {(i, j): edge_features(scene, i, j, bpts, widths) for i, j in pairs}
|
| 432 |
+
th = _nthreads()
|
| 433 |
+
DM, CP = np.empty((n, n)), np.empty((n, n))
|
| 434 |
+
CN, MO = np.empty((n, n, 10), np.int64), np.empty((n, n, len(MOMENTS)))
|
| 435 |
+
c = _cache() if not FAR_DECIMATION["k"] else None
|
| 436 |
+
if c and keys is None:
|
| 437 |
+
keys = body_keys(scene)
|
| 438 |
+
todo = {a: [b for b in range(n) if b != a] for a in range(n)}
|
| 439 |
+
if c:
|
| 440 |
+
for a in range(n):
|
| 441 |
+
got = c.rows(keys[a])
|
| 442 |
+
if got is None:
|
| 443 |
+
continue
|
| 444 |
+
idx, dm, cn, mo, cp = got
|
| 445 |
+
have = [b for b in todo[a] if keys[b] in idx]
|
| 446 |
+
r = [idx[keys[b]] for b in have]
|
| 447 |
+
DM[a, have], CN[a, have], MO[a, have], CP[a, have] = dm[r], cn[r], mo[r], cp[r]
|
| 448 |
+
todo[a] = [b for b in todo[a] if keys[b] not in idx]
|
| 449 |
+
share = None
|
| 450 |
+
if EMBED_MODE["mode"] == "numex":
|
| 451 |
+
cid, org = shape_classes(scene, bpts)
|
| 452 |
+
A, B = np.nonzero((cid[:, None] >= 0) & (cid[None, :] >= 0) & ~np.eye(n, dtype=bool))
|
| 453 |
+
K = np.c_[cid[A], cid[B], org[B] - org[A]]
|
| 454 |
+
_, first, inv = np.unique(K, axis=0, return_index=True, return_inverse=True)
|
| 455 |
+
R = first[inv.ravel()]
|
| 456 |
+
share = (A, B, A[R], B[R])
|
| 457 |
+
drop = np.zeros((n, n), bool)
|
| 458 |
+
drop[A[R != np.arange(len(A))], B[R != np.arange(len(A))]] = True
|
| 459 |
+
todo = {a: [b for b in bs if not drop[a, b]] for a, bs in todo.items()}
|
| 460 |
+
tasks = []
|
| 461 |
+
for a, bs in todo.items():
|
| 462 |
+
sig = [b for b in bs if not np.isinf(widths[b])]
|
| 463 |
+
tasks += [(a, [b]) for b in bs if np.isinf(widths[b])]
|
| 464 |
+
step = max(1, _CHUNK // len(bpts[a]))
|
| 465 |
+
tasks += [(a, sig[k:k + step]) for k in range(0, len(sig), step)]
|
| 466 |
+
tasks.sort(key=lambda t: -len(t[1]) * len(bpts[t[0]]))
|
| 467 |
+
need = sorted({b for _, bs in tasks for b in bs})
|
| 468 |
+
trees = dict(zip(need, _pmap(lambda i: _tree(bpts[i]), need, th)))
|
| 469 |
+
|
| 470 |
+
def run(t):
|
| 471 |
+
a, bs = t
|
| 472 |
+
f = _dir_stats_far if FAR_DECIMATION["k"] else _dir_stats
|
| 473 |
+
DM[a, bs], CN[a, bs], MO[a, bs], CP[a, bs] = f(bpts[a], trees, bs, widths[a], widths)
|
| 474 |
+
|
| 475 |
+
_pmap(run, tasks, th)
|
| 476 |
+
if share is not None:
|
| 477 |
+
A, B, RA, RB = share
|
| 478 |
+
DM[A, B], CN[A, B], MO[A, B], CP[A, B] = DM[RA, RB], CN[RA, RB], MO[RA, RB], CP[RA, RB]
|
| 479 |
+
if c:
|
| 480 |
+
for a in {t[0] for t in tasks}:
|
| 481 |
+
bs = [b for b in range(n) if b != a]
|
| 482 |
+
c.put_rows(keys[a], [keys[b] for b in bs], DM[a, bs], CN[a, bs], MO[a, bs], CP[a, bs])
|
| 483 |
+
c.trim()
|
| 484 |
+
return _assemble(scene, DM, CN, MO, CP)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _assemble(scene: Scene, DM, CN, MO, CP) -> dict:
|
| 488 |
+
"""Pair dicts from the per-direction statistics, in edge_features' operation order and key order."""
|
| 489 |
+
n = scene.n
|
| 490 |
+
I, J = np.triu_indices(n, 1)
|
| 491 |
+
dmin = np.minimum(DM[I, J], DM[J, I])
|
| 492 |
+
hist = 0.5 * (STEP_UM * CN[I, J]) + 0.5 * (STEP_UM * CN[J, I])
|
| 493 |
+
mom = 0.5 * MO[I, J] + 0.5 * MO[J, I]
|
| 494 |
+
cps = 0.5 * CP[I, J] + 0.5 * CP[J, I]
|
| 495 |
+
gnd = np.array([c.role == "ground" for c in scene.conductors])
|
| 496 |
+
cols = {"is_ground_pair": (gnd[I] | gnd[J]).astype(float), "log_dmin": np.log(np.maximum(dmin, 1e-9))}
|
| 497 |
+
sep = np.log1p(hist)
|
| 498 |
+
for k in range(sep.shape[1]):
|
| 499 |
+
cols[f"sep_{k:02d}"] = sep[:, k]
|
| 500 |
+
lm = np.log(np.maximum(mom, 1e-9))
|
| 501 |
+
for k, p in enumerate(MOMENTS):
|
| 502 |
+
cols[f"mom_{p:g}"] = lm[:, k]
|
| 503 |
+
cols["log_cps"] = np.log(np.maximum(cps, 1e-9))
|
| 504 |
+
if EDGE_TABLE["on"]:
|
| 505 |
+
return EdgeTable(n, {**cols, "_cps": cps}, ("_cps",))
|
| 506 |
+
keys = list(cols)
|
| 507 |
+
rows = zip(*[cols[k].tolist() for k in keys], list(cps))
|
| 508 |
+
return {(i, j): {**dict(zip(keys, r[:-1])), "_cps": r[-1]} for i, j, r in zip(I.tolist(), J.tolist(), rows)}
|
| 509 |
+
|
| 510 |
+
|
| 511 |
def global_features(scene: Scene) -> dict:
|
| 512 |
st = scene.stack
|
| 513 |
n_sig = sum(c.role == "signal" for c in scene.conductors)
|
|
|
|
| 518 |
|
| 519 |
|
| 520 |
def boundary_points(scene: Scene) -> tuple[dict, dict]:
|
| 521 |
+
def one(i):
|
|
|
|
| 522 |
g = region(scene, i)
|
| 523 |
+
return sample_boundary(g, STEP_UM), np.inf if scene.conductors[i].role == "ground" else 2 * g.area / g.length
|
| 524 |
+
|
| 525 |
+
out = _pmap(one, list(range(scene.n)), _nthreads())
|
| 526 |
+
return {i: p for i, (p, _) in enumerate(out)}, {i: w for i, (_, w) in enumerate(out)}
|
geomgnn/_tlsq/uge/graph.py
CHANGED
|
@@ -2,25 +2,29 @@
|
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
-
from itertools import combinations
|
| 6 |
-
|
| 7 |
import numpy as np
|
| 8 |
|
| 9 |
-
from .blocks import boundary_points,
|
| 10 |
from .proxies import Proxy
|
| 11 |
from .scene import Scene
|
| 12 |
|
| 13 |
|
| 14 |
def scene_graph(scene: Scene, proxy: Proxy | None = None) -> dict:
|
|
|
|
| 15 |
bpts, widths = boundary_points(scene)
|
| 16 |
-
nodes =
|
| 17 |
-
edges =
|
| 18 |
# shielding: share of each endpoint's total geometric coupling carried by this edge
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
tot[i] += f["_cps"]
|
| 22 |
tot[j] += f["_cps"]
|
| 23 |
-
for (i, j), f in edges.items():
|
| 24 |
si, sj = f["_cps"] / max(tot[i], 1e-12), f["_cps"] / max(tot[j], 1e-12)
|
| 25 |
f["share_mean"], f["share_absdiff"] = 0.5 * (si + sj), abs(si - sj)
|
| 26 |
g = {"names": scene.names(), "global": global_features(scene), "nodes": nodes, "edges": edges}
|
|
@@ -33,11 +37,22 @@ def scene_graph(scene: Scene, proxy: Proxy | None = None) -> dict:
|
|
| 33 |
g["global"].update({f"proxy_{k}": x for k, x in px["global"].items()})
|
| 34 |
if "matrix" in px:
|
| 35 |
g["proxy_matrix"] = px["matrix"]
|
| 36 |
-
for f in edges.values():
|
| 37 |
f.pop("_cps")
|
| 38 |
return g
|
| 39 |
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def pooled_vector(g: dict) -> dict:
|
| 42 |
"""Fixed-length universal vector for any number of conductors: global block, the ground node, sum/mean/max over
|
| 43 |
signal nodes, and sum/mean/max over signal-signal and signal-ground edges."""
|
|
|
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
|
| 7 |
+
from .blocks import EdgeTable, _cache, body_keys, boundary_points, edge_features_all, global_features, node_features_all
|
| 8 |
from .proxies import Proxy
|
| 9 |
from .scene import Scene
|
| 10 |
|
| 11 |
|
| 12 |
def scene_graph(scene: Scene, proxy: Proxy | None = None) -> dict:
|
| 13 |
+
keys = body_keys(scene) if _cache() else None
|
| 14 |
bpts, widths = boundary_points(scene)
|
| 15 |
+
nodes = node_features_all(scene, keys)
|
| 16 |
+
edges = edge_features_all(scene, bpts, widths, keys)
|
| 17 |
# shielding: share of each endpoint's total geometric coupling carried by this edge
|
| 18 |
+
table = isinstance(edges, EdgeTable)
|
| 19 |
+
if table:
|
| 20 |
+
edges = _shares_table(scene.n, edges)
|
| 21 |
+
if proxy is not None:
|
| 22 |
+
edges = {p: edges[p] for p in edges}
|
| 23 |
+
tot = None if table else np.zeros(scene.n)
|
| 24 |
+
for (i, j), f in (edges.items() if tot is not None else ()):
|
| 25 |
tot[i] += f["_cps"]
|
| 26 |
tot[j] += f["_cps"]
|
| 27 |
+
for (i, j), f in (edges.items() if tot is not None else ()):
|
| 28 |
si, sj = f["_cps"] / max(tot[i], 1e-12), f["_cps"] / max(tot[j], 1e-12)
|
| 29 |
f["share_mean"], f["share_absdiff"] = 0.5 * (si + sj), abs(si - sj)
|
| 30 |
g = {"names": scene.names(), "global": global_features(scene), "nodes": nodes, "edges": edges}
|
|
|
|
| 37 |
g["global"].update({f"proxy_{k}": x for k, x in px["global"].items()})
|
| 38 |
if "matrix" in px:
|
| 39 |
g["proxy_matrix"] = px["matrix"]
|
| 40 |
+
for f in (edges.values() if tot is not None else ()):
|
| 41 |
f.pop("_cps")
|
| 42 |
return g
|
| 43 |
|
| 44 |
|
| 45 |
+
def _shares_table(n: int, E: EdgeTable) -> EdgeTable:
|
| 46 |
+
"""The shares of scene_graph on an EdgeTable: the same additions in the same order (np.add.at is sequential)."""
|
| 47 |
+
I, J = np.triu_indices(n, 1)
|
| 48 |
+
cps = E.cols["_cps"]
|
| 49 |
+
tot = np.zeros(n)
|
| 50 |
+
np.add.at(tot, np.c_[I, J].ravel(), np.repeat(cps, 2))
|
| 51 |
+
si, sj = cps / np.maximum(tot[I], 1e-12), cps / np.maximum(tot[J], 1e-12)
|
| 52 |
+
return E.with_cols({"share_mean": 0.5 * (si + sj), "share_absdiff": np.abs(si - sj)}, drop=("_cps",),
|
| 53 |
+
npcols=("share_mean", "share_absdiff"))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
def pooled_vector(g: dict) -> dict:
|
| 57 |
"""Fixed-length universal vector for any number of conductors: global block, the ground node, sum/mean/max over
|
| 58 |
signal nodes, and sum/mean/max over signal-signal and signal-ground edges."""
|
geomgnn/_tlsq/uge/localtok.py
CHANGED
|
@@ -7,10 +7,10 @@ from __future__ import annotations
|
|
| 7 |
|
| 8 |
import numpy as np
|
| 9 |
import shapely
|
| 10 |
-
from scipy.spatial import cKDTree
|
| 11 |
|
| 12 |
from ..geometry import sample_boundary
|
| 13 |
-
from .
|
|
|
|
| 14 |
|
| 15 |
RADII_UM = (50.0, 150.0, 400.0)
|
| 16 |
KEYS = [f"lt_{k}{int(r)}" for r in RADII_UM for k in ("g", "o", "e")]
|
|
@@ -24,7 +24,8 @@ def node_tokens(scene) -> np.ndarray:
|
|
| 24 |
sig = [k for k, c in enumerate(conds) if c.role != "ground"]
|
| 25 |
tree = shapely.STRtree([conds[k].geom for k in sig])
|
| 26 |
out = np.full((n, len(KEYS)), np.nan)
|
| 27 |
-
|
|
|
|
| 28 |
g = conds[k].geom
|
| 29 |
vals = []
|
| 30 |
for R in RADII_UM:
|
|
@@ -36,6 +37,9 @@ def node_tokens(scene) -> np.ndarray:
|
|
| 36 |
om = shapely.intersection(shapely.union_all([conds[i].geom for i in near]), ring).area if near else 0.0
|
| 37 |
inchip = shapely.intersection(scene.chip, ring).area
|
| 38 |
vals += [gm / A, om / A, max(inchip - gm - om, 0.0) / A]
|
|
|
|
|
|
|
|
|
|
| 39 |
out[k] = vals
|
| 40 |
return out
|
| 41 |
|
|
@@ -51,30 +55,34 @@ def ground_tokens(scene) -> np.ndarray:
|
|
| 51 |
(fixed radius: independent of the ground window)."""
|
| 52 |
conds = scene.conductors
|
| 53 |
out = np.full((len(conds), len(LG_KEYS)), np.nan)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
g = c.geom
|
| 58 |
b = g.bounds
|
| 59 |
P = shapely.clip_by_rect(scene.pocket, b[0] - LG_R_UM, b[1] - LG_R_UM, b[2] + LG_R_UM, b[3] + LG_R_UM)
|
| 60 |
pj = sample_boundary(g, STEP_UM)
|
| 61 |
pg = sample_boundary(P, STEP_UM) if not P.is_empty else np.zeros((0, 2))
|
| 62 |
if len(pg):
|
| 63 |
-
pg = pg[
|
| 64 |
if not len(pg):
|
| 65 |
-
|
| 66 |
wj = 2 * g.area / g.length
|
| 67 |
hist = np.zeros(len(SEP_EDGES_UM) - 1)
|
| 68 |
mom = np.zeros(len(MOMENTS))
|
| 69 |
cps, dmin = 0.0, np.inf
|
| 70 |
for a_, b_ in ((pj, pg), (pg, pj)):
|
| 71 |
-
d =
|
| 72 |
dmin = min(dmin, d.min())
|
| 73 |
hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0]
|
| 74 |
dd = np.maximum(d, 0.05)
|
| 75 |
mom += 0.5 * np.array([np.sum(STEP_UM * dd ** (-p)) for p in MOMENTS])
|
| 76 |
cps += 0.5 * np.sum(STEP_UM * _kratio(dd / (dd + wj)))
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
return out
|
| 79 |
|
| 80 |
|
|
@@ -87,6 +95,8 @@ def add_from_tokens(row: dict, T: np.ndarray, Lg: np.ndarray, sig) -> dict:
|
|
| 87 |
"""Edges + KEYS (mean over the signal ends) + LG_KEYS (ground pairs: the fixed-radius tokens of the signal end; other
|
| 88 |
pairs: their own tokens, unchanged)."""
|
| 89 |
sig = np.asarray(sig)
|
|
|
|
|
|
|
| 90 |
edges = {}
|
| 91 |
for (i, j), f in row["edges"].items():
|
| 92 |
ends = [e for e in (i, j) if sig[e]]
|
|
@@ -97,3 +107,20 @@ def add_from_tokens(row: dict, T: np.ndarray, Lg: np.ndarray, sig) -> dict:
|
|
| 97 |
new.update({f"lg_{k}": float(f[k]) for k in TOK})
|
| 98 |
edges[(i, j)] = {**f, **new}
|
| 99 |
return {**row, "edges": edges}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
import numpy as np
|
| 9 |
import shapely
|
|
|
|
| 10 |
|
| 11 |
from ..geometry import sample_boundary
|
| 12 |
+
from ..embed.proxy import _nthreads
|
| 13 |
+
from .blocks import MOMENTS, SEP_EDGES_UM, STEP_UM, EdgeTable, _dist, _kratio, _pmap, _tree
|
| 14 |
|
| 15 |
RADII_UM = (50.0, 150.0, 400.0)
|
| 16 |
KEYS = [f"lt_{k}{int(r)}" for r in RADII_UM for k in ("g", "o", "e")]
|
|
|
|
| 24 |
sig = [k for k, c in enumerate(conds) if c.role != "ground"]
|
| 25 |
tree = shapely.STRtree([conds[k].geom for k in sig])
|
| 26 |
out = np.full((n, len(KEYS)), np.nan)
|
| 27 |
+
|
| 28 |
+
def one(k):
|
| 29 |
g = conds[k].geom
|
| 30 |
vals = []
|
| 31 |
for R in RADII_UM:
|
|
|
|
| 37 |
om = shapely.intersection(shapely.union_all([conds[i].geom for i in near]), ring).area if near else 0.0
|
| 38 |
inchip = shapely.intersection(scene.chip, ring).area
|
| 39 |
vals += [gm / A, om / A, max(inchip - gm - om, 0.0) / A]
|
| 40 |
+
return vals
|
| 41 |
+
|
| 42 |
+
for k, vals in zip(sig, _pmap(one, sig, _nthreads())): # threads: shapely releases the GIL
|
| 43 |
out[k] = vals
|
| 44 |
return out
|
| 45 |
|
|
|
|
| 55 |
(fixed radius: independent of the ground window)."""
|
| 56 |
conds = scene.conductors
|
| 57 |
out = np.full((len(conds), len(LG_KEYS)), np.nan)
|
| 58 |
+
|
| 59 |
+
def one(k):
|
| 60 |
+
g = conds[k].geom
|
|
|
|
| 61 |
b = g.bounds
|
| 62 |
P = shapely.clip_by_rect(scene.pocket, b[0] - LG_R_UM, b[1] - LG_R_UM, b[2] + LG_R_UM, b[3] + LG_R_UM)
|
| 63 |
pj = sample_boundary(g, STEP_UM)
|
| 64 |
pg = sample_boundary(P, STEP_UM) if not P.is_empty else np.zeros((0, 2))
|
| 65 |
if len(pg):
|
| 66 |
+
pg = pg[_dist(_tree(pj), pg) < LG_R_UM] # drops the clip-box edges (>= LG_R_UM away) and the far ground
|
| 67 |
if not len(pg):
|
| 68 |
+
return None
|
| 69 |
wj = 2 * g.area / g.length
|
| 70 |
hist = np.zeros(len(SEP_EDGES_UM) - 1)
|
| 71 |
mom = np.zeros(len(MOMENTS))
|
| 72 |
cps, dmin = 0.0, np.inf
|
| 73 |
for a_, b_ in ((pj, pg), (pg, pj)):
|
| 74 |
+
d = _dist(_tree(b_), a_)
|
| 75 |
dmin = min(dmin, d.min())
|
| 76 |
hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0]
|
| 77 |
dd = np.maximum(d, 0.05)
|
| 78 |
mom += 0.5 * np.array([np.sum(STEP_UM * dd ** (-p)) for p in MOMENTS])
|
| 79 |
cps += 0.5 * np.sum(STEP_UM * _kratio(dd / (dd + wj)))
|
| 80 |
+
return [np.log(max(dmin, 1e-9))] + list(np.log1p(hist)) + [np.log(max(v, 1e-9)) for v in mom] + [np.log(max(cps, 1e-9))]
|
| 81 |
+
|
| 82 |
+
sig = [k for k, c in enumerate(conds) if c.role != "ground"]
|
| 83 |
+
for k, v in zip(sig, _pmap(one, sig, _nthreads())): # threads: shapely and the k-d tree queries release the GIL
|
| 84 |
+
if v is not None:
|
| 85 |
+
out[k] = v
|
| 86 |
return out
|
| 87 |
|
| 88 |
|
|
|
|
| 95 |
"""Edges + KEYS (mean over the signal ends) + LG_KEYS (ground pairs: the fixed-radius tokens of the signal end; other
|
| 96 |
pairs: their own tokens, unchanged)."""
|
| 97 |
sig = np.asarray(sig)
|
| 98 |
+
if isinstance(row["edges"], EdgeTable):
|
| 99 |
+
return {**row, "edges": _add_table(row["edges"], T, Lg, sig)}
|
| 100 |
edges = {}
|
| 101 |
for (i, j), f in row["edges"].items():
|
| 102 |
ends = [e for e in (i, j) if sig[e]]
|
|
|
|
| 107 |
new.update({f"lg_{k}": float(f[k]) for k in TOK})
|
| 108 |
edges[(i, j)] = {**f, **new}
|
| 109 |
return {**row, "edges": edges}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _add_table(E: EdgeTable, T: np.ndarray, Lg: np.ndarray, sig: np.ndarray) -> EdgeTable:
|
| 113 |
+
"""add_from_tokens on an EdgeTable, per column with the same arithmetic: the mean over two signal ends is (a + b) / 2
|
| 114 |
+
(numpy's mean of two rows), over one end the row itself."""
|
| 115 |
+
I, J = np.triu_indices(E.n, 1)
|
| 116 |
+
sI, sJ = sig[I], sig[J]
|
| 117 |
+
both, oi, oj = sI & sJ, sI & ~sJ, ~sI & sJ
|
| 118 |
+
M = np.full((len(I), len(KEYS)), np.nan)
|
| 119 |
+
M[both] = (T[I[both]] + T[J[both]]) / 2
|
| 120 |
+
M[oi], M[oj] = T[I[oi]], T[J[oj]]
|
| 121 |
+
end = np.where(oi, I, J)
|
| 122 |
+
use = (oi | oj) & np.isfinite(Lg[end]).all(1)
|
| 123 |
+
new = {k: M[:, c] for c, k in enumerate(KEYS)}
|
| 124 |
+
for c, k in enumerate(TOK):
|
| 125 |
+
new[f"lg_{k}"] = np.where(use, Lg[end][:, c], E.cols[k])
|
| 126 |
+
return E.with_cols(new)
|
geomgnn/_tlsq/uge/nnk.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact nearest-sample distances (agents/embedspeed, CONSULT_HPC 3a): a 2-D k-d tree in numba whose squared distance is
|
| 2 |
+
the platform's cKDTree arithmetic (probed at first use against scipy: fma(dy, dy, dx * dx) on the arm64 wheels, plain
|
| 3 |
+
dx * dx + dy * dy elsewhere), queried in boundary order with a warm-start bound from the previous sample (triangle
|
| 4 |
+
inequality, inflated), so the minimum over samples, and its sqrt, are the same bits as cKDTree.query. If no variant
|
| 5 |
+
reproduces cKDTree on the probe, `available()` is False and callers keep cKDTree.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import threading
|
| 11 |
+
|
| 12 |
+
import numba as nb
|
| 13 |
+
import numpy as np
|
| 14 |
+
from llvmlite import ir
|
| 15 |
+
from numba import types
|
| 16 |
+
from numba.extending import intrinsic
|
| 17 |
+
|
| 18 |
+
LEAF = 32
|
| 19 |
+
WARM = 4 # boundary-order neighbours of the previous query's nearest sample evaluated first (an exact upper bound)
|
| 20 |
+
_STATE: dict = {}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@intrinsic
|
| 24 |
+
def _fma(typingctx, a, b, c):
|
| 25 |
+
sig = types.float64(types.float64, types.float64, types.float64)
|
| 26 |
+
|
| 27 |
+
def codegen(context, builder, signature, args):
|
| 28 |
+
d = ir.DoubleType()
|
| 29 |
+
fn = builder.module.declare_intrinsic("llvm.fma", [d], ir.FunctionType(d, [d, d, d]))
|
| 30 |
+
return builder.call(fn, args)
|
| 31 |
+
|
| 32 |
+
return sig, codegen
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@nb.njit(cache=True)
|
| 36 |
+
def _build(P, leaf):
|
| 37 |
+
"""Balanced k-d tree over P (m, 2): permutation, node boxes and ranges; node k has children 2k+1, 2k+2."""
|
| 38 |
+
m = P.shape[0]
|
| 39 |
+
nn = 1
|
| 40 |
+
while (m + leaf - 1) // leaf > (nn + 1) // 2:
|
| 41 |
+
nn = 2 * nn + 1
|
| 42 |
+
perm = np.arange(m)
|
| 43 |
+
lo = np.zeros(nn, np.int64)
|
| 44 |
+
hi = np.zeros(nn, np.int64)
|
| 45 |
+
box = np.empty((nn, 4))
|
| 46 |
+
lo[0], hi[0] = 0, m
|
| 47 |
+
for k in range(nn):
|
| 48 |
+
a, b = lo[k], hi[k]
|
| 49 |
+
if b > a:
|
| 50 |
+
x0 = x1 = P[perm[a], 0]
|
| 51 |
+
y0 = y1 = P[perm[a], 1]
|
| 52 |
+
for t in range(a + 1, b):
|
| 53 |
+
x, y = P[perm[t], 0], P[perm[t], 1]
|
| 54 |
+
x0, x1, y0, y1 = min(x0, x), max(x1, x), min(y0, y), max(y1, y)
|
| 55 |
+
box[k, 0], box[k, 1], box[k, 2], box[k, 3] = x0, y0, x1, y1
|
| 56 |
+
else:
|
| 57 |
+
box[k, 0] = box[k, 1] = np.inf
|
| 58 |
+
box[k, 2] = box[k, 3] = -np.inf
|
| 59 |
+
c = 2 * k + 1
|
| 60 |
+
if c < nn:
|
| 61 |
+
mid = (a + b) // 2
|
| 62 |
+
if b - a > 1:
|
| 63 |
+
d = 0 if box[k, 2] - box[k, 0] >= box[k, 3] - box[k, 1] else 1
|
| 64 |
+
sub = perm[a:b].copy()
|
| 65 |
+
order = np.argsort(P[sub, d], kind="mergesort")
|
| 66 |
+
perm[a:b] = sub[order]
|
| 67 |
+
lo[c], hi[c] = a, mid
|
| 68 |
+
lo[c + 1], hi[c + 1] = mid, b
|
| 69 |
+
return perm, lo, hi, box
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@nb.njit(cache=True, inline="always")
|
| 73 |
+
def _mind2(box, k, x, y):
|
| 74 |
+
dx = max(box[k, 0] - x, 0.0, x - box[k, 2])
|
| 75 |
+
dy = max(box[k, 1] - y, 0.0, y - box[k, 3])
|
| 76 |
+
return dx * dx + dy * dy
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@nb.njit(nogil=True, cache=True, inline="always")
|
| 80 |
+
def _sqd(x, y, P, j, use_fma):
|
| 81 |
+
dx, dy = x - P[j, 0], y - P[j, 1]
|
| 82 |
+
return _fma(dy, dy, dx * dx) if use_fma else dx * dx + dy * dy
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@nb.njit(nogil=True, cache=True)
|
| 86 |
+
def _kd(x, y, best, jb, P, perm, lo, hi, box, use_fma, stack):
|
| 87 |
+
"""Exact k-d search below the bound best (a squared distance already attained by sample jb, or inf)."""
|
| 88 |
+
nn = lo.shape[0]
|
| 89 |
+
stack[0] = 0
|
| 90 |
+
sp = 1
|
| 91 |
+
while sp:
|
| 92 |
+
sp -= 1
|
| 93 |
+
k = stack[sp]
|
| 94 |
+
if lo[k] >= hi[k] or _mind2(box, k, x, y) * (1.0 - 1e-12) > best:
|
| 95 |
+
continue
|
| 96 |
+
c = 2 * k + 1
|
| 97 |
+
if c >= nn:
|
| 98 |
+
for t in range(lo[k], hi[k]):
|
| 99 |
+
j = perm[t]
|
| 100 |
+
s = _sqd(x, y, P, j, use_fma)
|
| 101 |
+
if s < best:
|
| 102 |
+
best, jb = s, j
|
| 103 |
+
continue
|
| 104 |
+
d1, d2 = _mind2(box, c, x, y), _mind2(box, c + 1, x, y)
|
| 105 |
+
if d1 <= d2:
|
| 106 |
+
stack[sp] = c + 1
|
| 107 |
+
stack[sp + 1] = c
|
| 108 |
+
else:
|
| 109 |
+
stack[sp] = c
|
| 110 |
+
stack[sp + 1] = c + 1
|
| 111 |
+
sp += 2
|
| 112 |
+
return best, jb
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@nb.njit(nogil=True, cache=True)
|
| 116 |
+
def _scan(x, y, best, jb, P, et, ej, a, b, t0, t1, use_fma):
|
| 117 |
+
"""min over the edge-list entries a..b with t in [t0, t1] (t sorted)."""
|
| 118 |
+
lo_, hi_ = a, b
|
| 119 |
+
while lo_ < hi_:
|
| 120 |
+
mid = (lo_ + hi_) // 2
|
| 121 |
+
if et[mid] < t0:
|
| 122 |
+
lo_ = mid + 1
|
| 123 |
+
else:
|
| 124 |
+
hi_ = mid
|
| 125 |
+
for i in range(lo_, b):
|
| 126 |
+
if et[i] > t1:
|
| 127 |
+
break
|
| 128 |
+
s = _sqd(x, y, P, ej[i], use_fma)
|
| 129 |
+
if s < best:
|
| 130 |
+
best, jb = s, ej[i]
|
| 131 |
+
return best, jb
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@nb.njit(nogil=True, cache=True)
|
| 135 |
+
def _nearest_t(x, y, P, et, ej, a, b, tf, use_fma):
|
| 136 |
+
"""An attained upper bound: the better of the two list entries around t = tf."""
|
| 137 |
+
lo_, hi_ = a, b
|
| 138 |
+
while lo_ < hi_:
|
| 139 |
+
mid = (lo_ + hi_) // 2
|
| 140 |
+
if et[mid] < tf:
|
| 141 |
+
lo_ = mid + 1
|
| 142 |
+
else:
|
| 143 |
+
hi_ = mid
|
| 144 |
+
best, jb = np.inf, -1
|
| 145 |
+
for i in (lo_ - 1, lo_):
|
| 146 |
+
if a <= i < b:
|
| 147 |
+
s = _sqd(x, y, P, ej[i], use_fma)
|
| 148 |
+
if s < best:
|
| 149 |
+
best, jb = s, ej[i]
|
| 150 |
+
return best, jb
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@nb.njit(nogil=True, cache=True)
|
| 154 |
+
def _query(X, P, perm, lo, hi, box, use_fma, warm, H, hv, hx, hy, ux, uy, L, nx, ny, eoff, et, ej, eps, delta):
|
| 155 |
+
"""Distances from every row of X to the nearest sample of P. Far field (H > 0): x outside the hull of P projects to a
|
| 156 |
+
hull edge or vertex f at distance dH; every sample s satisfies |x - s|^2 >= dH^2 + |f - s|^2 (obtuse angle at f), so once
|
| 157 |
+
a sample o attains s_o, only samples within rho = sqrt(s_o - dH^2 + slack) of f can be nearer; those lie in the edge's
|
| 158 |
+
list (samples within delta of it). Otherwise, and whenever rho > delta, the k-d search (warm-started) decides."""
|
| 159 |
+
m = X.shape[0]
|
| 160 |
+
mp = P.shape[0]
|
| 161 |
+
out = np.empty(m)
|
| 162 |
+
stack = np.empty(128, np.int64)
|
| 163 |
+
jp = -1
|
| 164 |
+
e = 0
|
| 165 |
+
for q in range(m):
|
| 166 |
+
x, y = X[q, 0], X[q, 1]
|
| 167 |
+
best = np.inf
|
| 168 |
+
jb = -1
|
| 169 |
+
done = False
|
| 170 |
+
if H >= 3:
|
| 171 |
+
reg = -1
|
| 172 |
+
vtx = -1
|
| 173 |
+
for _ in range(H + 2):
|
| 174 |
+
t = (x - hx[e]) * ux[e] + (y - hy[e]) * uy[e]
|
| 175 |
+
if t < 0.0:
|
| 176 |
+
ep = e - 1 if e > 0 else H - 1
|
| 177 |
+
if (x - hx[ep]) * ux[ep] + (y - hy[ep]) * uy[ep] > L[ep]:
|
| 178 |
+
vtx = e
|
| 179 |
+
break
|
| 180 |
+
e = ep
|
| 181 |
+
continue
|
| 182 |
+
if t > L[e]:
|
| 183 |
+
en = e + 1 if e + 1 < H else 0
|
| 184 |
+
if (x - hx[en]) * ux[en] + (y - hy[en]) * uy[en] < 0.0:
|
| 185 |
+
vtx = en
|
| 186 |
+
break
|
| 187 |
+
e = en
|
| 188 |
+
continue
|
| 189 |
+
if (x - hx[e]) * nx[e] + (y - hy[e]) * ny[e] > 0.0:
|
| 190 |
+
reg = e
|
| 191 |
+
break
|
| 192 |
+
if vtx >= 0:
|
| 193 |
+
fx, fy = hx[vtx], hy[vtx]
|
| 194 |
+
dh2 = (x - fx) * (x - fx) + (y - fy) * (y - fy)
|
| 195 |
+
best = _sqd(x, y, P, hv[vtx], use_fma)
|
| 196 |
+
jb = hv[vtx]
|
| 197 |
+
rho2 = best - dh2 + 1e-9 * best + 1e-4 + 4.0 * eps * (np.sqrt(best) + 1.0)
|
| 198 |
+
if rho2 <= delta * delta:
|
| 199 |
+
r = np.sqrt(max(rho2, 0.0))
|
| 200 |
+
ep = vtx - 1 if vtx > 0 else H - 1
|
| 201 |
+
best, jb = _scan(x, y, best, jb, P, et, ej, eoff[vtx], eoff[vtx + 1], -r, r, use_fma)
|
| 202 |
+
best, jb = _scan(x, y, best, jb, P, et, ej, eoff[ep], eoff[ep + 1], L[ep] - r, L[ep] + r, use_fma)
|
| 203 |
+
done = True
|
| 204 |
+
elif reg >= 0:
|
| 205 |
+
tf = (x - hx[reg]) * ux[reg] + (y - hy[reg]) * uy[reg]
|
| 206 |
+
pp = (x - hx[reg]) * nx[reg] + (y - hy[reg]) * ny[reg]
|
| 207 |
+
dh2 = pp * pp
|
| 208 |
+
best, jb = _nearest_t(x, y, P, et, ej, eoff[reg], eoff[reg + 1], tf, use_fma)
|
| 209 |
+
if jb >= 0:
|
| 210 |
+
rho2 = best - dh2 + 1e-9 * best + 1e-4 + 4.0 * eps * (np.sqrt(best) + 1.0)
|
| 211 |
+
if rho2 <= delta * delta:
|
| 212 |
+
r = np.sqrt(max(rho2, 0.0))
|
| 213 |
+
best, jb = _scan(x, y, best, jb, P, et, ej, eoff[reg], eoff[reg + 1], tf - r, tf + r, use_fma)
|
| 214 |
+
done = True
|
| 215 |
+
if not done:
|
| 216 |
+
if jp >= 0:
|
| 217 |
+
for j in range(max(0, jp - warm), min(mp, jp + warm + 1)):
|
| 218 |
+
s = _sqd(x, y, P, j, use_fma)
|
| 219 |
+
if s < best:
|
| 220 |
+
best, jb = s, j
|
| 221 |
+
best, jb = _kd(x, y, best, jb, P, perm, lo, hi, box, use_fma, stack)
|
| 222 |
+
out[q] = np.sqrt(best)
|
| 223 |
+
jp = jb
|
| 224 |
+
return out
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
@nb.njit(cache=True)
|
| 228 |
+
def _hull_lists(P, hv, delta):
|
| 229 |
+
H = hv.shape[0]
|
| 230 |
+
hx, hy = np.empty(H), np.empty(H)
|
| 231 |
+
ux, uy, L, nx, ny = np.empty(H), np.empty(H), np.empty(H), np.empty(H), np.empty(H)
|
| 232 |
+
for i in range(H):
|
| 233 |
+
hx[i], hy[i] = P[hv[i], 0], P[hv[i], 1]
|
| 234 |
+
for i in range(H):
|
| 235 |
+
k = i + 1 if i + 1 < H else 0
|
| 236 |
+
dx, dy = hx[k] - hx[i], hy[k] - hy[i]
|
| 237 |
+
L[i] = np.sqrt(dx * dx + dy * dy)
|
| 238 |
+
ux[i], uy[i] = dx / L[i], dy / L[i]
|
| 239 |
+
nx[i], ny[i] = uy[i], -ux[i] # outward for a counter-clockwise hull
|
| 240 |
+
m = P.shape[0]
|
| 241 |
+
eps = 0.0
|
| 242 |
+
cnt = np.zeros(H + 1, np.int64)
|
| 243 |
+
db = delta + 0.01
|
| 244 |
+
for i in range(H):
|
| 245 |
+
for j in range(m):
|
| 246 |
+
ax, ay = P[j, 0] - hx[i], P[j, 1] - hy[i]
|
| 247 |
+
pp = ax * nx[i] + ay * ny[i]
|
| 248 |
+
if pp > eps:
|
| 249 |
+
eps = pp
|
| 250 |
+
t = ax * ux[i] + ay * uy[i]
|
| 251 |
+
if -db <= t <= L[i] + db and abs(pp) <= db:
|
| 252 |
+
cnt[i + 1] += 1
|
| 253 |
+
eoff = np.cumsum(cnt)
|
| 254 |
+
et, ej = np.empty(eoff[H]), np.empty(eoff[H], np.int64)
|
| 255 |
+
for i in range(H):
|
| 256 |
+
k = eoff[i]
|
| 257 |
+
for j in range(m):
|
| 258 |
+
ax, ay = P[j, 0] - hx[i], P[j, 1] - hy[i]
|
| 259 |
+
pp = ax * nx[i] + ay * ny[i]
|
| 260 |
+
t = ax * ux[i] + ay * uy[i]
|
| 261 |
+
if -db <= t <= L[i] + db and abs(pp) <= db:
|
| 262 |
+
et[k], ej[k] = t, j
|
| 263 |
+
k += 1
|
| 264 |
+
o = np.argsort(et[eoff[i]:eoff[i + 1]], kind="mergesort")
|
| 265 |
+
et[eoff[i]:eoff[i + 1]] = et[eoff[i]:eoff[i + 1]][o]
|
| 266 |
+
ej[eoff[i]:eoff[i + 1]] = ej[eoff[i]:eoff[i + 1]][o]
|
| 267 |
+
return hx, hy, ux, uy, L, nx, ny, eoff, et, ej, eps
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
DELTA = 1.0
|
| 271 |
+
HULL_MAX = 200_000 # targets with more samples (the ground) use the k-d search only
|
| 272 |
+
_EMPTY = (np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0),
|
| 273 |
+
np.zeros(1, np.int64), np.zeros(0), np.zeros(0, np.int64), 0.0)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class Tree:
|
| 277 |
+
"""Drop-in for cKDTree(P).query(X)[0] (distances only)."""
|
| 278 |
+
|
| 279 |
+
def __init__(self, P: np.ndarray, hull: bool | None = None):
|
| 280 |
+
self.P = np.ascontiguousarray(P, dtype=np.float64)
|
| 281 |
+
self.perm, self.lo, self.hi, self.box = _build(self.P, LEAF)
|
| 282 |
+
self.hv, self.H = np.zeros(0, np.int64), 0
|
| 283 |
+
self.hl = _EMPTY
|
| 284 |
+
if (HULL["on"] if hull is None else hull) and 3 <= len(self.P) <= HULL_MAX:
|
| 285 |
+
try:
|
| 286 |
+
from scipy.spatial import ConvexHull
|
| 287 |
+
hv = ConvexHull(self.P).vertices.astype(np.int64)
|
| 288 |
+
except Exception: # noqa: BLE001 (degenerate: collinear samples)
|
| 289 |
+
hv = None
|
| 290 |
+
if hv is not None and len(hv) >= 3:
|
| 291 |
+
self.hv, self.H = hv, len(hv)
|
| 292 |
+
self.hl = _hull_lists(self.P, hv, DELTA)
|
| 293 |
+
|
| 294 |
+
def dist(self, X: np.ndarray) -> np.ndarray:
|
| 295 |
+
return _query(np.ascontiguousarray(X, dtype=np.float64), self.P, self.perm, self.lo, self.hi, self.box, _STATE["fma"],
|
| 296 |
+
WARM, self.H, self.hv, *self.hl, DELTA)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
HULL: dict = {"on": os.environ.get("TLSQ_NN_HULL", "1") == "1"} # far-field hull path (exact; off: k-d search only)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def probe(n_targets: int = 40, seed: int = 0) -> dict:
|
| 303 |
+
"""Which arithmetic reproduces this platform's cKDTree bit for bit (random and boundary-like targets, near and far)."""
|
| 304 |
+
from scipy.spatial import cKDTree
|
| 305 |
+
|
| 306 |
+
rng = np.random.default_rng(seed)
|
| 307 |
+
res = {}
|
| 308 |
+
for name in ("fma", "plain"):
|
| 309 |
+
bad = tot = 0
|
| 310 |
+
for t in range(n_targets):
|
| 311 |
+
m = int(rng.integers(5, 3000))
|
| 312 |
+
if t % 2:
|
| 313 |
+
th = np.sort(rng.uniform(0, 2 * np.pi, m))
|
| 314 |
+
P = np.c_[np.cos(th) * rng.uniform(10, 300), np.sin(th) * rng.uniform(10, 300)] + rng.uniform(-5000, 5000, 2)
|
| 315 |
+
else:
|
| 316 |
+
P = rng.uniform(-300, 300, (m, 2)) + rng.uniform(-5000, 5000, 2)
|
| 317 |
+
X = np.cumsum(rng.normal(0, rng.choice([0.25, 30.0]), (2000, 2)), 0) + P.mean(0) + rng.uniform(-3000, 3000, 2)
|
| 318 |
+
tr = Tree(P, hull=False)
|
| 319 |
+
d = _query(np.ascontiguousarray(X), tr.P, tr.perm, tr.lo, tr.hi, tr.box, name == "fma", WARM, 0, tr.hv, *tr.hl, DELTA)
|
| 320 |
+
ref = cKDTree(P).query(X)[0]
|
| 321 |
+
bad += int((d != ref).sum())
|
| 322 |
+
tot += len(X)
|
| 323 |
+
res[name] = dict(mismatches=bad, queries=tot)
|
| 324 |
+
return res
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
_LOCK = threading.Lock()
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def available() -> bool:
|
| 331 |
+
with _LOCK:
|
| 332 |
+
return _available()
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _available() -> bool:
|
| 336 |
+
if "ok" not in _STATE:
|
| 337 |
+
r = probe()
|
| 338 |
+
ok = [k for k in ("fma", "plain") if r[k]["mismatches"] == 0]
|
| 339 |
+
_STATE.update(probe=r, ok=bool(ok), arith=ok[0] if ok else None)
|
| 340 |
+
_STATE["fma"] = bool(ok) and ok[0] == "fma"
|
| 341 |
+
return _STATE["ok"]
|
geomgnn/api.py
CHANGED
|
@@ -26,6 +26,12 @@ from . import infer as I
|
|
| 26 |
from ._tlsq.embed import fastprior, proxy
|
| 27 |
from ._tlsq.uge.graph import scene_graph
|
| 28 |
from ._tlsq.uge.scene import DEFAULT_STACK, Conductor, Scene
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
lt = I.lt
|
| 31 |
EPS_TRAIN, T_TRAIN_UM = 11.45, 350.0
|
|
@@ -139,7 +145,10 @@ def set_prior_stack(pr: dict, threads: int = 2) -> None:
|
|
| 139 |
ctx = priorv2.installed(**V2_KWARGS[v2[0]])
|
| 140 |
ctx.__enter__()
|
| 141 |
_STATE["v2ctx"] = ctx
|
| 142 |
-
_STATE.update(patches=patches, mode=mode, stack=key)
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
|
| 145 |
def _sha(p) -> str:
|
|
@@ -205,6 +214,7 @@ def load(name: str, reg, model_dir=None, threads: int | None = None) -> I.Predic
|
|
| 205 |
raise RuntimeError(f"{name}: {sf.name} SHA256 differs from the registry (learned prior {lpr['checkpoint']['sha256'][:12]})")
|
| 206 |
from . import learned_prior
|
| 207 |
model, prep, _ = learned_prior.load(sf)
|
|
|
|
| 208 |
P.surrogate = (model, prep)
|
| 209 |
else:
|
| 210 |
if not pr or abs(float(pr["alpha"]) - float(phys.get("alpha"))) > 0 or (pr["method"] == "local_gap") != (phys.get("prior_method") == "local_gap") \
|
|
@@ -284,7 +294,9 @@ def predict_scene(P: I.Predictor, sc: Scene, alpha=None, local_gap=None) -> dict
|
|
| 284 |
priorv2.clear() # its per-window traces would otherwise grow for the life of the server
|
| 285 |
start = time.perf_counter()
|
| 286 |
t1 = time.perf_counter()
|
| 287 |
-
|
|
|
|
|
|
|
| 288 |
t2 = time.perf_counter()
|
| 289 |
priors = {}
|
| 290 |
if getattr(P, "surrogate", None) is not None:
|
|
@@ -295,7 +307,12 @@ def predict_scene(P: I.Predictor, sc: Scene, alpha=None, local_gap=None) -> dict
|
|
| 295 |
try:
|
| 296 |
if alpha is not None:
|
| 297 |
fastprior.ALPHA_GAP_SHARE = alpha
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
if local_gap:
|
| 300 |
from ._tlsq.embed.fastprior_loc import micro_mom_loc
|
| 301 |
with proxy.substrate("slab_open", sc.stack["substrate_thickness_um"]), _quiet_mixed_cast():
|
|
@@ -308,10 +325,15 @@ def predict_scene(P: I.Predictor, sc: Scene, alpha=None, local_gap=None) -> dict
|
|
| 308 |
finally:
|
| 309 |
fastprior.ALPHA_GAP_SHARE = old
|
| 310 |
t3 = time.perf_counter()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
C = P.from_features(row, priors)
|
| 312 |
t4 = time.perf_counter()
|
| 313 |
return dict(C=C, names=row["names"], timing=dict(scene=t1 - start, geometry=t2 - t1, prior=t3 - t2, network_and_pack=t4 - t3,
|
| 314 |
-
total=t4 - start))
|
| 315 |
|
| 316 |
|
| 317 |
@contextlib.contextmanager
|
|
|
|
| 26 |
from ._tlsq.embed import fastprior, proxy
|
| 27 |
from ._tlsq.uge.graph import scene_graph
|
| 28 |
from ._tlsq.uge.scene import DEFAULT_STACK, Conductor, Scene
|
| 29 |
+
from ._tlsq.uge import blocks as _blocks
|
| 30 |
+
|
| 31 |
+
# Inference default: the numerically exact embedding (translated copies shared; last-bit differences only, agents/embedspeed);
|
| 32 |
+
# TLSQ_EMBED_MODE=bitwise restores the bit-identical training features.
|
| 33 |
+
_blocks.EMBED_MODE["mode"] = os.environ.get("TLSQ_EMBED_MODE", "numex")
|
| 34 |
+
_blocks.EDGE_TABLE["on"] = os.environ.get("TLSQ_EDGE_TABLE", "1") == "1" # array edge table (bitwise values; dicts on request)
|
| 35 |
|
| 36 |
lt = I.lt
|
| 37 |
EPS_TRAIN, T_TRAIN_UM = 11.45, 350.0
|
|
|
|
| 145 |
ctx = priorv2.installed(**V2_KWARGS[v2[0]])
|
| 146 |
ctx.__enter__()
|
| 147 |
_STATE["v2ctx"] = ctx
|
| 148 |
+
_STATE.update(patches=patches, mode=mode, stack=key, pr=dict(pr))
|
| 149 |
+
if mode:
|
| 150 |
+
from . import winpool
|
| 151 |
+
winpool.install() # macOS: the prior's windows on spawned workers (numerically exact; TLSQ_WINDOW_PROCS=0 turns it off)
|
| 152 |
|
| 153 |
|
| 154 |
def _sha(p) -> str:
|
|
|
|
| 214 |
raise RuntimeError(f"{name}: {sf.name} SHA256 differs from the registry (learned prior {lpr['checkpoint']['sha256'][:12]})")
|
| 215 |
from . import learned_prior
|
| 216 |
model, prep, _ = learned_prior.load(sf)
|
| 217 |
+
prep.floor_ff = lpr.get("floor_ff")
|
| 218 |
P.surrogate = (model, prep)
|
| 219 |
else:
|
| 220 |
if not pr or abs(float(pr["alpha"]) - float(phys.get("alpha"))) > 0 or (pr["method"] == "local_gap") != (phys.get("prior_method") == "local_gap") \
|
|
|
|
| 294 |
priorv2.clear() # its per-window traces would otherwise grow for the life of the server
|
| 295 |
start = time.perf_counter()
|
| 296 |
t1 = time.perf_counter()
|
| 297 |
+
from . import overlap as OV
|
| 298 |
+
fut = OV.start(sc, P.threads) if (getattr(P, "surrogate", None) is None and not P.direct and local_gap and OV.enabled(sc, P.threads)) else None
|
| 299 |
+
row = None if fut else lt.add_tokens(sc, scene_graph(sc)) # overlap: the embedding runs in the worker during the priors
|
| 300 |
t2 = time.perf_counter()
|
| 301 |
priors = {}
|
| 302 |
if getattr(P, "surrogate", None) is not None:
|
|
|
|
| 307 |
try:
|
| 308 |
if alpha is not None:
|
| 309 |
fastprior.ALPHA_GAP_SHARE = alpha
|
| 310 |
+
from . import levelpar
|
| 311 |
+
lvls = [.75, 1.5] if P.fast else [1.5, 3.]
|
| 312 |
+
if local_gap and levelpar.enabled(sc, lvls, P.threads): # the levels concurrently (spawned workers, same stack and statements)
|
| 313 |
+
priors.update(levelpar.solve(sc, lvls, P.threads, alpha)[0])
|
| 314 |
+
lvls = []
|
| 315 |
+
for p in lvls:
|
| 316 |
if local_gap:
|
| 317 |
from ._tlsq.embed.fastprior_loc import micro_mom_loc
|
| 318 |
with proxy.substrate("slab_open", sc.stack["substrate_thickness_um"]), _quiet_mixed_cast():
|
|
|
|
| 325 |
finally:
|
| 326 |
fastprior.ALPHA_GAP_SHARE = old
|
| 327 |
t3 = time.perf_counter()
|
| 328 |
+
extra = {}
|
| 329 |
+
if fut is not None:
|
| 330 |
+
row, embed_s = fut.result()
|
| 331 |
+
extra = dict(overlap=True, geometry_worker=embed_s, geometry_wait_after_prior=time.perf_counter() - t3)
|
| 332 |
+
t3 = time.perf_counter()
|
| 333 |
C = P.from_features(row, priors)
|
| 334 |
t4 = time.perf_counter()
|
| 335 |
return dict(C=C, names=row["names"], timing=dict(scene=t1 - start, geometry=t2 - t1, prior=t3 - t2, network_and_pack=t4 - t3,
|
| 336 |
+
total=t4 - start, **extra))
|
| 337 |
|
| 338 |
|
| 339 |
@contextlib.contextmanager
|
geomgnn/app_flagship.py
CHANGED
|
@@ -71,20 +71,29 @@ def tier_md(reg, k) -> str:
|
|
| 71 |
"These networks are trained on all 45,771 on-stack layouts, so they have no held-out score of their own: the paper rows are "
|
| 72 |
"the same recipe trained on the TRAIN split; B5 is one fresh check (one generated family, 3-4 conductors). Layout-mean median "
|
| 73 |
"relative error over mutual entries against Q3D, 0.1 fF floor."]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
return "\n".join(lines)
|
| 75 |
|
| 76 |
|
| 77 |
def _predict(lay, model, substrate, thickness_um):
|
|
|
|
| 78 |
reg = load_registry()
|
| 79 |
name = resolve(reg, model)
|
| 80 |
cap = int(reg["flagship_hub"]["max_conductors"])
|
| 81 |
if lay.n_conductors > cap:
|
| 82 |
raise LayoutError(f"{lay.n_conductors} conductors: this server is capped at {cap}; run the package locally for larger layouts")
|
| 83 |
fn = lambda: FS.predict(lay, name, reg, substrate=substrate, thickness_um=thickness_um) # noqa: E731
|
| 84 |
-
if lay.n_conductors
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
|
| 90 |
def report_md(res: dict, reg) -> str:
|
|
@@ -101,8 +110,8 @@ def report_md(res: dict, reg) -> str:
|
|
| 101 |
"", tier_md(reg, res["tier"])]
|
| 102 |
if res["warnings"]:
|
| 103 |
lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]]
|
| 104 |
-
lines += ["", f"Self capacitance: {res['self_capacitance']}.", "Planar single-layer layouts only (zero-thickness metal).
|
| 105 |
-
|
| 106 |
return "\n".join(lines)
|
| 107 |
|
| 108 |
|
|
|
|
| 71 |
"These networks are trained on all 45,771 on-stack layouts, so they have no held-out score of their own: the paper rows are "
|
| 72 |
"the same recipe trained on the TRAIN split; B5 is one fresh check (one generated family, 3-4 conductors). Layout-mean median "
|
| 73 |
"relative error over mutual entries against Q3D, 0.1 fF floor."]
|
| 74 |
+
e = t.get("embedding") or {}
|
| 75 |
+
if e.get("far_k"):
|
| 76 |
+
lines += ["", f"Speed: the pair vectors use far-sample decimation (blocks of {int(e['far_k'])} boundary samples farther than "
|
| 77 |
+
f"{float(e.get('d_far_um', 100.0)):g} µm from the other conductor are represented by one sample); it ties the exact embedding "
|
| 78 |
+
"on the paper's 4,608 validation layouts and the 1-, 5- and 9-qubit lattices. The paper Space keeps the exact embedding."]
|
| 79 |
return "\n".join(lines)
|
| 80 |
|
| 81 |
|
| 82 |
def _predict(lay, model, substrate, thickness_um):
|
| 83 |
+
from . import respcache
|
| 84 |
reg = load_registry()
|
| 85 |
name = resolve(reg, model)
|
| 86 |
cap = int(reg["flagship_hub"]["max_conductors"])
|
| 87 |
if lay.n_conductors > cap:
|
| 88 |
raise LayoutError(f"{lay.n_conductors} conductors: this server is capped at {cap}; run the package locally for larger layouts")
|
| 89 |
fn = lambda: FS.predict(lay, name, reg, substrate=substrate, thickness_um=thickness_um) # noqa: E731
|
| 90 |
+
if lay.n_conductors > 8:
|
| 91 |
+
fn0 = fn
|
| 92 |
+
|
| 93 |
+
def fn():
|
| 94 |
+
with HEAVY:
|
| 95 |
+
return fn0()
|
| 96 |
+
return respcache.cached(lay, ("flagship", name, str(substrate), float(thickness_um), reg["version"]), fn)
|
| 97 |
|
| 98 |
|
| 99 |
def report_md(res: dict, reg) -> str:
|
|
|
|
| 110 |
"", tier_md(reg, res["tier"])]
|
| 111 |
if res["warnings"]:
|
| 112 |
lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]]
|
| 113 |
+
lines += ["", f"Self capacitance: {res['self_capacitance']}.", "Planar single-layer layouts only (zero-thickness metal). Uploads are held in memory "
|
| 114 |
+
"only while the Space is running, to speed up repeat requests; nothing is written to permanent storage."]
|
| 115 |
return "\n".join(lines)
|
| 116 |
|
| 117 |
|
geomgnn/app_paper.py
CHANGED
|
@@ -56,12 +56,16 @@ def _predict(lay, arm, substrate, thickness_um, self_from_rows=True, trust_rule=
|
|
| 56 |
if lay.n_conductors > cap(reg, a):
|
| 57 |
raise LayoutError(f"{lay.n_conductors} conductors: the arm '{name}' is capped at {cap(reg, a)} on this server; run the package "
|
| 58 |
"locally for larger layouts")
|
|
|
|
| 59 |
fn = lambda: PA.predict(lay, name, reg, substrate=substrate, thickness_um=thickness_um, self_from_rows=self_from_rows, # noqa: E731
|
| 60 |
trust_rule=trust_rule)
|
| 61 |
-
if lay.n_conductors
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
def pct(e) -> str:
|
|
@@ -118,8 +122,8 @@ def report_md(res: dict, reg) -> str:
|
|
| 118 |
"", arm_md(reg, res["arm"])]
|
| 119 |
if res["warnings"]:
|
| 120 |
lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]]
|
| 121 |
-
lines += ["", f"Self capacitance: {res['self_capacitance']}.", "Planar single-layer layouts only (zero-thickness metal).
|
| 122 |
-
|
| 123 |
return "\n".join(lines)
|
| 124 |
|
| 125 |
|
|
|
|
| 56 |
if lay.n_conductors > cap(reg, a):
|
| 57 |
raise LayoutError(f"{lay.n_conductors} conductors: the arm '{name}' is capped at {cap(reg, a)} on this server; run the package "
|
| 58 |
"locally for larger layouts")
|
| 59 |
+
from . import respcache
|
| 60 |
fn = lambda: PA.predict(lay, name, reg, substrate=substrate, thickness_um=thickness_um, self_from_rows=self_from_rows, # noqa: E731
|
| 61 |
trust_rule=trust_rule)
|
| 62 |
+
if lay.n_conductors > 8:
|
| 63 |
+
fn0 = fn
|
| 64 |
+
|
| 65 |
+
def fn():
|
| 66 |
+
with HEAVY:
|
| 67 |
+
return fn0()
|
| 68 |
+
return respcache.cached(lay, ("paper", name, str(substrate), float(thickness_um), bool(self_from_rows), trust_rule, reg["version"]), fn)
|
| 69 |
|
| 70 |
|
| 71 |
def pct(e) -> str:
|
|
|
|
| 122 |
"", arm_md(reg, res["arm"])]
|
| 123 |
if res["warnings"]:
|
| 124 |
lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]]
|
| 125 |
+
lines += ["", f"Self capacitance: {res['self_capacitance']}.", "Planar single-layer layouts only (zero-thickness metal). Uploads are held in memory "
|
| 126 |
+
"only while the Space is running, to speed up repeat requests; nothing is written to permanent storage."]
|
| 127 |
return "\n".join(lines)
|
| 128 |
|
| 129 |
|
geomgnn/infer.py
CHANGED
|
@@ -11,6 +11,7 @@ W=Path(__file__).resolve().parent
|
|
| 11 |
from .pilot_p2 import build_model
|
| 12 |
from ._tlsq.uge.scene import scene_from_gds,tlsq_namer
|
| 13 |
from ._tlsq.uge.graph import scene_graph
|
|
|
|
| 14 |
from ._tlsq.uge.proxies import CapacitanceMoM
|
| 15 |
from ._tlsq.uge import localtok as lt
|
| 16 |
|
|
@@ -28,7 +29,7 @@ class Predictor:
|
|
| 28 |
for ck,model in self.models:
|
| 29 |
schema=ck.get('schema',ck);nk=schema['nodekeys'];ek=schema['edgekeys'];gk=schema.get('globkeys',['log_chip_area','log_pocket_area','log_substrate_t','eps_eff'])
|
| 30 |
X=np.array([[(float(not np.isfinite(nd['log_min_halfwidth'])) if k=='missing_log_min_halfwidth' else nd[k]) for k in nk] for nd in row['nodes']],np.float32)[None]
|
| 31 |
-
E=
|
| 32 |
kinds=E[0,:,ek.index('is_ground_pair')].astype(int)
|
| 33 |
if self.arm in ['pair_mlp','mesh','lofo_pair']:X=X[:,:,[nk.index('role_ground')]];G=np.zeros((1,1),np.float32)
|
| 34 |
if self.direct:base=np.array([[ck['direct_intercepts'][str(k)] for k in kinds]],np.float32)
|
|
|
|
| 11 |
from .pilot_p2 import build_model
|
| 12 |
from ._tlsq.uge.scene import scene_from_gds,tlsq_namer
|
| 13 |
from ._tlsq.uge.graph import scene_graph
|
| 14 |
+
from ._tlsq.uge.blocks import edge_matrix
|
| 15 |
from ._tlsq.uge.proxies import CapacitanceMoM
|
| 16 |
from ._tlsq.uge import localtok as lt
|
| 17 |
|
|
|
|
| 29 |
for ck,model in self.models:
|
| 30 |
schema=ck.get('schema',ck);nk=schema['nodekeys'];ek=schema['edgekeys'];gk=schema.get('globkeys',['log_chip_area','log_pocket_area','log_substrate_t','eps_eff'])
|
| 31 |
X=np.array([[(float(not np.isfinite(nd['log_min_halfwidth'])) if k=='missing_log_min_halfwidth' else nd[k]) for k in nk] for nd in row['nodes']],np.float32)[None]
|
| 32 |
+
E=edge_matrix(row['edges'],ek,n)[None];G=np.array([[row['global'][k] for k in gk]],np.float32)
|
| 33 |
kinds=E[0,:,ek.index('is_ground_pair')].astype(int)
|
| 34 |
if self.arm in ['pair_mlp','mesh','lofo_pair']:X=X[:,:,[nk.index('role_ground')]];G=np.zeros((1,1),np.float32)
|
| 35 |
if self.direct:base=np.array([[ck['direct_intercepts'][str(k)] for k in kinds]],np.float32)
|
geomgnn/learned_prior.py
CHANGED
|
@@ -11,6 +11,7 @@ from __future__ import annotations
|
|
| 11 |
import numpy as np
|
| 12 |
|
| 13 |
from . import lp_surrogate as S
|
|
|
|
| 14 |
|
| 15 |
PPG = (1.5, 3.0)
|
| 16 |
|
|
@@ -27,7 +28,7 @@ def pack(row: dict) -> dict:
|
|
| 27 |
nk = S.SCHEMA["nodekeys"]
|
| 28 |
X = np.array([[(float(not np.isfinite(nd["log_min_halfwidth"])) if k == "missing_log_min_halfwidth" else nd[k]) for k in nk]
|
| 29 |
for nd in row["nodes"]], np.float32)
|
| 30 |
-
E =
|
| 31 |
Gv = np.array([row["global"][k] for k in S.SCHEMA["globkeys"]], np.float32)
|
| 32 |
return dict(X=X, E=E, G=Gv, names=row["names"])
|
| 33 |
|
|
@@ -41,6 +42,8 @@ def priors(model, prep, row: dict) -> dict:
|
|
| 41 |
out = {}
|
| 42 |
for k, p in enumerate(PPG):
|
| 43 |
M = np.zeros((n, n))
|
| 44 |
-
|
|
|
|
|
|
|
| 45 |
out[p] = M + M.T
|
| 46 |
return out
|
|
|
|
| 11 |
import numpy as np
|
| 12 |
|
| 13 |
from . import lp_surrogate as S
|
| 14 |
+
from ._tlsq.uge.blocks import edge_matrix
|
| 15 |
|
| 16 |
PPG = (1.5, 3.0)
|
| 17 |
|
|
|
|
| 28 |
nk = S.SCHEMA["nodekeys"]
|
| 29 |
X = np.array([[(float(not np.isfinite(nd["log_min_halfwidth"])) if k == "missing_log_min_halfwidth" else nd[k]) for k in nk]
|
| 30 |
for nd in row["nodes"]], np.float32)
|
| 31 |
+
E = edge_matrix(row["edges"], S.SCHEMA["edgekeys"], n)
|
| 32 |
Gv = np.array([row["global"][k] for k in S.SCHEMA["globkeys"]], np.float32)
|
| 33 |
return dict(X=X, E=E, G=Gv, names=row["names"])
|
| 34 |
|
|
|
|
| 42 |
out = {}
|
| 43 |
for k, p in enumerate(PPG):
|
| 44 |
M = np.zeros((n, n))
|
| 45 |
+
v = np.exp(lp[:, k])
|
| 46 |
+
fl = getattr(prep, "floor_ff", None)
|
| 47 |
+
M[iu] = v if fl is None else np.maximum(v, fl) # registry learned_prior.floor_ff: the training minimum (agents/embedspeed)
|
| 48 |
out[p] = M + M.T
|
| 49 |
return out
|
geomgnn/levelpar.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mesh levels of the prior concurrently (agents/embedspeed). The two thin-film solves (e.g. 1.5 and 3 panels per gap) are
|
| 2 |
+
independent; on macOS each runs its windows serially and keeps only ~2-5 cores busy, so the extra levels run in spawned
|
| 3 |
+
worker processes that install the same prior stack (geomgnn.api.set_prior_stack with the recorded registry prior and
|
| 4 |
+
threads) and execute the same statements as the in-process loop; the caller solves the first level meanwhile.
|
| 5 |
+
|
| 6 |
+
TLSQ_LEVEL_PROCS: auto (default: TLSQ_LEVEL_MIN_N <= N <= TLSQ_LEVEL_MAX_N, default 30 and 150, on macOS or with >= 8 threads),
|
| 7 |
+
1 (always), 0 (never).
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 15 |
+
from multiprocessing import get_context
|
| 16 |
+
|
| 17 |
+
_EX: dict = {}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def enabled(sc, levels, threads: int = 2) -> bool:
|
| 21 |
+
from . import api as A
|
| 22 |
+
v = os.environ.get("TLSQ_LEVEL_PROCS", "auto")
|
| 23 |
+
if v == "0" or len(levels) < 2 or not A._STATE.get("pr"):
|
| 24 |
+
return False
|
| 25 |
+
if v == "1":
|
| 26 |
+
return True
|
| 27 |
+
n = len(sc.conductors) # measured (Mac, 18 threads): a gain at N = 67 (18.1 -> 11.9 s with spawned windows), a loss from
|
| 28 |
+
# N = 277 on (69 -> 75 s; grid_full 194 -> 238 s) where the spawned windows already fill the cores
|
| 29 |
+
# Linux x86, 16 CPUs (forked windows): 5q 15.1 -> 12.0 s, 9q 76.0 -> 46.6 s, 1q 7.8 -> 10.3 s (spawn cost); never below 8 threads
|
| 30 |
+
mid = int(os.environ.get("TLSQ_LEVEL_MIN_N", "30")) <= n <= int(os.environ.get("TLSQ_LEVEL_MAX_N", "150"))
|
| 31 |
+
return mid and (sys.platform == "darwin" or int(threads) >= int(os.environ.get("TLSQ_LEVEL_MIN_THREADS", "8")))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _init(paths, impl, pr, threads):
|
| 35 |
+
for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS", "TLSQ_NUM_THREADS"):
|
| 36 |
+
os.environ[k] = str(threads)
|
| 37 |
+
for p in reversed(paths):
|
| 38 |
+
if p not in sys.path:
|
| 39 |
+
sys.path.insert(0, p)
|
| 40 |
+
import torch
|
| 41 |
+
torch.set_num_threads(threads)
|
| 42 |
+
from geomgnn import api as A
|
| 43 |
+
A.set_prior_impl(impl)
|
| 44 |
+
A.set_prior_stack(pr, threads)
|
| 45 |
+
A._thread_limits(threads)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def solve_one(sc, p, threads, alpha):
|
| 49 |
+
"""The statements of the prior loop (geomgnn.api.predict_scene / paper.solve_levels) for one level."""
|
| 50 |
+
from geomgnn import api as A
|
| 51 |
+
from geomgnn._tlsq.embed import fastprior, proxy
|
| 52 |
+
from geomgnn._tlsq.embed.fastprior_loc import micro_mom_loc
|
| 53 |
+
proxy.NUM_THREADS = threads
|
| 54 |
+
if set(A.V2_KWARGS) & set(A._STATE["patches"]):
|
| 55 |
+
from geomgnn import priorv2
|
| 56 |
+
priorv2.clear()
|
| 57 |
+
old = fastprior.ALPHA_GAP_SHARE
|
| 58 |
+
t = time.perf_counter()
|
| 59 |
+
try:
|
| 60 |
+
if alpha is not None:
|
| 61 |
+
fastprior.ALPHA_GAP_SHARE = alpha
|
| 62 |
+
with proxy.substrate("slab_open", sc.stack["substrate_thickness_um"]), A._quiet_mixed_cast():
|
| 63 |
+
mat, _, _ = micro_mom_loc(sc.conductors[0].geom, [c.geom for c in sc.conductors[1:]], eps_r=sc.stack["substrate_eps_r"], ppg=p)
|
| 64 |
+
finally:
|
| 65 |
+
fastprior.ALPHA_GAP_SHARE = old
|
| 66 |
+
return -mat, time.perf_counter() - t
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _executor(n, threads):
|
| 70 |
+
from . import api as A
|
| 71 |
+
key = (n, threads, A._STATE["prior_impl"], repr(A._STATE["pr"]))
|
| 72 |
+
if _EX.get("key") != key:
|
| 73 |
+
if _EX.get("ex") is not None:
|
| 74 |
+
_EX["ex"].shutdown(wait=False, cancel_futures=True)
|
| 75 |
+
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 76 |
+
main = sys.modules["__main__"]
|
| 77 |
+
saved = main.__dict__.pop("__file__", None) # spawn would otherwise re-run the calling script in the worker
|
| 78 |
+
try:
|
| 79 |
+
ex = ProcessPoolExecutor(n, mp_context=get_context("spawn"), initializer=_init,
|
| 80 |
+
initargs=([here], A._STATE["prior_impl"], A._STATE["pr"], threads))
|
| 81 |
+
list(ex.map(int, range(n)))
|
| 82 |
+
finally:
|
| 83 |
+
if saved is not None:
|
| 84 |
+
main.__file__ = saved
|
| 85 |
+
_EX.update(key=key, ex=ex)
|
| 86 |
+
return _EX["ex"]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def solve(sc, levels, threads, alpha) -> tuple[dict, dict]:
|
| 90 |
+
"""{ppg: P} and {ppg: seconds} with levels[1:] in the workers and levels[0] here."""
|
| 91 |
+
ex = _executor(len(levels) - 1, threads)
|
| 92 |
+
futs = [ex.submit(solve_one, sc, p, threads, alpha) for p in levels[1:]]
|
| 93 |
+
first = solve_one(sc, levels[0], threads, alpha)
|
| 94 |
+
res = [first] + [f.result() for f in futs]
|
| 95 |
+
return {p: r[0] for p, r in zip(levels, res)}, {f"{p:g}": r[1] for p, r in zip(levels, res)}
|
geomgnn/overlap.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Embedding concurrently with the prior solves (agents/embedspeed). Both read only the geometry, so the embedding row
|
| 2 |
+
(scene_graph + localtok.add_tokens, the same functions) is computed in one spawned worker process while the caller runs the
|
| 3 |
+
prior solves, and joined before the network: bitwise the same row and priors as the sequential path.
|
| 4 |
+
|
| 5 |
+
The worker is spawned (never forked: macOS Accelerate; the prior forks its own window workers on Linux) once per process
|
| 6 |
+
and reused. TLSQ_OVERLAP=0 turns it off; layouts with fewer than TLSQ_OVERLAP_MIN_N conductors (default 30), and machines with fewer than
|
| 7 |
+
TLSQ_OVERLAP_MIN_THREADS threads (default 4), stay sequential.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
from concurrent.futures import Future, ProcessPoolExecutor
|
| 14 |
+
from multiprocessing import get_context
|
| 15 |
+
|
| 16 |
+
_EX: dict = {}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def enabled(sc, threads: int = 2) -> bool:
|
| 20 |
+
"""On for >= TLSQ_OVERLAP_MIN_N conductors (default 30) and >= TLSQ_OVERLAP_MIN_THREADS threads (default 4): measured on 2 x86
|
| 21 |
+
CPUs the two stages compete for the cores (3 x 3 lattice 141 -> 153 s with the overlap), from 16 they gain (grid_full 609 -> 572 s)."""
|
| 22 |
+
return (os.environ.get("TLSQ_OVERLAP", "1") != "0" and len(sc.conductors) >= int(os.environ.get("TLSQ_OVERLAP_MIN_N", "30"))
|
| 23 |
+
and int(threads) >= int(os.environ.get("TLSQ_OVERLAP_MIN_THREADS", "4")))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _settings() -> dict:
|
| 27 |
+
from geomgnn._tlsq.uge import blocks
|
| 28 |
+
|
| 29 |
+
return {"EMBED_MODE": dict(blocks.EMBED_MODE), "EMBED_CACHE": dict(blocks.EMBED_CACHE),
|
| 30 |
+
"FAR_DECIMATION": dict(blocks.FAR_DECIMATION)}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _apply(threads: int, st: dict):
|
| 34 |
+
from geomgnn._tlsq.embed import proxy
|
| 35 |
+
from geomgnn._tlsq.uge import blocks
|
| 36 |
+
|
| 37 |
+
proxy.NUM_THREADS = threads
|
| 38 |
+
for k, v in st.items():
|
| 39 |
+
getattr(blocks, k).update(v)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _init(threads: int, paths: list):
|
| 43 |
+
for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS", "TLSQ_NUM_THREADS"):
|
| 44 |
+
os.environ[k] = str(threads)
|
| 45 |
+
for p in reversed(paths):
|
| 46 |
+
if p not in sys.path:
|
| 47 |
+
sys.path.insert(0, p)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _embed(sc, threads: int, st: dict) -> tuple:
|
| 51 |
+
import time
|
| 52 |
+
|
| 53 |
+
from geomgnn._tlsq.uge import localtok as lt
|
| 54 |
+
from geomgnn._tlsq.uge.graph import scene_graph
|
| 55 |
+
|
| 56 |
+
_apply(threads, st)
|
| 57 |
+
t = time.perf_counter()
|
| 58 |
+
return lt.add_tokens(sc, scene_graph(sc)), time.perf_counter() - t
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _executor(threads: int) -> ProcessPoolExecutor:
|
| 62 |
+
if _EX.get("key") != threads:
|
| 63 |
+
if _EX.get("ex") is not None:
|
| 64 |
+
_EX["ex"].shutdown(wait=False, cancel_futures=True)
|
| 65 |
+
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 66 |
+
main = sys.modules["__main__"]
|
| 67 |
+
saved = main.__dict__.pop("__file__", None) # spawn would otherwise re-run the calling script in the worker
|
| 68 |
+
try:
|
| 69 |
+
ex = ProcessPoolExecutor(1, mp_context=get_context("spawn"), initializer=_init, initargs=(threads, [here]))
|
| 70 |
+
ex.submit(int, 0).result() # start the worker now, while __file__ is hidden
|
| 71 |
+
finally:
|
| 72 |
+
if saved is not None:
|
| 73 |
+
main.__file__ = saved
|
| 74 |
+
_EX.update(key=threads, ex=ex)
|
| 75 |
+
return _EX["ex"]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def start(sc, threads: int) -> Future:
|
| 79 |
+
"""Future of (embedding row, worker seconds) of scene sc, computed in the worker process."""
|
| 80 |
+
return _executor(threads).submit(_embed, sc, threads, _settings())
|
geomgnn/paper.py
CHANGED
|
@@ -159,6 +159,7 @@ def load(name, reg, model_dir=None, threads=2):
|
|
| 159 |
if a.get("learned_prior"):
|
| 160 |
from . import learned_prior
|
| 161 |
model, prep, _ = learned_prior.load(files(reg, name, "surrogate", model_dir)[0])
|
|
|
|
| 162 |
obj.surrogate = (model, prep)
|
| 163 |
if obj.direct != (a.get("stack") is None and not a.get("learned_prior")):
|
| 164 |
raise RuntimeError(f"{name}: solver-free checkpoints iff no prior stack and no learned prior")
|
|
@@ -189,6 +190,9 @@ def solve_levels(sc, levels, threads=2) -> tuple[dict, dict]:
|
|
| 189 |
"""Positive-mutual prior matrices P = -C at each level under the installed stack (the statements of
|
| 190 |
geomgnn.api.predict_scene's prior loop, any level list)."""
|
| 191 |
from ._tlsq.embed.fastprior_loc import micro_mom_loc
|
|
|
|
|
|
|
|
|
|
| 192 |
proxy.NUM_THREADS = threads
|
| 193 |
if set(A.V2_KWARGS) & set(A._STATE["patches"]):
|
| 194 |
from . import priorv2
|
|
@@ -226,19 +230,40 @@ def combine(a, obj, row, P) -> np.ndarray:
|
|
| 226 |
|
| 227 |
|
| 228 |
def predict_scene(reg, name, sc, threads=2, model_dir=None) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
a = arms(reg)[name]
|
| 230 |
obj = load(name, reg, model_dir, threads)
|
| 231 |
apply_stack(reg, a, threads)
|
| 232 |
t0 = time.perf_counter()
|
| 233 |
-
row = lt.add_tokens(sc, scene_graph(sc))
|
| 234 |
-
t1 = time.perf_counter()
|
| 235 |
need = [] if (a["kind"] == "gnn" and (obj.direct or obj.surrogate is not None)) else levels_of(a)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
P, tl = solve_levels(sc, need, threads) if need else ({}, {})
|
| 237 |
t2 = time.perf_counter()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
C = np.asarray(combine(a, obj, row, P), float)
|
| 239 |
t3 = time.perf_counter()
|
| 240 |
return dict(C=C, names=row["names"], row=row, priors=P,
|
| 241 |
-
timing=dict(geometry=t1 - t0, prior=t2 - t1, prior_levels=tl, network=t3 - t2, total=t3 - t0))
|
| 242 |
|
| 243 |
|
| 244 |
def predict(prepared, name, reg, substrate="Si (cryogenic, training)", thickness_um=350.0, model_dir=None, threads=None,
|
|
@@ -309,6 +334,20 @@ def preload(reg, example=None, names=None) -> dict:
|
|
| 309 |
t = time.perf_counter()
|
| 310 |
predict(prepare(str(example)), d, reg)
|
| 311 |
STARTUP["example_s"] = time.perf_counter() - t
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
STARTUP.update(default=d, numba_warmup_s=A._STATE.get("warmup_s"), total_s=time.perf_counter() - t0)
|
| 313 |
print("preload " + json.dumps({k: (round(v, 2) if isinstance(v, float) else v) for k, v in STARTUP.items()}), flush=True)
|
| 314 |
return dict(STARTUP)
|
|
|
|
| 159 |
if a.get("learned_prior"):
|
| 160 |
from . import learned_prior
|
| 161 |
model, prep, _ = learned_prior.load(files(reg, name, "surrogate", model_dir)[0])
|
| 162 |
+
prep.floor_ff = a["learned_prior"].get("floor_ff")
|
| 163 |
obj.surrogate = (model, prep)
|
| 164 |
if obj.direct != (a.get("stack") is None and not a.get("learned_prior")):
|
| 165 |
raise RuntimeError(f"{name}: solver-free checkpoints iff no prior stack and no learned prior")
|
|
|
|
| 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)."""
|
| 192 |
from ._tlsq.embed.fastprior_loc import micro_mom_loc
|
| 193 |
+
from . import levelpar
|
| 194 |
+
if levelpar.enabled(sc, levels, threads): # the levels concurrently (spawned workers, same stack and statements)
|
| 195 |
+
return levelpar.solve(sc, list(levels), threads, ALPHA)
|
| 196 |
proxy.NUM_THREADS = threads
|
| 197 |
if set(A.V2_KWARGS) & set(A._STATE["patches"]):
|
| 198 |
from . import priorv2
|
|
|
|
| 230 |
|
| 231 |
|
| 232 |
def predict_scene(reg, name, sc, threads=2, model_dir=None) -> dict:
|
| 233 |
+
"""The arm's prediction; an arm's `embedding: {far_k, d_far_um}` (flagship tiers only, agents/embedspeed Part A) selects the
|
| 234 |
+
far-sample decimation of the pair vectors for this call (the paper's arms always use the exact embedding)."""
|
| 235 |
+
from ._tlsq.uge import blocks as _B
|
| 236 |
+
emb = {} if os.environ.get("TLSQ_EMBEDDING_EXACT") == "1" else (arms(reg)[name].get("embedding") or {}) # tests of the exact recipe
|
| 237 |
+
old = dict(_B.FAR_DECIMATION)
|
| 238 |
+
_B.FAR_DECIMATION.update(k=int(emb.get("far_k", 0)), d_far=float(emb.get("d_far_um", 100.0)))
|
| 239 |
+
try:
|
| 240 |
+
return _predict_scene(reg, name, sc, threads, model_dir)
|
| 241 |
+
finally:
|
| 242 |
+
_B.FAR_DECIMATION.clear()
|
| 243 |
+
_B.FAR_DECIMATION.update(old)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _predict_scene(reg, name, sc, threads=2, model_dir=None) -> dict:
|
| 247 |
a = arms(reg)[name]
|
| 248 |
obj = load(name, reg, model_dir, threads)
|
| 249 |
apply_stack(reg, a, threads)
|
| 250 |
t0 = time.perf_counter()
|
|
|
|
|
|
|
| 251 |
need = [] if (a["kind"] == "gnn" and (obj.direct or obj.surrogate is not None)) else levels_of(a)
|
| 252 |
+
from . import overlap as OV
|
| 253 |
+
fut = OV.start(sc, threads) if need and OV.enabled(sc, threads) else None # the embedding runs in the worker during the priors
|
| 254 |
+
row = None if fut else lt.add_tokens(sc, scene_graph(sc))
|
| 255 |
+
t1 = time.perf_counter()
|
| 256 |
P, tl = solve_levels(sc, need, threads) if need else ({}, {})
|
| 257 |
t2 = time.perf_counter()
|
| 258 |
+
extra = {}
|
| 259 |
+
if fut is not None:
|
| 260 |
+
row, embed_s = fut.result()
|
| 261 |
+
extra = dict(overlap=True, geometry_worker=embed_s, geometry_wait_after_prior=time.perf_counter() - t2)
|
| 262 |
+
t2 = time.perf_counter()
|
| 263 |
C = np.asarray(combine(a, obj, row, P), float)
|
| 264 |
t3 = time.perf_counter()
|
| 265 |
return dict(C=C, names=row["names"], row=row, priors=P,
|
| 266 |
+
timing=dict(geometry=t1 - t0, prior=t2 - t1, prior_levels=tl, network=t3 - t2, total=t3 - t0, **extra))
|
| 267 |
|
| 268 |
|
| 269 |
def predict(prepared, name, reg, substrate="Si (cryogenic, training)", thickness_um=350.0, model_dir=None, threads=None,
|
|
|
|
| 334 |
t = time.perf_counter()
|
| 335 |
predict(prepare(str(example)), d, reg)
|
| 336 |
STARTUP["example_s"] = time.perf_counter() - t
|
| 337 |
+
if os.environ.get("TLSQ_PRELOAD_ALL", "1") != "0": # every live arm once (each stack's compile, the surrogates)
|
| 338 |
+
t = time.perf_counter()
|
| 339 |
+
for k in names or live(reg):
|
| 340 |
+
if k != d and arms(reg)[k]["kind"] != "final" and available(k, reg):
|
| 341 |
+
predict(prepare(str(example)), k, reg)
|
| 342 |
+
STARTUP["example_all_arms_s"] = time.perf_counter() - t
|
| 343 |
+
t = time.perf_counter()
|
| 344 |
+
from ._tlsq.uge import nnk
|
| 345 |
+
STARTUP["nn_kernel"] = nnk.available() and nnk._STATE.get("arith") # probe + compile of the exact NN kernel
|
| 346 |
+
from . import overlap
|
| 347 |
+
th = int(os.environ.get("TLSQ_NUM_THREADS") or 2)
|
| 348 |
+
if th >= int(os.environ.get("TLSQ_OVERLAP_MIN_THREADS", "4")):
|
| 349 |
+
overlap._executor(th) # the embedding worker of large layouts, spawned now
|
| 350 |
+
STARTUP["kernel_and_worker_s"] = time.perf_counter() - t
|
| 351 |
STARTUP.update(default=d, numba_warmup_s=A._STATE.get("warmup_s"), total_s=time.perf_counter() - t0)
|
| 352 |
print("preload " + json.dumps({k: (round(v, 2) if isinstance(v, float) else v) for k, v in STARTUP.items()}), flush=True)
|
| 353 |
return dict(STARTUP)
|
geomgnn/respcache.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""In-memory response cache of the Spaces (agents/embedspeed; user decision 2026-10-20): a size-bounded LRU of finished
|
| 2 |
+
predictions keyed by the prepared layout (ground and conductor geometry, names) and every setting of the request. Entries live
|
| 3 |
+
only in this process's memory while the Space runs. TLSQ_RESPONSE_CACHE = max entries (0 = off), TLSQ_RESPONSE_CACHE_MB =
|
| 4 |
+
max total size of the pickled entries."""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import copy
|
| 8 |
+
import hashlib
|
| 9 |
+
import os
|
| 10 |
+
import pickle
|
| 11 |
+
import threading
|
| 12 |
+
from collections import OrderedDict
|
| 13 |
+
|
| 14 |
+
_LRU: OrderedDict = OrderedDict()
|
| 15 |
+
_LOCK = threading.Lock()
|
| 16 |
+
_BYTES = [0]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _limits() -> tuple:
|
| 20 |
+
return int(os.environ.get("TLSQ_RESPONSE_CACHE", "0")), float(os.environ.get("TLSQ_RESPONSE_CACHE_MB", "1024")) * 2**20
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def key(lay, *settings) -> str:
|
| 24 |
+
import shapely
|
| 25 |
+
h = hashlib.sha256(repr((settings, list(lay.names))).encode())
|
| 26 |
+
for g in [lay.ground, *lay.conductors]:
|
| 27 |
+
h.update(shapely.to_wkb(g))
|
| 28 |
+
return h.hexdigest()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def cached(lay, settings: tuple, fn):
|
| 32 |
+
"""fn() through the cache (a deep copy is stored and returned, so callers may modify their result)."""
|
| 33 |
+
n, mb = _limits()
|
| 34 |
+
if n <= 0:
|
| 35 |
+
return fn()
|
| 36 |
+
k = key(lay, *settings)
|
| 37 |
+
with _LOCK:
|
| 38 |
+
if k in _LRU:
|
| 39 |
+
_LRU.move_to_end(k)
|
| 40 |
+
res = copy.deepcopy(_LRU[k][0])
|
| 41 |
+
if isinstance(res.get("timing_s"), dict):
|
| 42 |
+
res["timing_s"]["response_cache_hit"] = True
|
| 43 |
+
return res
|
| 44 |
+
res = fn()
|
| 45 |
+
size = len(pickle.dumps(res, protocol=5))
|
| 46 |
+
if size > mb:
|
| 47 |
+
return res
|
| 48 |
+
with _LOCK:
|
| 49 |
+
_LRU[k] = (copy.deepcopy(res), size)
|
| 50 |
+
_BYTES[0] += size
|
| 51 |
+
while len(_LRU) > n or _BYTES[0] > mb:
|
| 52 |
+
_, (_, s) = _LRU.popitem(last=False)
|
| 53 |
+
_BYTES[0] -= s
|
| 54 |
+
return res
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def stats() -> dict:
|
| 58 |
+
with _LOCK:
|
| 59 |
+
return {"entries": len(_LRU), "mb": _BYTES[0] / 2**20}
|
geomgnn/winpool.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Window solves of the prior on spawned workers (agents/embedspeed; macOS). The vendor's window pool forks, which macOS
|
| 2 |
+
cannot do with Accelerate, so on macOS fastprior_pkg runs the windows serially (a few cores busy). Here the vendor's own
|
| 3 |
+
micro_mom runs with `workers` > 1 and its ProcessPoolExecutor / get_context("fork") are swapped, for that call only, for a
|
| 4 |
+
spawn pool whose workers install the same prior stack (geomgnn.api.set_prior_stack with the recorded registry prior), copy the
|
| 5 |
+
running call's layout (fastprior._LITE, the k-d tree rebuilt) and the module settings, and run fastprior_pkg's window job.
|
| 6 |
+
Each window is the same statements; BLAS threads per window differ (one per worker), so the result is numerically exact,
|
| 7 |
+
not bitwise (gate: <= 1e-9 relative vs the serial windows).
|
| 8 |
+
|
| 9 |
+
TLSQ_WINDOW_PROCS: auto (default: macOS, CPUs from TLSQ_NUM_THREADS / os.cpu_count()), <n> (force n workers), 0 (off).
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 16 |
+
from multiprocessing import get_context
|
| 17 |
+
|
| 18 |
+
_ON: dict = {"n": 0}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def workers() -> int:
|
| 22 |
+
v = os.environ.get("TLSQ_WINDOW_PROCS", "auto")
|
| 23 |
+
if v == "0":
|
| 24 |
+
return 0
|
| 25 |
+
if v != "auto":
|
| 26 |
+
return int(v)
|
| 27 |
+
return (os.cpu_count() or 1) if sys.platform == "darwin" else 0
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _init(paths, impl, pr, state):
|
| 31 |
+
os.environ["TLSQ_WINDOW_PROCS"] = "0"
|
| 32 |
+
os.environ.update({k: "1" for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS",
|
| 33 |
+
"TLSQ_NUM_THREADS", "VECLIB_MAXIMUM_THREADS")})
|
| 34 |
+
for p in reversed(paths):
|
| 35 |
+
if p not in sys.path:
|
| 36 |
+
sys.path.insert(0, p)
|
| 37 |
+
import shapely
|
| 38 |
+
import torch
|
| 39 |
+
torch.set_num_threads(1)
|
| 40 |
+
from geomgnn import api as A
|
| 41 |
+
from geomgnn._tlsq.embed import fastprior as F
|
| 42 |
+
from geomgnn._tlsq.embed import proxy
|
| 43 |
+
A.set_prior_impl(impl)
|
| 44 |
+
A.set_prior_stack(pr, 1)
|
| 45 |
+
A._thread_limits(1)
|
| 46 |
+
proxy.NUM_THREADS = 1
|
| 47 |
+
proxy.SUBSTRATE.clear()
|
| 48 |
+
proxy.SUBSTRATE.update(state["substrate"])
|
| 49 |
+
for k in ("ALPHA_GAP_SHARE", "LITE_WINDOW_BUDGET", "LITE_REFINE", "LITE_GROWTH", "FORMULA_STEP_UM", "ROW_SUM_EPS"):
|
| 50 |
+
setattr(F, k, state["F"][k])
|
| 51 |
+
F.LITE_WINDOW_PPG[:] = state["F"]["LITE_WINDOW_PPG"]
|
| 52 |
+
F.LITE_MAX_CORE[:] = state["F"]["LITE_MAX_CORE"]
|
| 53 |
+
lite = dict(state["lite"])
|
| 54 |
+
lite["tree"] = shapely.STRtree(lite["conds"])
|
| 55 |
+
F._LITE.clear()
|
| 56 |
+
F._LITE.update(lite)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class _SpawnPool(ProcessPoolExecutor):
|
| 60 |
+
def __init__(self, max_workers, mp_context=None):
|
| 61 |
+
from . import api as A
|
| 62 |
+
from ._tlsq.embed import fastprior as F
|
| 63 |
+
from ._tlsq.embed import proxy
|
| 64 |
+
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 65 |
+
state = dict(substrate=dict(proxy.SUBSTRATE), lite={k: v for k, v in F._LITE.items() if k != "tree"},
|
| 66 |
+
F={k: getattr(F, k) for k in ("ALPHA_GAP_SHARE", "LITE_WINDOW_BUDGET", "LITE_REFINE", "LITE_GROWTH",
|
| 67 |
+
"FORMULA_STEP_UM", "ROW_SUM_EPS")}
|
| 68 |
+
| {"LITE_WINDOW_PPG": list(F.LITE_WINDOW_PPG), "LITE_MAX_CORE": list(F.LITE_MAX_CORE)})
|
| 69 |
+
main = sys.modules["__main__"]
|
| 70 |
+
self._saved = main.__dict__.pop("__file__", None) # spawn would otherwise re-run the calling script
|
| 71 |
+
super().__init__(max_workers, mp_context=get_context("spawn"), initializer=_init,
|
| 72 |
+
initargs=([here], A._STATE["prior_impl"], A._STATE["pr"], state))
|
| 73 |
+
|
| 74 |
+
def shutdown(self, *a, **k):
|
| 75 |
+
try:
|
| 76 |
+
super().shutdown(*a, **k)
|
| 77 |
+
finally:
|
| 78 |
+
if self._saved is not None:
|
| 79 |
+
sys.modules["__main__"].__file__ = self._saved
|
| 80 |
+
self._saved = None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class _Serial:
|
| 84 |
+
"""In-process stand-in for the other pools of the call (formula_prior's rows): what macOS runs today."""
|
| 85 |
+
|
| 86 |
+
def __init__(self, *a, **k):
|
| 87 |
+
pass
|
| 88 |
+
|
| 89 |
+
def __enter__(self):
|
| 90 |
+
return self
|
| 91 |
+
|
| 92 |
+
def __exit__(self, *e):
|
| 93 |
+
return False
|
| 94 |
+
|
| 95 |
+
def map(self, fn, *its, **k):
|
| 96 |
+
return map(fn, *its)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _pool(max_workers, mp_context=None):
|
| 100 |
+
"""Spawned workers for the windows of a call with >= TLSQ_WINDOW_MIN_CORES windows (default 5; measured on the Mac: the
|
| 101 |
+
1q lattice's 2 windows 3.4 -> 5.9 s with the spawn, the 9q lattice's 9 windows 23.8 -> 18.1 s); in-process otherwise."""
|
| 102 |
+
from ._tlsq.embed import fastprior as F
|
| 103 |
+
big = len(F._LITE.get("cores", ())) >= int(os.environ.get("TLSQ_WINDOW_MIN_CORES", "5"))
|
| 104 |
+
return _SpawnPool(max_workers) if F._LITE and big else _Serial()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def install() -> bool:
|
| 108 |
+
"""Wrap the installed stack's micro_mom so that its windows run on spawned workers (idempotent; macOS by default)."""
|
| 109 |
+
from . import api as A
|
| 110 |
+
from . import fastprior_pkg as fp
|
| 111 |
+
from ._tlsq.embed import fastprior as F
|
| 112 |
+
n = workers()
|
| 113 |
+
if n < 2 or not A._STATE.get("pr") or not A._STATE.get("mode") or "micro_mom" not in fp._ORIG:
|
| 114 |
+
return False
|
| 115 |
+
if getattr(F.micro_mom, "_winpool", False):
|
| 116 |
+
_ON["n"] = n
|
| 117 |
+
return True
|
| 118 |
+
vendor = fp._ORIG["micro_mom"]
|
| 119 |
+
sig = fp._ORIG["micro_mom_sig"]
|
| 120 |
+
|
| 121 |
+
def micro_mom(*args, **kw):
|
| 122 |
+
ba = sig.bind(*args, **kw)
|
| 123 |
+
if _ON["n"] < 2:
|
| 124 |
+
return fp._micro_mom(*args, **kw)
|
| 125 |
+
ba.arguments["workers"] = _ON["n"]
|
| 126 |
+
fp._PARENT[0] = os.getpid()
|
| 127 |
+
old = F.ProcessPoolExecutor, F.get_context
|
| 128 |
+
F.ProcessPoolExecutor, F.get_context = _pool, (lambda method=None: None)
|
| 129 |
+
try:
|
| 130 |
+
return vendor(*ba.args, **ba.kwargs)
|
| 131 |
+
finally:
|
| 132 |
+
F.ProcessPoolExecutor, F.get_context = old
|
| 133 |
+
|
| 134 |
+
micro_mom._winpool = True
|
| 135 |
+
F.micro_mom = micro_mom
|
| 136 |
+
_ON["n"] = n
|
| 137 |
+
return True
|
geomgnn/x1_core.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
"""X1 shared model code (agents/v4test/PROTOCOL.md): row -> arrays, multifid forward, surrogate priors. No solver, no labels."""
|
| 2 |
import numpy as np
|
| 3 |
|
|
|
|
|
|
|
| 4 |
PPG = (0.375, 0.75, 1.5, 3.0)
|
| 5 |
|
| 6 |
|
|
@@ -15,7 +17,7 @@ def raw_arrays(row, nk, ek, gk):
|
|
| 15 |
pairs = np.array([(i, j) for i in range(n) for j in range(i + 1, n)])
|
| 16 |
X = np.array([[(float(not np.isfinite(nd['log_min_halfwidth'])) if k == 'missing_log_min_halfwidth' else nd[k]) for k in nk]
|
| 17 |
for nd in row['nodes']], np.float32)
|
| 18 |
-
E =
|
| 19 |
G = np.array([row['global'][k] for k in gk], np.float32)
|
| 20 |
return X, E, G, pairs
|
| 21 |
|
|
|
|
| 1 |
"""X1 shared model code (agents/v4test/PROTOCOL.md): row -> arrays, multifid forward, surrogate priors. No solver, no labels."""
|
| 2 |
import numpy as np
|
| 3 |
|
| 4 |
+
from ._tlsq.uge.blocks import edge_matrix
|
| 5 |
+
|
| 6 |
PPG = (0.375, 0.75, 1.5, 3.0)
|
| 7 |
|
| 8 |
|
|
|
|
| 17 |
pairs = np.array([(i, j) for i in range(n) for j in range(i + 1, n)])
|
| 18 |
X = np.array([[(float(not np.isfinite(nd['log_min_halfwidth'])) if k == 'missing_log_min_halfwidth' else nd[k]) for k in nk]
|
| 19 |
for nd in row['nodes']], np.float32)
|
| 20 |
+
E = edge_matrix(row['edges'], ek, n)
|
| 21 |
G = np.array([row['global'][k] for k in gk], np.float32)
|
| 22 |
return X, E, G, pairs
|
| 23 |
|
registry.yaml
CHANGED
|
@@ -696,6 +696,7 @@ final_models:
|
|
| 696 |
# entry below, keep the old one with status: retired (never delete), point gnn_hub.default_model at the new id.
|
| 697 |
gnn_hub:
|
| 698 |
space: shanto268/PlanarCapGNN # NEW private repo (user, 2026-10-16); never the Spaces above
|
|
|
|
| 699 |
title: Planar Capacitance (GNN preview)
|
| 700 |
private: true # Spaces stay private (CLAUDE.md rule 11)
|
| 701 |
space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM
|
|
@@ -843,6 +844,7 @@ gnn_models:
|
|
| 843 |
learned_prior:
|
| 844 |
name: surrogate_t100_norm
|
| 845 |
checkpoint: {path: data_local/learnedprior/runs/t100_norm/model.pt, sha256: 622fc374cc989bcc5569373787996169b8cde1254efdd118baa7252da0d788ce} # = agents/v4test/HASHES.json surrogate_t100_norm
|
|
|
|
| 846 |
code: "geomgnn/lp_surrogate.py = scripts/learnedprior/lp_surrogate.py (sha256 55804c93..., verbatim) + schema_p2d.json (17eba5f7...); geomgnn/learned_prior.py = lp_bench.py Learned.from_gds after the features"
|
| 847 |
ppg: [1.5, 3.0] # predicts log P at 1.5 and 3 panels per gap (the priors the networks read)
|
| 848 |
training: "tri-GNN (1.02M parameters, width 128, 4 rounds) on the exact frozen prior of 35,354 geomfast TRAIN layouts + 384k generated layouts (v1 235k + targeted 149k), 60k steps, H200 job 6497375 (agents/learnedprior/STATUS.md, PROTOCOL.md)"
|
|
@@ -942,7 +944,7 @@ paper_hub:
|
|
| 942 |
space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM
|
| 943 |
default_arm: model
|
| 944 |
checkpoints_repo: shanto268/PlanarCap2026PaperCheckpoints # private model repo: every other checkpoint the paper reports + scripts
|
| 945 |
-
companion_space: shanto268/
|
| 946 |
max_conductors: 70 # signal conductors per layout on this Space (the nine-qubit lattice has 66 + ground)
|
| 947 |
archive:
|
| 948 |
space: shanto268/2026PaperModels
|
|
@@ -951,6 +953,7 @@ paper_hub:
|
|
| 951 |
note: "the earlier draft's model repos (SQuADDS/2026PaperModels-*) are untouched"
|
| 952 |
deployed: {commit: 53ba4502b9697bd65d69f249d71df65c475c863b, date: 2026-10-20, gate: deploy/tests/results/paper_space_gate_20261020.json,
|
| 953 |
live: deploy/tests/results/paper_space_live_20261020_examples.json} # 24 arms, 156 MB bundle, RUNNING on cpu-basic, private
|
|
|
|
| 954 |
prior_stacks: # process-wide prior settings (geomgnn.api.set_prior_stack), installed per request
|
| 955 |
corrected: &stack_corrected # prior v2m + compiled exact solver = the model's prior (gnn_models.GNN); also flagship_hub
|
| 956 |
patches: [priorv2m]
|
|
@@ -1326,6 +1329,7 @@ paper_arms:
|
|
| 1326 |
learned_prior:
|
| 1327 |
name: surrogate_t100_norm
|
| 1328 |
checkpoint: {path: data_local/learnedprior/runs/t100_norm/model.pt, sha256: 622fc374cc989bcc5569373787996169b8cde1254efdd118baa7252da0d788ce}
|
|
|
|
| 1329 |
summary: "A learned surrogate (1.02M parameters, 385,593 generated layouts labelled by the prior alone + every family's training geometry) predicts the two priors; the model's networks correct them. No field solve."
|
| 1330 |
warning: "Use the fast model only for the 13 component families of its training data (interdigital, paddle, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated, synthetic campaign layouts). On a family held out of it, it is behind the physics it distils: 3.113 % (MAE 0.533 / RMSE 0.633 fF) against 1.554 % (0.166 / 0.205 fF). Use the model for a new component type."
|
| 1331 |
paper:
|
|
@@ -1378,6 +1382,8 @@ flagship_hub:
|
|
| 1378 |
commit: 906bc45ae05ce9a1dac796a22c9aef481f079d40 # last commit of the earlier draft's v3 tiers (fast / coarse / fine, 2026-10-10); restore = push this revision
|
| 1379 |
local_copy: data_local/hf_archive/PlanarCapacitanceModel_906bc45a # snapshot_download of that revision (79 files, 27 MB)
|
| 1380 |
note: "the earlier draft's model repos (SQuADDS/2026PaperModels-*) are untouched; the old builder (sync.py without flags) skips this Space"
|
|
|
|
|
|
|
| 1381 |
prior_stacks:
|
| 1382 |
corrected: *stack_corrected # prior v2m + compiled exact solver (the same stack as the paper Space's model)
|
| 1383 |
|
|
@@ -1388,6 +1394,7 @@ flagship_tiers:
|
|
| 1388 |
route: "Accurate"
|
| 1389 |
kind: gnn
|
| 1390 |
arm: full_gnn
|
|
|
|
| 1391 |
stack: corrected
|
| 1392 |
ppg: [1.5, 3.0]
|
| 1393 |
checkpoints:
|
|
@@ -1411,6 +1418,7 @@ flagship_tiers:
|
|
| 1411 |
route: "Balanced"
|
| 1412 |
kind: gnn
|
| 1413 |
arm: full_gnn
|
|
|
|
| 1414 |
stack: corrected
|
| 1415 |
ppg: [0.75, 1.5]
|
| 1416 |
checkpoints:
|
|
@@ -1431,6 +1439,7 @@ flagship_tiers:
|
|
| 1431 |
route: "Fast"
|
| 1432 |
kind: gnn
|
| 1433 |
arm: full_gnn
|
|
|
|
| 1434 |
stack: null
|
| 1435 |
checkpoints:
|
| 1436 |
- {name: acc_v1_s0, path: data_local/flagship_v4/hpc/runs/acc_v1_s0/model.pt, sha256: 9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba}
|
|
|
|
| 696 |
# entry below, keep the old one with status: retired (never delete), point gnn_hub.default_model at the new id.
|
| 697 |
gnn_hub:
|
| 698 |
space: shanto268/PlanarCapGNN # NEW private repo (user, 2026-10-16); never the Spaces above
|
| 699 |
+
status: retired # paused 2026-10-20 (HfApi.pause_space; private, files kept, Space sha 4193e5a7), superseded by the flagship + paper Spaces; restore = HfApi().restart_space
|
| 700 |
title: Planar Capacitance (GNN preview)
|
| 701 |
private: true # Spaces stay private (CLAUDE.md rule 11)
|
| 702 |
space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM
|
|
|
|
| 844 |
learned_prior:
|
| 845 |
name: surrogate_t100_norm
|
| 846 |
checkpoint: {path: data_local/learnedprior/runs/t100_norm/model.pt, sha256: 622fc374cc989bcc5569373787996169b8cde1254efdd118baa7252da0d788ce} # = agents/v4test/HASHES.json surrogate_t100_norm
|
| 847 |
+
floor_ff: 1.7161304599611071e-09 # smallest positive prior mutual entry of the surrogate's training data (learnedprior/p2d_prepared TRAIN, both levels): the predicted priors are floored here before the networks' log (agents/embedspeed; grid_full underflowed to 0)
|
| 848 |
code: "geomgnn/lp_surrogate.py = scripts/learnedprior/lp_surrogate.py (sha256 55804c93..., verbatim) + schema_p2d.json (17eba5f7...); geomgnn/learned_prior.py = lp_bench.py Learned.from_gds after the features"
|
| 849 |
ppg: [1.5, 3.0] # predicts log P at 1.5 and 3 panels per gap (the priors the networks read)
|
| 850 |
training: "tri-GNN (1.02M parameters, width 128, 4 rounds) on the exact frozen prior of 35,354 geomfast TRAIN layouts + 384k generated layouts (v1 235k + targeted 149k), 60k steps, H200 job 6497375 (agents/learnedprior/STATUS.md, PROTOCOL.md)"
|
|
|
|
| 944 |
space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM
|
| 945 |
default_arm: model
|
| 946 |
checkpoints_repo: shanto268/PlanarCap2026PaperCheckpoints # private model repo: every other checkpoint the paper reports + scripts
|
| 947 |
+
companion_space: shanto268/PlanarCapacitanceModel # the flagship Space (fast / balanced / accurate, trained on all data); was PlanarCapGNN until 2026-10-20
|
| 948 |
max_conductors: 70 # signal conductors per layout on this Space (the nine-qubit lattice has 66 + ground)
|
| 949 |
archive:
|
| 950 |
space: shanto268/2026PaperModels
|
|
|
|
| 953 |
note: "the earlier draft's model repos (SQuADDS/2026PaperModels-*) are untouched"
|
| 954 |
deployed: {commit: 53ba4502b9697bd65d69f249d71df65c475c863b, date: 2026-10-20, gate: deploy/tests/results/paper_space_gate_20261020.json,
|
| 955 |
live: deploy/tests/results/paper_space_live_20261020_examples.json} # 24 arms, 156 MB bundle, RUNNING on cpu-basic, private
|
| 956 |
+
text_update: {commit: 34091ebf7be6bbc7ebc37e392b7ae527805cbe97, date: 2026-10-20, gate: deploy/tests/results/paper_space_gate_flagshiplink_20261020.json} # README companion link -> flagship Space; outputs unchanged (48/48 live matrices equal)
|
| 957 |
prior_stacks: # process-wide prior settings (geomgnn.api.set_prior_stack), installed per request
|
| 958 |
corrected: &stack_corrected # prior v2m + compiled exact solver = the model's prior (gnn_models.GNN); also flagship_hub
|
| 959 |
patches: [priorv2m]
|
|
|
|
| 1329 |
learned_prior:
|
| 1330 |
name: surrogate_t100_norm
|
| 1331 |
checkpoint: {path: data_local/learnedprior/runs/t100_norm/model.pt, sha256: 622fc374cc989bcc5569373787996169b8cde1254efdd118baa7252da0d788ce}
|
| 1332 |
+
floor_ff: 1.7161304599611071e-09 # smallest positive prior mutual entry of the surrogate's training data (learnedprior/p2d_prepared TRAIN, both levels): the predicted priors are floored here before the networks' log (agents/embedspeed; grid_full underflowed to 0)
|
| 1333 |
summary: "A learned surrogate (1.02M parameters, 385,593 generated layouts labelled by the prior alone + every family's training geometry) predicts the two priors; the model's networks correct them. No field solve."
|
| 1334 |
warning: "Use the fast model only for the 13 component families of its training data (interdigital, paddle, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated, synthetic campaign layouts). On a family held out of it, it is behind the physics it distils: 3.113 % (MAE 0.533 / RMSE 0.633 fF) against 1.554 % (0.166 / 0.205 fF). Use the model for a new component type."
|
| 1335 |
paper:
|
|
|
|
| 1382 |
commit: 906bc45ae05ce9a1dac796a22c9aef481f079d40 # last commit of the earlier draft's v3 tiers (fast / coarse / fine, 2026-10-10); restore = push this revision
|
| 1383 |
local_copy: data_local/hf_archive/PlanarCapacitanceModel_906bc45a # snapshot_download of that revision (79 files, 27 MB)
|
| 1384 |
note: "the earlier draft's model repos (SQuADDS/2026PaperModels-*) are untouched; the old builder (sync.py without flags) skips this Space"
|
| 1385 |
+
deployed: {commit: 8db73f7d1bcd7a5aeaf777dfd9f878afa054068a, date: 2026-10-20, gate: deploy/tests/results/flagship_space_gate_20261020.json,
|
| 1386 |
+
live: deploy/tests/results/flagship_space_live_20261020.json} # 3 tiers, 80.7 MB bundle, RUNNING on cpu-basic, private (first push 79acb1d9, then the Space timings)
|
| 1387 |
prior_stacks:
|
| 1388 |
corrected: *stack_corrected # prior v2m + compiled exact solver (the same stack as the paper Space's model)
|
| 1389 |
|
|
|
|
| 1394 |
route: "Accurate"
|
| 1395 |
kind: gnn
|
| 1396 |
arm: full_gnn
|
| 1397 |
+
embedding: {far_k: 64, d_far_um: 100.0} # agents/embedspeed Part A (PROTOCOL.md amendment 2): far-sample decimation F64 of the pair vectors, the fastest arm tying the exact embedding on validation 4,608 and the 1q / 5q / 9q lattices; the paper Space keeps the exact embedding
|
| 1398 |
stack: corrected
|
| 1399 |
ppg: [1.5, 3.0]
|
| 1400 |
checkpoints:
|
|
|
|
| 1418 |
route: "Balanced"
|
| 1419 |
kind: gnn
|
| 1420 |
arm: full_gnn
|
| 1421 |
+
embedding: {far_k: 64, d_far_um: 100.0} # agents/embedspeed Part A (PROTOCOL.md amendment 2): far-sample decimation F64 of the pair vectors, the fastest arm tying the exact embedding on validation 4,608 and the 1q / 5q / 9q lattices; the paper Space keeps the exact embedding
|
| 1422 |
stack: corrected
|
| 1423 |
ppg: [0.75, 1.5]
|
| 1424 |
checkpoints:
|
|
|
|
| 1439 |
route: "Fast"
|
| 1440 |
kind: gnn
|
| 1441 |
arm: full_gnn
|
| 1442 |
+
embedding: {far_k: 64, d_far_um: 100.0} # agents/embedspeed Part A (PROTOCOL.md amendment 2): far-sample decimation F64 of the pair vectors, the fastest arm tying the exact embedding on validation 4,608 and the 1q / 5q / 9q lattices; the paper Space keeps the exact embedding
|
| 1443 |
stack: null
|
| 1444 |
checkpoints:
|
| 1445 |
- {name: acc_v1_s0, path: data_local/flagship_v4/hpc/runs/acc_v1_s0/model.pt, sha256: 9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba}
|
warm.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build-time warm-up (Docker variant): the Space's own preload at import of app.py (every arm / tier on the interdigital
|
| 2 |
+
example: the prior's numba kernels, the NN kernel, the surrogates), so the image carries the compiled cache."""
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
t = time.perf_counter()
|
| 7 |
+
os.environ["TLSQ_PRELOAD"] = "1"
|
| 8 |
+
import app # noqa: E402,F401 (app.py preloads at import; the server starts only under __main__)
|
| 9 |
+
|
| 10 |
+
print("warm.py: preload and cache population", round(time.perf_counter() - t, 1), "s", flush=True)
|