diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..97176c4eb37e2aca707c2311b701bafe41abbd53 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +**/__pycache__ +**/*.pyc +**/.pytest_cache diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..2deedc4e993142b2c53072af3a7ccd8ac77a510f --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.gds filter=lfs diff=lfs merge=lfs -text diff --git a/Dockerfile b/Dockerfile index bf06e0656d05d7488d4bada8e8f26f1bc4cde079..a5f24be46d6bc8a054d813361c3ba0153bf7b0a3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,16 +1,17 @@ -FROM python:3.10-slim - -ENV PYTHONDONTWRITEBYTECODE=1 \ - PYTHONUNBUFFERED=1 \ - PIP_NO_CACHE_DIR=1 - -WORKDIR /app - -COPY requirements.txt . -RUN pip install --upgrade pip && pip install -r requirements.txt - -COPY . . - +FROM python:3.12-slim +ARG TARGETARCH +# gdstk has no Linux arm64 wheel: compile it there (local arm64 builds only; HF builds amd64 and skips this) +RUN if [ "$TARGETARCH" != "amd64" ]; then apt-get update && apt-get install -y --no-install-recommends build-essential \ + cmake zlib1g-dev libqhull-dev && rm -rf /var/lib/apt/lists/*; fi +RUN useradd -m -u 1000 user +USER user +ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH PYTHONUNBUFFERED=1 PYTHONPATH=/home/user/app/src \ + KERAS_BACKEND=torch NUMBA_CPU_NAME=generic NUMBA_CACHE_DIR=/home/user/app/numba_cache \ + SQUADDS_ML_API_EXIT_ON_LOAD_FAILURE=1 +WORKDIR /home/user/app +COPY --chown=user requirements.txt . +RUN pip install --no-cache-dir --user -r requirements.txt +COPY --chown=user . . +RUN python warm.py && date -u +%Y-%m-%dT%H:%M:%SZ > IMAGE_BUILT_AT EXPOSE 7860 - -CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"] +CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"] diff --git a/README.md b/README.md index e610745554663cf1c07a86284d53e2e5701b3ef6..faf2d518a2f3f53b4272c4e041dbb17524866422 100644 --- a/README.md +++ b/README.md @@ -1,48 +1,30 @@ --- title: SQuADDS ML Inference API +emoji: 🧪 +colorFrom: blue +colorTo: gray sdk: docker app_port: 7860 license: mit +short_description: REST API for the machine-learning models of SQuADDS --- # SQuADDS ML Inference API -An HTTP API for SQuADDS machine-learning models. +A REST API for machine-learning models trained on SQuADDS data. Send JSON and get predictions back. The API is free and needs no sign-in. -Auto-generated deployment bundle for serving ML_qubit_design models with a FastAPI app. +## TransmonCross Hamiltonian to geometry -## Live URLs +The first model served here is `transmon_cross_hamiltonian_inverse`. It takes a target qubit frequency (GHz) and anharmonicity (MHz) and predicts the TransmonCross geometry that gives them, in meters: the readout claw length, the claw ground spacing and the cross length. Feed those values straight into SQuADDS or Qiskit Metal. -- Space repo: https://huggingface.co/spaces/SQuADDS/squadds-ml-inference-api -- Space host: https://squadds-squadds-ml-inference-api.hf.space - -## Endpoints - -- `GET /health` -- `GET /models` -- `POST /predict` - -## Quickstart - -List models: - -```bash -curl https://squadds-squadds-ml-inference-api.hf.space/models -``` - -## Included Models - -Run a sample prediction: +The model was developed in collaboration with Taylor Patti, Nicola Pancotti, Enectali Figueroa-Feliciano, Sara Sussman, Abhishek Chakraborty, Olivia Seidel, Firas Abouzahr, Eli Levenson-Falk and Sadman Ahmed Shanto. Olivia Seidel and Firas Abouzahr trained it. The weights are in the model repo [SQuADDS/transmon-cross-hamiltonian-inverse](https://huggingface.co/SQuADDS/transmon-cross-hamiltonian-inverse). ```bash -curl -X POST \ - https://squadds-squadds-ml-inference-api.hf.space/predict \ +curl -X POST https://squadds-squadds-ml-inference-api.hf.space/predict \ -H 'Content-Type: application/json' \ - -d '{"model_id": "transmon_cross_hamiltonian_inverse", "inputs": {"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0}, "options": {"include_scaled_outputs": false}}' + -d '{"model_id": "transmon_cross_hamiltonian_inverse", "inputs": {"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0}}' ``` -Sample response: - ```json { "model_id": "transmon_cross_hamiltonian_inverse", @@ -54,34 +36,47 @@ Sample response: "design_options.cross_length": 0.0002005973074119538 } ], - "metadata": { - "input_order": [ - "qubit_frequency_GHz", - "anharmonicity_MHz" - ], - "output_order": [ - "design_options.connection_pads.readout.claw_length", - "design_options.connection_pads.readout.ground_spacing", - "design_options.cross_length" - ], - "input_units": { - "qubit_frequency_GHz": "GHz", - "anharmonicity_MHz": "MHz" - }, - "output_units": { - "design_options.connection_pads.readout.claw_length": "m", - "design_options.connection_pads.readout.ground_spacing": "m", - "design_options.cross_length": "m" - }, - "num_predictions": 1 - } + "metadata": {"input_order": ["qubit_frequency_GHz", "anharmonicity_MHz"], "num_predictions": 1, "...": "..."} } ``` -- `transmon_cross_hamiltonian_inverse`: Inverse model that predicts TransmonCross geometry parameters from target Hamiltonian values. +`inputs` can also be a list of up to 1000 objects. Add `"options": {"include_scaled_outputs": true}` to get the raw scaled outputs too. + +## Endpoints + +These routes work as before: + +- `GET /health` lists the ready models. +- `GET /models` lists every model with its status and units. +- `POST /predict` runs a model, as in the example above. + +The `/v1` routes work the same way for every model: + +- `GET /v1/models` lists the models, and `GET /v1/models/{model_id}` describes one. +- `GET /v1/models/{model_id}/schema` gives the request schema. Add `?format=tool` for a ready agent tool definition. +- `POST /v1/models/{model_id}/predict` takes `{"inputs": {...}, "options": {...}}`. +- `GET /v1/health` reports the state of each model and the build. + +```bash +curl -X POST https://squadds-squadds-ml-inference-api.hf.space/v1/models/transmon_cross_hamiltonian_inverse/predict \ + -H 'Content-Type: application/json' \ + -d '{"inputs": {"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0}}' +``` + +The answer has the predictions under `outputs`, the names and units under `metadata`, and the time taken under `timing_s`. Errors come back as `{"error": {"code": ..., "message": ...}}`. Interactive documentation is at `/docs`. + +More SQuADDS models will be added to this API. + +## Limits + +Requests run one at a time, and a repeated request is answered from a cache. Each address can send 60 requests per minute. When the queue is full the API answers 429 with a `Retry-After` header. + +## Links + +- Code: [github.com/LFL-Lab/SQuADDS](https://github.com/LFL-Lab/SQuADDS) +- Documentation: [ML models in SQuADDS](https://lfl-lab.github.io/SQuADDS/source/ml_models.html) +- Organization: [huggingface.co/SQuADDS](https://huggingface.co/SQuADDS) -## Skipped Models +## Licence -- `transmon_cross_cap_matrix_inverse`: No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras -- `coupler_ncap_cap_matrix_inverse`: No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras -- `cavity_claw_route_meander_inverse`: No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate.keras, model/best_keras_model_model2_surrogate.keras +MIT. diff --git a/app.py b/app.py index 96890ea2bcef167fcd9f70f50a576623f552909b..0a42f7ded49a60681944727b119b5c4c9444dbef 100644 --- a/app.py +++ b/app.py @@ -1,6 +1,7 @@ +import logging from pathlib import Path from squadds_ml_api.api import create_app - +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s") app = create_app(Path(__file__).resolve().parent) diff --git a/artifacts/transmon_cross_hamiltonian_inverse/X_names b/artifacts/transmon_cross_hamiltonian_inverse/X_names deleted file mode 100644 index b3d91290b008b1244a50f32c9daab4ec1a7308bd..0000000000000000000000000000000000000000 --- a/artifacts/transmon_cross_hamiltonian_inverse/X_names +++ /dev/null @@ -1,2 +0,0 @@ -qubit_frequency_GHz -anharmonicity_MHz \ No newline at end of file diff --git a/artifacts/transmon_cross_hamiltonian_inverse/model/best_inverse_model_surrogate_defined_loss.keras b/artifacts/transmon_cross_hamiltonian_inverse/model/best_inverse_model_surrogate_defined_loss.keras deleted file mode 100644 index 17c50be509f80305a6dcaf2c6a2eb4fa099c0ddd..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/model/best_inverse_model_surrogate_defined_loss.keras and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_anharmonicity_MHz.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_anharmonicity_MHz.save deleted file mode 100644 index d94cfd5bd82c62e7d36a5f04e478f67511b19421..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_anharmonicity_MHz.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_anharmonicity_MHz.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_anharmonicity_MHz.save deleted file mode 100644 index fac9dc445462920ba348be5d7ee9bd315ae2712f..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_anharmonicity_MHz.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_qubit_frequency_GHz.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_qubit_frequency_GHz.save deleted file mode 100644 index 21e45d808ff20974fcb5e477a37c8e84f2471422..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_qubit_frequency_GHz.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_qubit_frequency_GHz.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_qubit_frequency_GHz.save deleted file mode 100644 index 886a07df2fb2ee6629857398eef718da1e66e558..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_qubit_frequency_GHz.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.claw_length_one_hot_encoding.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.claw_length_one_hot_encoding.save deleted file mode 100644 index faf41544a6d69bd66c3b71806c2e21955a37b041..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.claw_length_one_hot_encoding.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.ground_spacing_one_hot_encoding.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.ground_spacing_one_hot_encoding.save deleted file mode 100644 index 992c059aebd766a47fe1d6a781c1b04e4defcab3..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.ground_spacing_one_hot_encoding.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.cross_length_one_hot_encoding.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.cross_length_one_hot_encoding.save deleted file mode 100644 index 805523c39f633bf9338309e6262f310a86a2c8bf..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.cross_length_one_hot_encoding.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.claw_length.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.claw_length.save deleted file mode 100644 index 0b09d82d8a945d6b7efee8fdd6cd25461eaff916..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.claw_length.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.ground_spacing.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.ground_spacing.save deleted file mode 100644 index 55705564cd7e797fcbd694e743bab24b3042d3b7..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.ground_spacing.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.cross_length.save b/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.cross_length.save deleted file mode 100644 index e4f2def66247b5613cededc6f4660af05c41c1a0..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.cross_length.save and /dev/null differ diff --git a/artifacts/transmon_cross_hamiltonian_inverse/y_columns.npy b/artifacts/transmon_cross_hamiltonian_inverse/y_columns.npy deleted file mode 100644 index c04782870d4daf39673ba1a34b26db593db86bc5..0000000000000000000000000000000000000000 Binary files a/artifacts/transmon_cross_hamiltonian_inverse/y_columns.npy and /dev/null differ diff --git a/bundle.lock.json b/bundle.lock.json new file mode 100644 index 0000000000000000000000000000000000000000..b6d2c6bb1b37623289b806ac2bab4d788fad482e --- /dev/null +++ b/bundle.lock.json @@ -0,0 +1,48 @@ +{ + "built_at": "2026-11-14T18:10:35+00:00", + "squadds": { + "commit": "53ec2b11f5d2c212e314d858e632c327b97714cc", + "dirty": false, + "dirty_files": [] + }, + "registry_sha256": "1dbf099ad5fb9ed2abd1610c1bbfaefb6a5d40ca702d10c11770342ff7ebf7da", + "models": { + "transmon_cross_hamiltonian_inverse": { + "visibility": "public", + "repo_id": "SQuADDS/transmon-cross-hamiltonian-inverse", + "revision": "26f2e04eb09ccd816e1c39ca7aa90a88bd737171", + "files": { + "inference_manifest.json": "093d984b6e9372ba1f601742a68cfa3f222be9ac7ff3f756be3b87a4acf433fb", + "model/best_inverse_model_surrogate_defined_loss.keras": "20442b08a83b9d8cba43f5fe4594d04566184b0d4ed399a80b2106ff4f4bda30", + "X_names": "6eff9d4082d11593ca562b1bb1edb582c1f2033bbee28b6fd65d84c523af4bad", + "y_columns.npy": "b0ac62e1f9f61d878633cb24cdc9ae9c942dacb7c12cc521b0d8f23bafcc3755", + "scalers/scaler_X_qubit_frequency_GHz.save": "de2428fcc998fcb6108969fe7d7746e7dcece44b6aeaff2e4c5bcbf91e50f5fc", + "scalers/scaler_X_anharmonicity_MHz.save": "0386abd75ab411717739b1091a19d510da081038c29e0063685b0cb774fe47d9", + "scalers/scaler_y_design_options.connection_pads.readout.claw_length_one_hot_encoding.save": "9576bc4393c987ebf765612df6bb6f0ad3c93de5e5ffcf01c14d5bdf804cd892", + "scalers/scaler_y_design_options.connection_pads.readout.ground_spacing_one_hot_encoding.save": "a38fcfcd1c4ef4b0ed7814dced91a110ee9033da8d5ebb319c14859e9ff786c2", + "scalers/scaler_y_design_options.cross_length_one_hot_encoding.save": "356bf37ad04ec755d37bc5a09f282bca015c3c8c542e050a110f4ede51a2c1b8" + } + }, + "planar_capacitance_flagship": { + "visibility": "hidden", + "repo_id": "SQuADDS/PlanarCapacitance-flagship", + "revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc", + "files": { + "accurate/acc_v2m_sf_s0.pt": "cc69c5818f5028c26177159b88239116520abbb290743d6a6c091657e8dbf1c5", + "accurate/acc_v2m_sf_s1.pt": "2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57", + "accurate/acc_v2m_sf_s2.pt": "d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed" + } + }, + "planar_capacitance_fast": { + "visibility": "hidden", + "repo_id": "SQuADDS/PlanarCapacitance-flagship", + "revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc", + "files": { + "fast/acc_v1_s0.pt": "9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba", + "fast/acc_v1_s1.pt": "f1ad2ca065dd650ccabcad73a3c6ad2ac1042f4f68bb828893bbdecc47411ffe", + "fast/acc_v1_s2.pt": "8cbada211724df5cc05a7b4fdd232607de047b248a43993d3844bd68ff8060c4", + "fast/sall_all_s0.pt": "132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac" + } + } + } +} diff --git a/deployment_manifest.json b/deployment_manifest.json deleted file mode 100644 index 1b62a1a54c00c10b19e1908566555462bb09e26e..0000000000000000000000000000000000000000 --- a/deployment_manifest.json +++ /dev/null @@ -1,161 +0,0 @@ -{ - "generated_at": "2026-04-11T02:52:17.016202+00:00", - "space": { - "repo_id": "SQuADDS/squadds-ml-inference-api", - "title": "SQuADDS ML Inference API", - "sdk": "docker", - "app_port": 7860, - "license": "mit", - "host": "https://squadds-squadds-ml-inference-api.hf.space", - "repo_url": "https://huggingface.co/spaces/SQuADDS/squadds-ml-inference-api" - }, - "models": [ - { - "id": "transmon_cross_hamiltonian_inverse", - "display_name": "TransmonCross Hamiltonian to Geometry", - "description": "Inverse model that predicts TransmonCross geometry parameters from target Hamiltonian values.", - "artifact_dir": "artifacts/transmon_cross_hamiltonian_inverse", - "model_path": "model/best_inverse_model_surrogate_defined_loss.keras", - "input_names_path": "X_names", - "input_names_format": "text_lines", - "output_names_path": "y_columns.npy", - "output_names_format": "npy", - "x_scaler_pattern": "scalers/scaler_X_{name}.save", - "y_scaler_pattern": "scalers/scaler_y_{name}_one_hot_encoding.save", - "input_units": { - "qubit_frequency_GHz": "GHz", - "anharmonicity_MHz": "MHz" - }, - "output_units": { - "design_options.connection_pads.readout.claw_length": "m", - "design_options.connection_pads.readout.ground_spacing": "m", - "design_options.cross_length": "m" - }, - "sample_request": { - "model_id": "transmon_cross_hamiltonian_inverse", - "inputs": { - "qubit_frequency_GHz": 4.85, - "anharmonicity_MHz": -205.0 - }, - "options": { - "include_scaled_outputs": false - } - }, - "sample_response": { - "model_id": "transmon_cross_hamiltonian_inverse", - "display_name": "TransmonCross Hamiltonian to Geometry", - "predictions": [ - { - "design_options.connection_pads.readout.claw_length": 0.00011072495544794947, - "design_options.connection_pads.readout.ground_spacing": 4.571595582092414e-06, - "design_options.cross_length": 0.0002005973074119538 - } - ], - "metadata": { - "input_order": [ - "qubit_frequency_GHz", - "anharmonicity_MHz" - ], - "output_order": [ - "design_options.connection_pads.readout.claw_length", - "design_options.connection_pads.readout.ground_spacing", - "design_options.cross_length" - ], - "input_units": { - "qubit_frequency_GHz": "GHz", - "anharmonicity_MHz": "MHz" - }, - "output_units": { - "design_options.connection_pads.readout.claw_length": "m", - "design_options.connection_pads.readout.ground_spacing": "m", - "design_options.cross_length": "m" - }, - "num_predictions": 1 - } - }, - "status": "ready", - "status_detail": "", - "tags": [ - "inverse-design", - "transmon", - "hamiltonian" - ], - "prediction_output_index": 0 - }, - { - "id": "transmon_cross_cap_matrix_inverse", - "display_name": "TransmonCross Cap Matrix to Geometry", - "description": "Inverse model that predicts TransmonCross geometry parameters from cap matrix targets.", - "artifact_dir": "", - "model_path": "", - "input_names_path": "X_names", - "input_names_format": "text_lines", - "output_names_path": "y_columns.npy", - "output_names_format": "npy", - "x_scaler_pattern": "scalers/scaler_X_{name}.save", - "y_scaler_pattern": "scalers/scaler_y_{name}_one_hot_encoding.save", - "input_units": {}, - "output_units": {}, - "sample_request": null, - "sample_response": null, - "status": "missing_model_artifact", - "status_detail": "No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras", - "tags": [ - "inverse-design", - "transmon", - "cap-matrix" - ], - "prediction_output_index": 0 - }, - { - "id": "coupler_ncap_cap_matrix_inverse", - "display_name": "NCap Coupler Cap Matrix to Geometry", - "description": "Inverse model that predicts NCap coupler geometry from cap matrix targets.", - "artifact_dir": "", - "model_path": "", - "input_names_path": "X_names", - "input_names_format": "text_lines", - "output_names_path": "y_columns.npy", - "output_names_format": "npy", - "x_scaler_pattern": "scalers/scaler_X_{name}.save", - "y_scaler_pattern": "scalers/scaler_y_{name}_one_hot_encoding.save", - "input_units": {}, - "output_units": {}, - "sample_request": null, - "sample_response": null, - "status": "missing_model_artifact", - "status_detail": "No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras", - "tags": [ - "inverse-design", - "coupler", - "cap-matrix" - ], - "prediction_output_index": 0 - }, - { - "id": "cavity_claw_route_meander_inverse", - "display_name": "Cavity Claw RouteMeander Targets to Geometry", - "description": "Inverse model that predicts cavity claw RouteMeander geometry from target cavity frequency and kappa.", - "artifact_dir": "", - "model_path": "", - "input_names_path": "X_names", - "input_names_format": "text_lines", - "output_names_path": "y_columns.npy", - "output_names_format": "npy", - "x_scaler_pattern": "scalers/scaler_X_{name}.save", - "y_scaler_pattern": "scalers/scaler_y_{name}_one_hot_encoding.save", - "input_units": {}, - "output_units": {}, - "sample_request": null, - "sample_response": null, - "status": "missing_model_artifact", - "status_detail": "No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate.keras, model/best_keras_model_model2_surrogate.keras", - "tags": [ - "inverse-design", - "cavity", - "readout" - ], - "prediction_output_index": 0 - } - ] -} diff --git a/examples/interdigital.gds b/examples/interdigital.gds new file mode 100644 index 0000000000000000000000000000000000000000..6cbb2a694e29e93d270b9f14afc998b037387aeb Binary files /dev/null and b/examples/interdigital.gds differ diff --git a/examples/planar_capacitance_fast.json b/examples/planar_capacitance_fast.json new file mode 100644 index 0000000000000000000000000000000000000000..a2f5a9cab636821e20eaae479f07a0dceaffb93d --- /dev/null +++ b/examples/planar_capacitance_fast.json @@ -0,0 +1,103 @@ +{ + "file": "examples/interdigital.gds", + "request": { + "inputs": {} + }, + "response": { + "model_id": "planar_capacitance_fast", + "family": "planar_capacitance", + "revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc", + "outputs": { + "names": [ + "G", + "C1", + "C2" + ], + "matrix_fF": [ + [ + 31.592315673828125, + -4.261831760406494, + -5.681989669799805 + ], + [ + -4.261831760406494, + 6.577047824859619, + -2.2709009647369385 + ], + [ + -5.681989669799805, + -2.2709009647369385, + 7.988653659820557 + ] + ], + "units": "fF", + "convention": "Maxwell matrix, ground first (row and column 0), nets never merged", + "sim_results": { + "C1_to_C1": 6.577047824859619, + "C1_to_C2": 2.2709009647369385, + "C1_to_ground": 4.261831760406494, + "C2_to_C2": 7.988653659820557, + "C2_to_ground": 5.681989669799805, + "ground_to_ground": 31.592315673828125, + "maxwell_matrix": { + "C_G_G": 31.592315673828125, + "C_G_C1": -4.261831760406494, + "C_G_C2": -5.681989669799805, + "C_C1_G": -4.261831760406494, + "C_C1_C1": 6.577047824859619, + "C_C1_C2": -2.2709009647369385, + "C_C2_G": -5.681989669799805, + "C_C2_C1": -2.2709009647369385, + "C_C2_C2": 7.988653659820557 + }, + "units": "fF" + } + }, + "metadata": { + "n_conductors": 3, + "checks": { + "symmetric_max_abs": 0.0, + "symmetric": true, + "diagonal_positive": true, + "offdiag_all_negative": true, + "closure_min_row_sum": 0.03576302528381348, + "closure": true, + "signal_block_min_eig": 4.904795034420886, + "positive_definite": true, + "passed": true + }, + "warnings": [ + "Use the fast model only for quick screening of the component families it was trained on (interdigital, paddle, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated and synthetic campaign layouts). On new designs of a trained family (B5) it was worse than the physics alone, 3.175 % (MAE 0.583 / RMSE 0.824 fF) against 1.765 % (0.275 / 0.376 fF), and the paper's version of it was worse than the physics alone on a held-out family too, 3.11 % (0.533 / 0.633 fF) against 1.55 % (0.166 / 0.205 fF). Use the flagship model for anything that matters.", + "metal on layer 2/0 inside the window is not assigned (ground / conductor) and is ignored", + "metal on layer 3/0 inside the window is not assigned (ground / conductor) and is ignored" + ], + "substrate": { + "eps_r": 11.45, + "thickness_um": 350.0, + "training_stack": { + "eps_r": 11.45, + "thickness_um": 350.0 + }, + "embedding_stack": { + "eps_r": 11.45, + "thickness_um": 350.0 + }, + "tested": true, + "route": "training stack", + "prior_solved_at": null, + "eps_rescale_factor": 1.0 + }, + "ground_detection": null, + "threads": 2, + "prior_version": "learned prior surrogate", + "weights_sha256": [ + "9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba", + "f1ad2ca065dd650ccabcad73a3c6ad2ac1042f4f68bb828893bbdecc47411ffe", + "8cbada211724df5cc05a7b4fdd232607de047b248a43993d3844bd68ff8060c4" + ], + "learned_prior_sha256": "132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac" + } + }, + "rtol": 1e-05, + "note": "generated on macOS arm64 (Apple M5 Pro, 2 threads) with squadds.ml.capacitance.serving; priors on x86 differ by up to ~2.4e-3 relative, so compare with rtol 5e-3 there" +} diff --git a/examples/planar_capacitance_flagship.json b/examples/planar_capacitance_flagship.json new file mode 100644 index 0000000000000000000000000000000000000000..11ccce980432e772c6ef2ba5638c758720c63fcd --- /dev/null +++ b/examples/planar_capacitance_flagship.json @@ -0,0 +1,104 @@ +{ + "file": "examples/interdigital.gds", + "request": { + "inputs": {} + }, + "response": { + "model_id": "planar_capacitance_flagship", + "family": "planar_capacitance", + "revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc", + "outputs": { + "names": [ + "G", + "C1", + "C2" + ], + "matrix_fF": [ + [ + 31.726598739624023, + -4.264019012451172, + -5.710771560668945 + ], + [ + -4.264019012451172, + 6.598451614379883, + -2.2851016521453857 + ], + [ + -5.710771560668945, + -2.2851016521453857, + 8.045040130615234 + ] + ], + "units": "fF", + "convention": "Maxwell matrix, ground first (row and column 0), nets never merged", + "sim_results": { + "C1_to_C1": 6.598451614379883, + "C1_to_C2": 2.2851016521453857, + "C1_to_ground": 4.264019012451172, + "C2_to_C2": 8.045040130615234, + "C2_to_ground": 5.710771560668945, + "ground_to_ground": 31.726598739624023, + "maxwell_matrix": { + "C_G_G": 31.726598739624023, + "C_G_C1": -4.264019012451172, + "C_G_C2": -5.710771560668945, + "C_C1_G": -4.264019012451172, + "C_C1_C1": 6.598451614379883, + "C_C1_C2": -2.2851016521453857, + "C_C2_G": -5.710771560668945, + "C_C2_C1": -2.2851016521453857, + "C_C2_C2": 8.045040130615234 + }, + "units": "fF" + } + }, + "metadata": { + "n_conductors": 3, + "checks": { + "symmetric_max_abs": 0.0, + "symmetric": true, + "diagonal_positive": true, + "offdiag_all_negative": true, + "closure_min_row_sum": 0.04916691780090332, + "closure": true, + "signal_block_min_eig": 4.924905422141389, + "positive_definite": true, + "passed": true + }, + "warnings": [ + "metal on layer 2/0 inside the window is not assigned (ground / conductor) and is ignored", + "metal on layer 3/0 inside the window is not assigned (ground / conductor) and is ignored" + ], + "substrate": { + "eps_r": 11.45, + "thickness_um": 350.0, + "training_stack": { + "eps_r": 11.45, + "thickness_um": 350.0 + }, + "embedding_stack": { + "eps_r": 11.45, + "thickness_um": 350.0 + }, + "tested": true, + "route": "training stack", + "prior_solved_at": { + "eps_r": 11.45, + "thickness_um": 350.0 + }, + "eps_rescale_factor": 1.0 + }, + "ground_detection": null, + "threads": 2, + "prior_version": "v2m_sf_fc_dipfill_margin_slabfar", + "weights_sha256": [ + "cc69c5818f5028c26177159b88239116520abbb290743d6a6c091657e8dbf1c5", + "2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57", + "d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed" + ] + } + }, + "rtol": 1e-05, + "note": "generated on macOS arm64 (Apple M5 Pro, 2 threads) with squadds.ml.capacitance.serving; priors on x86 differ by up to ~2.4e-3 relative, so compare with rtol 5e-3 there" +} diff --git a/examples/transmon_cross_hamiltonian_inverse.json b/examples/transmon_cross_hamiltonian_inverse.json new file mode 100644 index 0000000000000000000000000000000000000000..072888072006f32500167735ff97b111acf543f2 --- /dev/null +++ b/examples/transmon_cross_hamiltonian_inverse.json @@ -0,0 +1,48 @@ +{ + "request": { + "inputs": { + "qubit_frequency_GHz": 4.85, + "anharmonicity_MHz": -205.0 + }, + "options": { + "include_scaled_outputs": false + } + }, + "response": { + "model_id": "transmon_cross_hamiltonian_inverse", + "family": "keras_tabular", + "revision": "26f2e04eb09ccd816e1c39ca7aa90a88bd737171", + "outputs": { + "predictions": [ + { + "design_options.connection_pads.readout.claw_length": 0.00011072495544794947, + "design_options.connection_pads.readout.ground_spacing": 4.571595582092414e-06, + "design_options.cross_length": 0.0002005973074119538 + } + ] + }, + "metadata": { + "input_order": [ + "qubit_frequency_GHz", + "anharmonicity_MHz" + ], + "output_order": [ + "design_options.connection_pads.readout.claw_length", + "design_options.connection_pads.readout.ground_spacing", + "design_options.cross_length" + ], + "input_units": { + "qubit_frequency_GHz": "GHz", + "anharmonicity_MHz": "MHz" + }, + "output_units": { + "design_options.connection_pads.readout.claw_length": "m", + "design_options.connection_pads.readout.ground_spacing": "m", + "design_options.cross_length": "m" + }, + "num_predictions": 1 + } + }, + "rtol": 1e-05, + "note": "the stored sample response of the model's inference_manifest.json" +} \ No newline at end of file diff --git a/registry.yaml b/registry.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dd97a02b01e2e55bae7a155030ed19ef505f3285 --- /dev/null +++ b/registry.yaml @@ -0,0 +1,149 @@ +# Generated by build.py from deploy/squadds_ml_api/registry.yaml (weights.from_manifest expanded). +version: 1 +models: + transmon_cross_hamiltonian_inverse: + family: keras_tabular + adapter: squadds_ml_api.adapters.keras_tabular:Adapter + display_name: TransmonCross Hamiltonian to Geometry + description: Inverse model that predicts TransmonCross geometry parameters from target Hamiltonian values. + tags: + - inverse-design + - transmon + - hamiltonian + visibility: public + weights: + repo_id: SQuADDS/transmon-cross-hamiltonian-inverse + revision: 26f2e04eb09ccd816e1c39ca7aa90a88bd737171 + files: + - path: inference_manifest.json + sha256: 093d984b6e9372ba1f601742a68cfa3f222be9ac7ff3f756be3b87a4acf433fb + - path: model/best_inverse_model_surrogate_defined_loss.keras + sha256: 20442b08a83b9d8cba43f5fe4594d04566184b0d4ed399a80b2106ff4f4bda30 + - path: X_names + sha256: 6eff9d4082d11593ca562b1bb1edb582c1f2033bbee28b6fd65d84c523af4bad + - path: y_columns.npy + sha256: b0ac62e1f9f61d878633cb24cdc9ae9c942dacb7c12cc521b0d8f23bafcc3755 + - path: scalers/scaler_X_qubit_frequency_GHz.save + sha256: de2428fcc998fcb6108969fe7d7746e7dcece44b6aeaff2e4c5bcbf91e50f5fc + - path: scalers/scaler_X_anharmonicity_MHz.save + sha256: 0386abd75ab411717739b1091a19d510da081038c29e0063685b0cb774fe47d9 + - path: scalers/scaler_y_design_options.connection_pads.readout.claw_length_one_hot_encoding.save + sha256: 9576bc4393c987ebf765612df6bb6f0ad3c93de5e5ffcf01c14d5bdf804cd892 + - path: scalers/scaler_y_design_options.connection_pads.readout.ground_spacing_one_hot_encoding.save + sha256: a38fcfcd1c4ef4b0ed7814dced91a110ee9033da8d5ebb319c14859e9ff786c2 + - path: scalers/scaler_y_design_options.cross_length_one_hot_encoding.save + sha256: 356bf37ad04ec755d37bc5a09f282bca015c3c8c542e050a110f4ede51a2c1b8 + config: + manifest: inference_manifest.json + limits: + max_batch_rows: 1000 + legacy_predict: true + warm: examples/transmon_cross_hamiltonian_inverse.json + example: examples/transmon_cross_hamiltonian_inverse.json + transmon_cross_cap_matrix_inverse: + display_name: TransmonCross Cap Matrix to Geometry + description: Inverse model that predicts TransmonCross geometry parameters from cap matrix targets. + tags: + - inverse-design + - transmon + - cap-matrix + visibility: hidden + status: missing_model_artifact + status_detail: 'No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras' + legacy_predict: true + coupler_ncap_cap_matrix_inverse: + display_name: NCap Coupler Cap Matrix to Geometry + description: Inverse model that predicts NCap coupler geometry from cap matrix targets. + tags: + - inverse-design + - coupler + - cap-matrix + visibility: hidden + status: missing_model_artifact + status_detail: 'No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras' + legacy_predict: true + cavity_claw_route_meander_inverse: + display_name: Cavity Claw RouteMeander Targets to Geometry + description: Inverse model that predicts cavity claw RouteMeander geometry from target cavity frequency and kappa. + tags: + - inverse-design + - cavity + - readout + visibility: hidden + status: missing_model_artifact + status_detail: 'No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate.keras, model/best_keras_model_model2_surrogate.keras' + legacy_predict: true + planar_capacitance_flagship: + family: planar_capacitance + adapter: squadds.ml.capacitance.serving:Adapter + display_name: Planar capacitance, flagship (Accurate) + description: GDS layout in, full Maxwell capacitance matrix out (fF, ground first, nets never merged). + tags: + - capacitance + - gds + - graph-neural-network + visibility: hidden + weights: + repo_id: SQuADDS/PlanarCapacitance-flagship + revision: bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc + files: + - path: accurate/acc_v2m_sf_s0.pt + sha256: cc69c5818f5028c26177159b88239116520abbb290743d6a6c091657e8dbf1c5 + - path: accurate/acc_v2m_sf_s1.pt + sha256: 2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57 + - path: accurate/acc_v2m_sf_s2.pt + sha256: d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed + source: squadds/ml/capacitance/manifest.json#models.flagship + config: + model: flagship + threads: 2 + limits: + max_upload_mb: 20 + max_conductors: 70 + numbers: + error_39_new_layouts: + median_pct: 1.05 + mae_fF: 0.132 + rmse_fF: 0.188 + median_time_s: 1.1 + source: 39 generated layouts (rings with a neighbour, 3 or 4 conductors) that no part of the model saw in training; median time on two CPUs of an Intel Xeon E5-2640 v4 cluster node, not on this Space + warm: examples/interdigital.gds + example: examples/planar_capacitance_flagship.json + planar_capacitance_fast: + family: planar_capacitance + adapter: squadds.ml.capacitance.serving:Adapter + display_name: Planar capacitance, fast + description: GDS layout in, full Maxwell capacitance matrix out, without a field solve. For quick screening of the trained component families only. + tags: + - capacitance + - gds + - graph-neural-network + visibility: hidden + weights: + repo_id: SQuADDS/PlanarCapacitance-flagship + revision: bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc + files: + - path: fast/acc_v1_s0.pt + sha256: 9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba + - path: fast/acc_v1_s1.pt + sha256: f1ad2ca065dd650ccabcad73a3c6ad2ac1042f4f68bb828893bbdecc47411ffe + - path: fast/acc_v1_s2.pt + sha256: 8cbada211724df5cc05a7b4fdd232607de047b248a43993d3844bd68ff8060c4 + - path: fast/sall_all_s0.pt + sha256: 132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac + source: squadds/ml/capacitance/manifest.json#models.fast + config: + model: fast + threads: 2 + limits: + max_upload_mb: 20 + max_conductors: 70 + numbers: + error_39_new_layouts: + median_pct: 3.175 + mae_fF: 0.583 + rmse_fF: 0.824 + median_time_s: 0.24 + source: 39 generated layouts (rings with a neighbour, 3 or 4 conductors) that no part of the model saw in training; median time on two CPUs of an Intel Xeon E5-2640 v4 cluster node, not on this Space + warm: examples/interdigital.gds + example: examples/planar_capacitance_fast.json diff --git a/requirements.txt b/requirements.txt index d0f1e3c209b178ca94a3b67079a60011f8e2782a..cf6c3b6677a2d16c78c791e3dc55cc7fa7bc90e3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,23 @@ +--extra-index-url https://download.pytorch.org/whl/cpu +# serving fastapi==0.115.12 uvicorn[standard]==0.34.0 +python-multipart==0.0.20 +pydantic>=2 +pyyaml +huggingface_hub +httpx==0.28.1 +# planar_capacitance (squadds[ml], vendored under src/) +torch==2.8.0 numpy==1.26.4 -joblib==1.4.2 -scikit-learn==1.6.1 +scipy +shapely>=2.0 +gdstk==1.0.2 +pandas +numba==0.68.0 +llvmlite==0.50.0 +threadpoolctl +# keras_tabular (Keras 3 on the torch backend, KERAS_BACKEND=torch; scikit-learn pinned to the version that pickled the scalers) keras==3.11.3 -tensorflow-cpu==2.19.0 +scikit-learn==1.6.1 +joblib==1.4.2 diff --git a/squadds_ml_api/__init__.py b/squadds_ml_api/__init__.py index 5f546ad8a7e5dfcbd1ad8ecbb1631222dc993c6f..6b89fb7ff5b53c8c46bce32ab60d9285e9dd6bc9 100644 --- a/squadds_ml_api/__init__.py +++ b/squadds_ml_api/__init__.py @@ -1,2 +1 @@ -"""Runtime package for the SQuADDS ML Hugging Face Space.""" - +"""SQuADDS ML API: one registry-driven FastAPI app for every SQuADDS model.""" diff --git a/squadds_ml_api/adapters/__init__.py b/squadds_ml_api/adapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/squadds_ml_api/adapters/base.py b/squadds_ml_api/adapters/base.py new file mode 100644 index 0000000000000000000000000000000000000000..bdcd31af3b4773ee810b722eaedb7f23318c4b08 --- /dev/null +++ b/squadds_ml_api/adapters/base.py @@ -0,0 +1,18 @@ +"""The adapter protocol (duck-typed; tests/test_registry.py enforces it). + +class Adapter: + input_kind: "json" | "file" json: inputs is an object (or a list when batch = True); file: one uploaded file + inputs + InputModel: pydantic model request schema of `inputs` (drives /docs, validation and the tool schema) + OptionsModel: pydantic model optional, schema of `options` + batch: bool optional, inputs may be a list of objects + + def __init__(self, model_id, root, config, limits) root = verified local weights + def describe(self) -> dict merged into GET /v1/models/{id} + def predict(self, inputs, file=None, options=None) -> {"outputs": {...}, "metadata": {...}, "timing_s": {...}} + def warm(self, example: Path) -> None optional + +predict validates its own raw inputs: pydantic.ValidationError -> 422, ValueError -> 400, a ValueError with +`too_large = True` -> 413, anything else -> 500. +""" + +REQUIRED = ("input_kind", "describe", "predict") diff --git a/squadds_ml_api/adapters/keras_tabular.py b/squadds_ml_api/adapters/keras_tabular.py new file mode 100644 index 0000000000000000000000000000000000000000..e6d8e27ea8532d218e67a0fe92d3e5918a8884b9 --- /dev/null +++ b/squadds_ml_api/adapters/keras_tabular.py @@ -0,0 +1,121 @@ +"""Tabular Keras models with joblib scalers (ML_qubit_design): JSON parameters in, JSON parameters out.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path + +import joblib +import numpy as np +from pydantic import BaseModel, ConfigDict, Field, create_model + +os.environ.setdefault("KERAS_BACKEND", "torch") + + +class Options(BaseModel): + include_scaled_outputs: bool = Field( + default=False, description="Include raw scaled model outputs alongside inverse-transformed values." + ) + + +class TooLarge(ValueError): + too_large = True + + +def _read_names(path: Path, fmt: str) -> list[str]: + if fmt == "text_lines": + return [line.strip() for line in path.read_text().splitlines() if line.strip()] + if fmt == "csv_header": + return [item.strip() for item in path.read_text().splitlines()[0].split(",") if item.strip()] + if fmt == "npy": + return [str(item) for item in np.load(path, allow_pickle=True).tolist()] + raise ValueError(f"Unsupported name file format: {fmt}") + + +class Adapter: + input_kind = "json" + batch = True + OptionsModel = Options + + def __init__(self, model_id: str, root: Path, config: dict, limits: dict): + import keras + + root = Path(root) + m = json.loads((root / config.get("manifest", "inference_manifest.json")).read_text()) + self.model_id = model_id + self.input_names = _read_names(root / m["input_names_path"], m["input_names_format"]) + self.output_names = _read_names(root / m["output_names_path"], m["output_names_format"]) + self.input_units = m.get("input_units", {}) + self.output_units = m.get("output_units", {}) + self.output_index = int(m.get("prediction_output_index", 0)) + self.model = keras.models.load_model(root / m["model_path"], compile=False) + xp, yp = m.get("x_scaler_pattern"), m.get("y_scaler_pattern") + self.x_scalers = [joblib.load(root / xp.format(name=n)) for n in self.input_names] if xp else None + self.y_scalers = [joblib.load(root / yp.format(name=n)) for n in self.output_names] if yp else None + self.max_rows = int(limits.get("max_batch_rows", 1000)) + self.backend = f"keras {keras.__version__} ({keras.backend.backend()})" + fields = { + f"x{i}": (float, Field(..., alias=n, description=f"{n} ({self.input_units[n]})" if n in self.input_units else n)) + for i, n in enumerate(self.input_names) + } + self.InputModel = create_model(f"{model_id}_inputs", __config__=ConfigDict(extra="forbid"), **fields) + + def describe(self) -> dict: + return { + "input_order": self.input_names, + "output_order": self.output_names, + "input_units": self.input_units, + "output_units": self.output_units, + "runtime": self.backend, + } + + def _rows(self, inputs) -> list[dict]: + rows = inputs if isinstance(inputs, list) else [inputs] + if len(rows) > self.max_rows: + raise TooLarge(f"batch of {len(rows)} rows; this server takes at most {self.max_rows}") + out = [] + for index, row in enumerate(rows): + if not isinstance(row, dict): + raise ValueError(f"Each input row must be an object, got {type(row).__name__} at index {index}.") + missing = [n for n in self.input_names if n not in row] + extras = [n for n in row if n not in self.input_names] + if missing or extras: + raise ValueError( + f"Model '{self.model_id}' expects inputs {self.input_names}. " + f"Missing: {missing or 'none'}. Extra: {extras or 'none'}." + ) + try: + out.append({n: float(row[n]) for n in self.input_names}) + except (TypeError, ValueError) as exc: + raise ValueError(f"Input values must be numbers: {exc}") from exc + return out + + def predict(self, inputs, file: bytes | None = None, options: dict | None = None) -> dict: + opts = Options.model_validate(options or {}) + rows = self._rows(inputs) + X = np.array([[r[n] for n in self.input_names] for r in rows], dtype=np.float64) + if self.x_scalers: + X = np.column_stack([s.transform(X[:, [j]])[:, 0] for j, s in enumerate(self.x_scalers)]) + raw = self.model.predict(X.astype(np.float32), verbose=0) + scaled = np.asarray(raw[self.output_index] if isinstance(raw, list) else raw) + Y = np.asarray(scaled, dtype=np.float32).copy() + if self.y_scalers: + for j, s in enumerate(self.y_scalers): + Y[:, j] = s.inverse_transform(Y[:, j].reshape(-1, 1)).reshape(-1) + outputs = {"predictions": [{n: float(Y[i, j]) for j, n in enumerate(self.output_names)} for i in range(len(Y))]} + if opts.include_scaled_outputs: + outputs["scaled_predictions"] = [ + {n: float(scaled[i, j]) for j, n in enumerate(self.output_names)} for i in range(len(scaled)) + ] + metadata = { + "input_order": self.input_names, + "output_order": self.output_names, + "input_units": self.input_units, + "output_units": self.output_units, + "num_predictions": len(outputs["predictions"]), + } + return {"outputs": outputs, "metadata": metadata} + + def warm(self, example: Path) -> None: + self.predict(json.loads(Path(example).read_text())["request"]["inputs"]) diff --git a/squadds_ml_api/api.py b/squadds_ml_api/api.py index 477322e657e0d12dad4b3f8d36735b11bf30350a..fde9480fdbefed2d1a60454bcc73fde8bbdc1295 100644 --- a/squadds_ml_api/api.py +++ b/squadds_ml_api/api.py @@ -1,61 +1,419 @@ +"""FastAPI factory: the /v1 routes, the legacy routes of the original Space, errors, limits, queue and cache.""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import json +import logging +import os +import threading +import time +from collections import OrderedDict +from contextlib import asynccontextmanager from pathlib import Path -from fastapi import FastAPI, HTTPException +import pydantic +from fastapi import FastAPI, HTTPException, Request +from fastapi.exception_handlers import request_validation_exception_handler +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.concurrency import run_in_threadpool + +from .auth import Gate, bearer +from .registry import Model, Registry +from .schemas import ApiError, PredictionRequest, PredictResponse + +log = logging.getLogger("squadds_ml_api") +SERVICE = "SQuADDS ML API" +MB = 2**20 + + +class Runner: + """One prediction at a time; at most `depth` requests in flight (running + waiting), the next one gets 429.""" + + def __init__(self, depth: int): + self.lock = threading.Lock() + self.slots = threading.BoundedSemaphore(depth) + + +class Cache: + def __init__(self, size: int = 64): + self.size, self.data, self.lock = size, OrderedDict(), threading.Lock() + + def get(self, k): + with self.lock: + if k in self.data: + self.data.move_to_end(k) + return self.data[k] + return None + + def put(self, k, v): + with self.lock: + self.data[k] = v + while len(self.data) > self.size: + self.data.popitem(last=False) + + +class RateLimiter: + """Token bucket per client IP: `per_minute` requests, refilled continuously (0 disables it).""" -from .registry import BundleConfigError, ModelRegistry, RequestValidationError -from .schemas import PredictionRequest + def __init__(self, per_minute: int): + self.rate, self.buckets, self.lock = per_minute, {}, threading.Lock() + def allow(self, ip: str) -> bool: + if self.rate <= 0: + return True + now = time.monotonic() + with self.lock: + tokens, last = self.buckets.get(ip, (float(self.rate), now)) + tokens = min(float(self.rate), tokens + (now - last) * self.rate / 60.0) + ok = tokens >= 1.0 + self.buckets[ip] = (tokens - 1.0 if ok else tokens, now) + if len(self.buckets) > 10000: + self.buckets.clear() + return ok -def create_app(bundle_root: Path) -> FastAPI: - registry = ModelRegistry(bundle_root) + +def client_ip(request: Request) -> str: + fwd = request.headers.get("x-forwarded-for") + return fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "?") + + +PREDICT_OPENAPI = { + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "inputs": {"description": "The model's inputs (see GET /v1/models/{model_id}/schema); file " + "models take the file as inputs.file_base64"}, + "options": {"type": "object"}, + }, + "required": ["inputs"], + } + }, + "multipart/form-data": { + "schema": { + "type": "object", + "properties": { + "file": {"type": "string", "format": "binary"}, + "inputs": {"type": "string", "description": "JSON of the other input fields"}, + "options": {"type": "string", "description": "JSON of the options"}, + }, + "required": ["file"], + } + }, + }, + } +} + + +def create_app(root: Path, registry_file: Path | None = None, load: bool = True) -> FastAPI: + root = Path(root) + reg = Registry(root, registry_file or os.environ.get("SQUADDS_ML_API_REGISTRY")) + gate = Gate(os.environ.get("SQUADDS_ML_API_ORG", "SQuADDS")) + depth = int(os.environ.get("SQUADDS_ML_API_QUEUE", "8")) + runner = Runner(depth) + cache = Cache(int(os.environ.get("SQUADDS_ML_API_CACHE", "64"))) + limiter = RateLimiter(int(os.environ.get("SQUADDS_ML_API_RATE_PER_MIN", "60"))) + built = root / "IMAGE_BUILT_AT" + build_info = { + "squadds_commit": reg.lock_info.get("squadds", {}).get("commit"), + "squadds_dirty": reg.lock_info.get("squadds", {}).get("dirty"), + "registry_sha256": reg.sha256, + "image_built_at": built.read_text().strip() if built.exists() else None, + } + + @asynccontextmanager + async def lifespan(_app): + if load: + reg.start(exit_on_failure=os.environ.get("SQUADDS_ML_API_EXIT_ON_LOAD_FAILURE") == "1") + yield app = FastAPI( - title="SQuADDS ML Inference API", - version="0.1.0", - description=( - "HTTP API for running inference against ML models trained in " - "ML_qubit_design and packaged for the SQuADDS Hugging Face Space." - ), + title=SERVICE, + version="2.0.0", + description="HTTP API for the machine-learning models of SQuADDS. Every model is an entry of the registry; " + "`/v1` is the API, and the original routes `/health`, `/models` and `/predict` are kept unchanged.", + lifespan=lifespan, ) + app.state.registry, app.state.cache, app.state.runner = reg, cache, runner + + @app.exception_handler(ApiError) + async def _api_error(_request: Request, exc: ApiError): + return JSONResponse(exc.body(), status_code=exc.status, headers=exc.headers) + + @app.exception_handler(RequestValidationError) + async def _validation(request: Request, exc: RequestValidationError): + if request.url.path.startswith("/v1"): + err = ApiError(422, "validation_error", "the request does not match the schema", + request.path_params.get("model_id"), details=jsonable(exc.errors())) + return JSONResponse(err.body(), status_code=422) + return await request_validation_exception_handler(request, exc) + + def member(request: Request) -> bool | None: + tok = bearer(request.headers) + if tok is None: + return None + try: + return gate.is_member(tok) + except Exception as exc: # noqa: BLE001 + raise ApiError(503, "loading", f"could not verify the token with Hugging Face: {exc}", + headers={"Retry-After": "30"}) from exc + + def visible(m: Model, who: bool | None) -> bool: + return m.status == "ready" and (m.visibility == "public" or (m.visibility == "gated" and who is True)) + + def access(model_id: str, request: Request, need_ready: bool = True) -> Model: + m = reg.models.get(model_id) + if m is None or m.visibility == "hidden" or m.status != "ready": + raise ApiError(404, "unknown_model", f"unknown model '{model_id}'", model_id) + if m.visibility == "gated": + who = member(request) + if who is None: + raise ApiError(401, "auth_required", "this model needs 'Authorization: Bearer ' " + "of a member of the SQuADDS organization", model_id) + if not who: + raise ApiError(403, "forbidden", "this token does not belong to a member of the SQuADDS organization", + model_id) + if need_ready and m.state != "ready": + if m.state == "failed": + raise ApiError(500, "inference_error", f"model failed to load: {m.error}", model_id) + raise ApiError(503, "loading", "the model is still loading", model_id, headers={"Retry-After": "10"}) + return m + + def entry(m: Model) -> dict: + s = m.spec + return { + "id": m.id, + "family": s.get("family"), + "display_name": s["display_name"], + "description": s["description"], + "tags": s.get("tags", []), + "input_kind": getattr(m.adapter_cls, "input_kind", None), + "visibility": m.visibility, + "revision": m.revision, + "status": m.state, + } + + def rate(request: Request) -> None: + if not limiter.allow(client_ip(request)): + raise ApiError(429, "rate_limited", f"more than {limiter.rate} requests per minute from this address", + headers={"Retry-After": "60"}) + + def run_predict(m: Model, inputs, options, data: bytes | None) -> dict: + t0 = time.perf_counter() + key = hashlib.sha256(json.dumps([m.id, m.revision, inputs, options], sort_keys=True, default=str).encode() + + (data or b"")).hexdigest() + + def hit(v): + return {**v, "timing_s": {"total": round(time.perf_counter() - t0, 6), "queue": 0.0}, "cached": True} + + v = cache.get(key) + if v is not None: + return hit(v) + if not runner.slots.acquire(blocking=False): + raise ApiError(429, "busy", "the server is busy; retry later", m.id, headers={"Retry-After": "30"}) + try: + tq = time.perf_counter() + with runner.lock: + queue_s = time.perf_counter() - tq + v = cache.get(key) + if v is not None: + return hit(v) + try: + out = m.adapter.predict(inputs, file=data, options=options) + except pydantic.ValidationError as exc: + raise ApiError(422, "validation_error", "the inputs do not match the schema", m.id, + details=jsonable(exc.errors())) from exc + except ValueError as exc: + if getattr(exc, "too_large", False): + raise ApiError(413, "too_large", str(exc), m.id) from exc + raise ApiError(400, "invalid_input", str(exc), m.id) from exc + except Exception as exc: # noqa: BLE001 + log.exception("inference error in %s", m.id) + raise ApiError(500, "inference_error", f"{type(exc).__name__}: {exc}", m.id) from exc + finally: + runner.slots.release() + v = { + "model_id": m.id, + "family": m.spec["family"], + "revision": m.revision, + "outputs": out["outputs"], + "metadata": out.get("metadata", {}), + } + cache.put(key, v) + timing = {"total": round(time.perf_counter() - t0, 6), "queue": round(queue_s, 6)} + timing.update({k: round(x, 6) if isinstance(x, float) else x for k, x in (out.get("timing_s") or {}).items()}) + return {**v, "timing_s": timing, "cached": False} + + def request_schema(m: Model) -> dict: + ad = m.adapter + ins = ad.InputModel.model_json_schema() + if getattr(ad, "batch", False): + items = {"type": "array", "items": ins, "maxItems": m.limits.get("max_batch_rows", 1000)} + ins = {"anyOf": [ins, items]} + opts = ad.OptionsModel.model_json_schema() if getattr(ad, "OptionsModel", None) else {"type": "object"} + return {"type": "object", "properties": {"inputs": ins, "options": opts}, "required": ["inputs"]} + + # ---------- root and /v1 ---------- @app.get("/") - def root() -> dict: + def root_route() -> dict: return { - "service": "SQuADDS ML Inference API", + "service": SERVICE, "docs": "/docs", + "openapi": "/openapi.json", + "v1": {"health": "/v1/health", "models": "/v1/models", "model": "/v1/models/{model_id}", + "schema": "/v1/models/{model_id}/schema", "predict": "/v1/models/{model_id}/predict"}, "models_endpoint": "/models", "predict_endpoint": "/predict", } - @app.get("/health") + @app.get("/v1/health", tags=["v1"]) + def health_v1(request: Request) -> dict: + who = member(request) + return {"status": "ok", "models": {m.id: m.state for m in reg.models.values() if visible(m, who)}, + "build": build_info} + + @app.get("/v1/models", tags=["v1"]) + def models_v1(request: Request) -> dict: + who = member(request) + return {"models": [entry(m) for m in reg.models.values() if visible(m, who)]} + + @app.get("/v1/models/{model_id}", tags=["v1"]) + def model_v1(model_id: str, request: Request) -> dict: + m = access(model_id, request) + out = {**entry(m), **m.adapter.describe(), "limits": {**m.limits, "queue_depth": depth}} + if m.spec.get("numbers"): + out["numbers"] = m.spec["numbers"] + if m.spec.get("example"): + ex = json.loads((root / m.spec["example"]).read_text()) + out["example"] = {k: ex[k] for k in ("file", "request") if k in ex} + return out + + @app.get("/v1/models/{model_id}/schema", tags=["v1"]) + def schema_v1(model_id: str, request: Request, format: str = "json") -> dict: + m = access(model_id, request) + req = request_schema(m) + if format == "tool": + how = (" Send a GDS file as inputs.file_base64." if m.adapter.input_kind == "file" else "") + return {"name": f"squadds_{m.id}", + "description": f"{m.spec['display_name']}: {m.spec['description']} POST the input to " + f"/v1/models/{m.id}/predict.{how}", + "input_schema": req} + if format != "json": + raise ApiError(400, "invalid_input", "format must be 'json' or 'tool'", model_id) + return {"request": req, "response": PredictResponse.model_json_schema()} + + @app.post("/v1/models/{model_id}/predict", tags=["v1"], response_model=PredictResponse, + openapi_extra=PREDICT_OPENAPI) + async def predict_v1(model_id: str, request: Request): + rate(request) + m = access(model_id, request) + file_model = m.adapter.input_kind == "file" + max_bytes = int(float(m.limits.get("max_upload_mb", 20)) * MB) + length = request.headers.get("content-length") + if length and length.isdigit() and int(length) > max_bytes * 1.4 + MB: + raise ApiError(413, "too_large", f"request larger than {max_bytes // MB} MB", model_id) + data = None + if request.headers.get("content-type", "").startswith("multipart/form-data"): + if not file_model: + raise ApiError(400, "invalid_input", "this model takes a JSON body", model_id) + form = await request.form() + up = form.get("file") + if up is None or isinstance(up, str): + raise ApiError(400, "invalid_input", "multipart requests need the file in the field 'file'", model_id) + data = await up.read(max_bytes + 1) + try: + inputs = json.loads(form.get("inputs") or "{}") + options = json.loads(form.get("options") or "{}") + except json.JSONDecodeError as exc: + raise ApiError(400, "invalid_input", f"the fields 'inputs' and 'options' must be JSON: {exc}", + model_id) from exc + else: + try: + body = await request.json() + except (json.JSONDecodeError, UnicodeDecodeError) as exc: + raise ApiError(400, "invalid_input", "the body must be JSON (or multipart for file models)", + model_id) from exc + if not isinstance(body, dict) or "inputs" not in body: + raise ApiError(422, "validation_error", "the body must be an object with 'inputs'", model_id) + inputs, options = body["inputs"], body.get("options") or {} + if file_model and isinstance(inputs, dict) and inputs.get("file_base64") is not None: + inputs = dict(inputs) + try: + data = base64.b64decode(inputs.pop("file_base64"), validate=True) + except (binascii.Error, ValueError, TypeError) as exc: + raise ApiError(400, "invalid_input", "inputs.file_base64 is not valid base64", model_id) from exc + if not isinstance(options, dict): + raise ApiError(422, "validation_error", "options must be an object", model_id) + if data is not None and len(data) > max_bytes: + raise ApiError(413, "too_large", f"file larger than {max_bytes // MB} MB", model_id) + return await run_in_threadpool(run_predict, m, inputs, options, data) + + # ---------- legacy routes of the original Space (same shapes, {"detail": ...} errors) ---------- + + def legacy_models() -> list[Model]: + return [m for m in reg.models.values() if m.spec.get("legacy_predict")] + + def legacy_ready() -> list[str]: + return [m.id for m in legacy_models() if m.status == "ready" and m.visibility == "public"] + + @app.get("/health", tags=["legacy"]) def health() -> dict: - return { - "status": "ok", - "available_models": registry.available_model_ids(), - "bundle_root": str(bundle_root), - } + return {"status": "ok", "available_models": legacy_ready(), "bundle_root": str(root)} - @app.get("/models") + @app.get("/models", tags=["legacy"]) def list_models() -> dict: - return {"models": registry.describe_models()} + out = [] + for m in legacy_models(): + d = m.adapter.describe() if m.adapter is not None else {} + out.append({ + "id": m.id, + "display_name": m.spec["display_name"], + "description": m.spec["description"], + "status": m.status, + "status_detail": m.spec.get("status_detail", ""), + "input_units": d.get("input_units", {}), + "output_units": d.get("output_units", {}), + "tags": m.spec.get("tags", []), + }) + return {"models": out} - @app.post("/predict") - def predict(request: PredictionRequest) -> dict: - try: - payload = registry.predict( - model_id=request.model_id, - inputs=request.inputs, - include_scaled_outputs=request.options.include_scaled_outputs, - ) - except RequestValidationError as exc: - raise HTTPException(status_code=400, detail=str(exc)) from exc - except BundleConfigError as exc: - raise HTTPException(status_code=500, detail=str(exc)) from exc - except Exception as exc: + @app.post("/predict", tags=["legacy"]) + def predict(body: PredictionRequest, request: Request) -> dict: + if not limiter.allow(client_ip(request)): + raise HTTPException(429, f"more than {limiter.rate} requests per minute from this address", + headers={"Retry-After": "60"}) + m = reg.models.get(body.model_id) + if m is None or not m.spec.get("legacy_predict") or (m.visibility != "public" and m.status == "ready"): + raise HTTPException(400, f"Unknown model_id '{body.model_id}'. Available models: {legacy_ready()}.") + if m.status != "ready": raise HTTPException( - status_code=500, - detail=f"Unexpected inference error for model '{request.model_id}': {exc}", - ) from exc - return payload + 400, f"Model '{m.id}' is not deployable in this bundle: {m.spec.get('status_detail') or m.status}.") + if m.state != "ready": + raise HTTPException(503 if m.state != "failed" else 500, f"Model '{m.id}' is {m.state}.") + try: + v = run_predict(m, body.inputs, body.options.model_dump(), None) + except ApiError as exc: + if exc.status in (400, 413, 422): + raise HTTPException(400, exc.message) from exc + if exc.status == 429: + raise HTTPException(429, exc.message, headers=exc.headers) from exc + raise HTTPException(500, f"Unexpected inference error for model '{m.id}': {exc.message}") from exc + out = {"model_id": m.id, "display_name": m.spec["display_name"], "predictions": v["outputs"]["predictions"], + "metadata": v["metadata"]} + if "scaled_predictions" in v["outputs"]: + out["scaled_predictions"] = v["outputs"]["scaled_predictions"] + return out return app + + +def jsonable(x): + return json.loads(json.dumps(x, default=str)) diff --git a/squadds_ml_api/auth.py b/squadds_ml_api/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..2ad989076d4f5eb65aaa2d56546a8f93f38c813b --- /dev/null +++ b/squadds_ml_api/auth.py @@ -0,0 +1,39 @@ +"""Gate for gated models: a Hugging Face token of a member of the organization (whoami, cached for ten minutes).""" + +from __future__ import annotations + +import hashlib +import threading +import time + + +def bearer(headers) -> str | None: + h = headers.get("authorization", "") + return h[7:].strip() or None if h.lower().startswith("bearer ") else None + + +class Gate: + def __init__(self, org: str = "SQuADDS", ttl_s: float = 600): + self.org, self.ttl_s = org, ttl_s + self._memo: dict = {} + self._lock = threading.Lock() + + def is_member(self, token: str) -> bool: + from huggingface_hub import whoami + from huggingface_hub.errors import HfHubHTTPError + + k = hashlib.sha256(token.encode()).hexdigest() + with self._lock: + hit = self._memo.get(k) + if hit and time.monotonic() - hit[1] < self.ttl_s: + return hit[0] + try: + info = whoami(token=token) + ok = any(o.get("name") == self.org for o in info.get("orgs", [])) + except HfHubHTTPError as exc: + if getattr(exc.response, "status_code", None) not in (401, 403): + raise + ok = False + with self._lock: + self._memo[k] = (ok, time.monotonic()) + return ok diff --git a/squadds_ml_api/registry.py b/squadds_ml_api/registry.py index e1646dca1350b1073524c434ec3e49d73f31635f..1d0e0fa114346f2a232ff30a422850d48eaa72f1 100644 --- a/squadds_ml_api/registry.py +++ b/squadds_ml_api/registry.py @@ -1,237 +1,179 @@ +"""registry.yaml: schema checks, adapter imports, weight fetching (pinned revision, sha256) and the loaded adapters.""" + from __future__ import annotations +import hashlib +import importlib import json +import logging +import re +import threading from dataclasses import dataclass, field from pathlib import Path -from typing import Any, Dict, Iterable, List - -import joblib -import numpy as np -from keras.models import load_model - - -class BundleConfigError(RuntimeError): - """Raised when the deployed bundle is missing required files or config.""" - - -class RequestValidationError(ValueError): - """Raised when an inference request does not match the model contract.""" - -@dataclass(frozen=True) -class ModelSpec: +import yaml + +from .adapters.base import REQUIRED + +log = logging.getLogger("squadds_ml_api") +VISIBILITY = ("public", "gated", "hidden") +HEX40 = re.compile(r"^[0-9a-f]{40}$") +HEX64 = re.compile(r"^[0-9a-f]{64}$") + + +class RegistryError(RuntimeError): + pass + + +def import_object(path: str): + module, _, name = path.partition(":") + return getattr(importlib.import_module(module), name) + + +def sha256_file(p: Path) -> str: + h = hashlib.sha256() + with open(p, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def validate(data: dict, root: Path | None = None) -> None: + """Raise RegistryError on the first violation of the registry rules.""" + if not isinstance(data, dict) or data.get("version") != 1 or not isinstance(data.get("models"), dict): + raise RegistryError("registry must have version: 1 and a models mapping") + for mid, e in data["models"].items(): + where = f"registry model {mid!r}" + if e.get("visibility") not in VISIBILITY: + raise RegistryError(f"{where}: visibility must be one of {VISIBILITY}") + for k in ("display_name", "description"): + if not e.get(k): + raise RegistryError(f"{where}: {k} missing") + if e.get("status", "ready") != "ready": + continue + for k in ("family", "adapter", "weights"): + if not e.get(k): + raise RegistryError(f"{where}: {k} missing") + w = e["weights"] + if "from_manifest" in w: + raise RegistryError(f"{where}: weights.from_manifest is not expanded (run build.py)") + if not HEX40.match(str(w.get("revision", ""))): + raise RegistryError(f"{where}: weights.revision must be a full 40-character commit hash") + if not w.get("repo_id") or not w.get("files"): + raise RegistryError(f"{where}: weights need repo_id and files") + for f in w["files"]: + if not f.get("path") or not HEX64.match(str(f.get("sha256", ""))): + raise RegistryError(f"{where}: every weights file needs a path and a sha256") + if root is not None: + for k in ("example", "warm"): + if e.get(k) and not (root / e[k]).exists(): + raise RegistryError(f"{where}: {k} file {e[k]} missing") + + +def fetch(weights: dict) -> Path: + """Download every file at the pinned revision, check its sha256 and return the local snapshot root.""" + from huggingface_hub import hf_hub_download + + root = None + for f in weights["files"]: + p = Path(hf_hub_download(repo_id=weights["repo_id"], filename=f["path"], revision=weights["revision"])) + got = sha256_file(p) + if got != f["sha256"]: + raise RegistryError(f"{weights['repo_id']}/{f['path']}: sha256 {got[:12]} differs from the registry") + r = p + for _ in Path(f["path"]).parts: + r = r.parent + if root is not None and r != root: + raise RegistryError(f"files of {weights['repo_id']} resolved to different snapshots") + root = r + return root + + +@dataclass +class Model: id: str - display_name: str - description: str - artifact_dir: str - model_path: str - input_names_path: str - input_names_format: str - output_names_path: str - output_names_format: str - x_scaler_pattern: str | None = None - y_scaler_pattern: str | None = None - input_units: Dict[str, str] = field(default_factory=dict) - output_units: Dict[str, str] = field(default_factory=dict) - sample_request: Dict[str, Any] | None = None - sample_response: Dict[str, Any] | None = None - status: str = "ready" - status_detail: str = "" - tags: List[str] = field(default_factory=list) - prediction_output_index: int = 0 - - @classmethod - def from_dict(cls, payload: Dict[str, Any]) -> "ModelSpec": - return cls(**payload) - - -def _read_names(path: Path, fmt: str) -> List[str]: - if fmt == "text_lines": - return [line.strip() for line in path.read_text().splitlines() if line.strip()] - if fmt == "csv_header": - first_line = path.read_text().splitlines()[0] - return [item.strip() for item in first_line.split(",") if item.strip()] - if fmt == "npy": - values = np.load(path, allow_pickle=True) - return [str(item) for item in values.tolist()] - raise BundleConfigError(f"Unsupported name file format: {fmt}") - - -class EndpointModel: - def __init__(self, bundle_root: Path, spec: ModelSpec): - self.bundle_root = bundle_root - self.spec = spec - self.artifact_root = bundle_root / spec.artifact_dir - - if not self.artifact_root.exists(): - raise BundleConfigError( - f"Artifact directory for model '{spec.id}' is missing: {self.artifact_root}" - ) - - self.input_names = _read_names( - self.artifact_root / spec.input_names_path, spec.input_names_format - ) - self.output_names = _read_names( - self.artifact_root / spec.output_names_path, spec.output_names_format - ) - - model_file = self.artifact_root / spec.model_path - if not model_file.exists(): - raise BundleConfigError( - f"Model file for '{spec.id}' is missing: {model_file}" - ) - self.model = load_model(model_file, compile=False) - - def _load_scaler(self, pattern: str, name: str): - scaler_path = self.artifact_root / pattern.format(name=name) - if not scaler_path.exists(): - raise BundleConfigError( - f"Required scaler for '{self.spec.id}' is missing: {scaler_path}" - ) - return joblib.load(scaler_path) - - def _normalize_rows(self, inputs: Dict[str, float] | List[Dict[str, float]]) -> List[Dict[str, float]]: - rows = inputs if isinstance(inputs, list) else [inputs] - normalized: List[Dict[str, float]] = [] - for index, row in enumerate(rows): - if not isinstance(row, dict): - raise RequestValidationError( - f"Each input row must be an object, got {type(row).__name__} at index {index}." - ) - - missing = [name for name in self.input_names if name not in row] - extras = [name for name in row if name not in self.input_names] - if missing or extras: - raise RequestValidationError( - f"Model '{self.spec.id}' expects inputs {self.input_names}. " - f"Missing: {missing or 'none'}. Extra: {extras or 'none'}." - ) - - normalized.append({name: float(row[name]) for name in self.input_names}) - return normalized - - def _scale_inputs(self, rows: List[Dict[str, float]]) -> np.ndarray: - matrix = np.zeros((len(rows), len(self.input_names)), dtype=np.float32) - for row_idx, row in enumerate(rows): - for col_idx, name in enumerate(self.input_names): - value = row[name] - if self.spec.x_scaler_pattern: - scaler = self._load_scaler(self.spec.x_scaler_pattern, name) - scaled = scaler.transform([[value]])[0][0] - else: - scaled = value - matrix[row_idx, col_idx] = float(scaled) - return matrix - - def _unscale_outputs(self, scaled_outputs: np.ndarray) -> np.ndarray: - matrix = np.asarray(scaled_outputs, dtype=np.float32).copy() - if not self.spec.y_scaler_pattern: - return matrix - - for col_idx, name in enumerate(self.output_names): - scaler = self._load_scaler(self.spec.y_scaler_pattern, name) - column = matrix[:, col_idx].reshape(-1, 1) - matrix[:, col_idx] = scaler.inverse_transform(column).reshape(-1) - return matrix - - def predict( - self, - inputs: Dict[str, float] | List[Dict[str, float]], - include_scaled_outputs: bool = False, - ) -> Dict[str, Any]: - rows = self._normalize_rows(inputs) - scaled_inputs = self._scale_inputs(rows) - raw_predictions = self.model.predict(scaled_inputs, verbose=0) - - if isinstance(raw_predictions, list): - scaled_outputs = np.asarray(raw_predictions[self.spec.prediction_output_index]) - else: - scaled_outputs = np.asarray(raw_predictions) - - unscaled_outputs = self._unscale_outputs(scaled_outputs) - - predictions = [ - { - output_name: float(unscaled_outputs[row_idx, col_idx]) - for col_idx, output_name in enumerate(self.output_names) - } - for row_idx in range(unscaled_outputs.shape[0]) - ] - - response: Dict[str, Any] = { - "model_id": self.spec.id, - "display_name": self.spec.display_name, - "predictions": predictions, - "metadata": { - "input_order": self.input_names, - "output_order": self.output_names, - "input_units": self.spec.input_units, - "output_units": self.spec.output_units, - "num_predictions": len(predictions), - }, - } - if include_scaled_outputs: - response["scaled_predictions"] = [ - { - output_name: float(scaled_outputs[row_idx, col_idx]) - for col_idx, output_name in enumerate(self.output_names) - } - for row_idx in range(scaled_outputs.shape[0]) - ] - return response - - -class ModelRegistry: - def __init__(self, bundle_root: Path): - self.bundle_root = Path(bundle_root) - manifest_path = self.bundle_root / "deployment_manifest.json" - if not manifest_path.exists(): - raise BundleConfigError( - f"Deployment manifest is missing from bundle: {manifest_path}" - ) - - payload = json.loads(manifest_path.read_text()) - self.bundle_info = payload.get("space", {}) - self.specs = [ModelSpec.from_dict(item) for item in payload.get("models", [])] - self._models: Dict[str, EndpointModel] = {} - - def available_model_ids(self) -> List[str]: - return [spec.id for spec in self.specs if spec.status == "ready"] - - def describe_models(self) -> List[Dict[str, Any]]: - return [ - { - "id": spec.id, - "display_name": spec.display_name, - "description": spec.description, - "status": spec.status, - "status_detail": spec.status_detail, - "input_units": spec.input_units, - "output_units": spec.output_units, - "tags": spec.tags, - } - for spec in self.specs - ] - - def _get_model(self, model_id: str) -> EndpointModel: - spec = next((item for item in self.specs if item.id == model_id), None) - if spec is None: - raise RequestValidationError( - f"Unknown model_id '{model_id}'. Available models: {self.available_model_ids()}." - ) - if spec.status != "ready": - raise RequestValidationError( - f"Model '{model_id}' is not deployable in this bundle: {spec.status_detail or spec.status}." - ) - if model_id not in self._models: - self._models[model_id] = EndpointModel(self.bundle_root, spec) - return self._models[model_id] - - def predict( - self, - model_id: str, - inputs: Dict[str, float] | List[Dict[str, float]], - include_scaled_outputs: bool = False, - ) -> Dict[str, Any]: - model = self._get_model(model_id) - return model.predict(inputs=inputs, include_scaled_outputs=include_scaled_outputs) + spec: dict + adapter_cls: type | None = None + adapter: object | None = None + state: str = "pending" + error: str | None = None + + @property + def visibility(self) -> str: + return self.spec["visibility"] + + @property + def status(self) -> str: + return self.spec.get("status", "ready") + + @property + def revision(self) -> str | None: + return (self.spec.get("weights") or {}).get("revision") + + @property + def limits(self) -> dict: + return self.spec.get("limits") or {} + + +@dataclass +class Registry: + root: Path + path: Path | None = None + models: dict = field(default_factory=dict) + fetched: list = field(default_factory=list) + lock_info: dict = field(default_factory=dict) + + def __post_init__(self): + self.root = Path(self.root) + self.path = Path(self.path or self.root / "registry.yaml") + self.raw = self.path.read_bytes() + data = yaml.safe_load(self.raw) + validate(data, self.root) + for mid, e in data["models"].items(): + m = Model(mid, e) + if e.get("adapter"): + m.adapter_cls = import_object(e["adapter"]) + missing = [k for k in REQUIRED if not hasattr(m.adapter_cls, k)] + if missing: + raise RegistryError(f"adapter of {mid!r} lacks {missing}") + self.models[mid] = m + lock = self.root / "bundle.lock.json" + self.lock_info = json.loads(lock.read_text()) if lock.exists() else {} + self.sha256 = hashlib.sha256(self.raw).hexdigest() + + def servable(self) -> list[Model]: + return [m for m in self.models.values() if m.visibility != "hidden" and m.status == "ready"] + + def load_all(self) -> list[Model]: + """Fetch, verify, instantiate and warm every public and gated model; hidden ones are never touched.""" + failed = [] + for m in self.servable(): + m.state = "loading" + for m in self.servable(): + try: + root = fetch(m.spec["weights"]) + self.fetched.append(m.spec["weights"]["repo_id"]) + m.adapter = m.adapter_cls(m.id, root, m.spec.get("config") or {}, m.limits) + if m.spec.get("warm") and hasattr(m.adapter, "warm"): + m.adapter.warm(self.root / m.spec["warm"]) + log.info("warm prediction done for %s", m.id) + m.state = "ready" + except Exception as exc: # noqa: BLE001 + m.state, m.error = "failed", f"{type(exc).__name__}: {exc}" + log.error("model %s failed to load: %s", m.id, m.error) + failed.append(m) + return failed + + def start(self, exit_on_failure: bool = False) -> threading.Thread: + def run(): + failed = self.load_all() + if failed and exit_on_failure: + import os + + os._exit(1) + + for m in self.servable(): + m.state = "loading" + t = threading.Thread(target=run, name="registry-load", daemon=True) + t.start() + return t diff --git a/squadds_ml_api/schemas.py b/squadds_ml_api/schemas.py index 2be458dfc8a7c859e6429ef73215f6cf23a9c65e..0e8cfdb54a9242f41d1e2f9ff731a2f8dafe4261 100644 --- a/squadds_ml_api/schemas.py +++ b/squadds_ml_api/schemas.py @@ -1,10 +1,35 @@ from __future__ import annotations -from typing import Dict, List, Union +from typing import Any, Dict, List, Union from pydantic import BaseModel, Field +class ApiError(Exception): + def __init__(self, status: int, code: str, message: str, model_id: str | None = None, headers: dict | None = None, + details: Any = None): + super().__init__(message) + self.status, self.code, self.message, self.model_id, self.headers, self.details = ( + status, code, message, model_id, headers or {}, details) + + def body(self) -> dict: + err = {"code": self.code, "message": self.message, "model_id": self.model_id} + if self.details is not None: + err["details"] = self.details + return {"error": err} + + +class PredictResponse(BaseModel): + model_id: str + family: str + revision: str + outputs: Dict[str, Any] = Field(description="Family specific outputs") + metadata: Dict[str, Any] = Field(description="Family specific metadata: names, units, orders, checks") + timing_s: Dict[str, Any] = Field(description="Seconds: total, queue and family specific steps") + cached: bool + + +# Legacy request of the original Space (POST /predict), unchanged. class PredictionOptions(BaseModel): include_scaled_outputs: bool = Field( default=False, diff --git a/src/squadds/__init__.py b/src/squadds/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0b8bca044fec0547b34edf3ba5bffd9abecad3 --- /dev/null +++ b/src/squadds/__init__.py @@ -0,0 +1 @@ +"""Inference-only subset of SQuADDS (squadds.ml).""" diff --git a/src/squadds/ml/__init__.py b/src/squadds/ml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4495e5083778b472d28c7ab0021aa6d6724cc97f --- /dev/null +++ b/src/squadds/ml/__init__.py @@ -0,0 +1,34 @@ +"""Machine-learning models for SQuADDS (optional extra: ``pip install squadds[ml]``). + +Submodules import torch / gdstk / numba lazily, so ``import squadds`` works without the extra. +""" + +from __future__ import annotations + +import importlib.util + +ML_REQUIREMENTS = ("torch", "gdstk", "numba", "threadpoolctl", "shapely", "yaml") + + +def missing_ml_dependencies() -> list[str]: + return [m for m in ML_REQUIREMENTS if importlib.util.find_spec(m) is None] + + +def require_ml() -> None: + """Raise ImportError naming the missing packages when the ``[ml]`` extra is not installed.""" + missing = missing_ml_dependencies() + if missing: + raise ImportError( + f"squadds.ml needs the optional ML dependencies (missing: {', '.join(missing)}). " + "Install them with: pip install 'squadds[ml]'" + ) + + +def __getattr__(name): + if name == "capacitance": + require_ml() + return importlib.import_module("squadds.ml.capacitance") + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +__all__ = ["ML_REQUIREMENTS", "missing_ml_dependencies", "require_ml"] diff --git a/src/squadds/ml/capacitance/__init__.py b/src/squadds/ml/capacitance/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97397002b6a6a59d54c7e3913c8e7072193932dc --- /dev/null +++ b/src/squadds/ml/capacitance/__init__.py @@ -0,0 +1,55 @@ +"""Planar capacitance models: GDS layout -> full N x N Maxwell capacitance matrix (fF, ground first). + + from squadds.ml.capacitance import CapacitancePredictor, load_model + res = CapacitancePredictor(load_model("flagship")).predict("chip.gds") + res.names, res.matrix_fF, res.to_sim_results() + +Models: ``flagship`` (the default) and ``fast`` (both trained on all data), and ``paper`` (the paper's model, TRAIN split +only; use it for benchmarks). Physics priors: ``coarse_physics_prior`` and ``optimized_physics_prior``. +""" + +from __future__ import annotations + +import importlib + +from .. import require_ml + +_EXPORTS = { + "CapacitancePredictor": "predictor", + "CapacitanceResult": "result", + "CapacitanceModel": "models", + "ModelIntegrityError": "models", + "list_models": "models", + "load_model": "models", + "PriorResult": "priors", + "coarse_physics_prior": "priors", + "optimized_physics_prior": "priors", + "prepare_layout": "_runtime", + "inspect_layout": "_runtime", + "MLSimulator": "bridge", + "TrainConfig": "train", + "fit": "train", + "fit_in_family": "train", + "retrain_collective": "train", + "build_shards": "training_data", + "resolve_dataset_names": "training_data", + "score": "benchmark", + "PlanarCapacitanceDB": "dataset", + "label_qc": "qc", + "validate_capacitance_contribution": "contribute", + "contribute_capacitance": "contribute", + "validate_model": "contribute", + "contribute_model": "contribute", +} +_NO_ML_NEEDED = {"PlanarCapacitanceDB", "label_qc"} + + +def __getattr__(name): + if name in _EXPORTS: + if name not in _NO_ML_NEEDED: + require_ml() + return getattr(importlib.import_module(f"{__name__}.{_EXPORTS[name]}"), name) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +__all__ = sorted(_EXPORTS) diff --git a/src/squadds/ml/capacitance/_core/SOURCES.json b/src/squadds/ml/capacitance/_core/SOURCES.json new file mode 100644 index 0000000000000000000000000000000000000000..f100ee747520d5b698ce48cfa53198d17073d6cc --- /dev/null +++ b/src/squadds/ml/capacitance/_core/SOURCES.json @@ -0,0 +1,379 @@ +{ + "note": "Frozen inference stage of the tl-squadds Spaces (deploy/geomgnn/src/geomgnn, deploy/tlsq_infer/src/tlsq_infer/layout.py), namespaced under squadds.ml.capacitance._core. Edits: import lines; the network builder moved to squadds.ml.capacitance.network (verbatim from pilot_p2.build_model); spawned worker pools start through _spawn.boot (same worker functions and arguments, the squadds package __init__ is not executed in the workers). Numerics unchanged.", + "tl_squadds_repo": "github.com/shanto268/tl-squadds (private), branch paper-backup", + "files": { + "api.py": { + "source": "deploy/geomgnn/src/geomgnn/api.py", + "source_sha256": "7905e805e48377dc36f60241e042a597bb7afb5491b5f4c89d8a0a5b28ff975f", + "sha256": "3e6cb02f180b6c2138511fbcb628daa07e0529f80b31ee4add26111738179549", + "rewrites": [ + { + "pattern": "module=r\"geomgnn\\\\\\.fastprior_pkg\"", + "replacement": "module=r\"squadds\\.ml\\.capacitance\\._core\\.fastprior_pkg\"", + "count": 1 + }, + { + "pattern": "from tlsq_infer\\.layout import prepare", + "replacement": "from .layout import prepare", + "count": 1 + } + ] + }, + "paper.py": { + "source": "deploy/geomgnn/src/geomgnn/paper.py", + "source_sha256": "fc951f350f5d0bc4de0b1cf93209a4dfa7770fde2661330c6bde6c92c9f6a31f", + "sha256": "3d1f95dcf06d005a6bf0ff3d545fead3c18bed4db9a1629469ef2d2375644a8c", + "rewrites": [ + { + "pattern": "from tlsq_infer\\.layout import prepare", + "replacement": "from .layout import prepare", + "count": 1 + } + ] + }, + "flagship.py": { + "source": "deploy/geomgnn/src/geomgnn/flagship.py", + "source_sha256": "f86bf5bab11dbedbdd1e07626b172dae4d4f53ed356f47e26da18bd008df448b", + "sha256": "f86bf5bab11dbedbdd1e07626b172dae4d4f53ed356f47e26da18bd008df448b", + "rewrites": [] + }, + "infer.py": { + "source": "deploy/geomgnn/src/geomgnn/infer.py", + "source_sha256": "cee37e8ed6f229363801b9a8118aea9dfb4ce5f476e6e2d8ff13cfa734e87b96", + "sha256": "ed77e7456af217a4ee438068c4ee1c7b07a9e1768424156e64a40e5480bc9376", + "rewrites": [ + { + "pattern": "from \\.pilot_p2 import build_model", + "replacement": "from ..network import build_model", + "count": 1 + } + ] + }, + "x1_core.py": { + "source": "deploy/geomgnn/src/geomgnn/x1_core.py", + "source_sha256": "0a4be5ec3b8819bdc6d6314775c7f8acf46f4a54569d975011726ec1912c5100", + "sha256": "0a4be5ec3b8819bdc6d6314775c7f8acf46f4a54569d975011726ec1912c5100", + "rewrites": [] + }, + "farfield.py": { + "source": "deploy/geomgnn/src/geomgnn/farfield.py", + "source_sha256": "6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836", + "sha256": "6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836", + "rewrites": [] + }, + "fastprior_pkg.py": { + "source": "deploy/geomgnn/src/geomgnn/fastprior_pkg.py", + "source_sha256": "956f2b62c308ec1561bbc033716b52c24dc63a916b9373cc44090eb6514e5dde", + "sha256": "26a2c03786bacf85fd48005968d53e8661b66cd3367b66dd86adac12a2bd3e92", + "rewrites": [ + { + "pattern": "from geomgnn\\._tlsq", + "replacement": "from squadds.ml.capacitance._core._tlsq", + "count": 1 + }, + { + "pattern": "\"geomgnn\\._tlsq\\.embed\\.fastprior\" in sys\\.modules", + "replacement": "\"squadds.ml.capacitance._core._tlsq.embed.fastprior\" in sys.modules", + "count": 1 + } + ] + }, + "priorv2.py": { + "source": "deploy/geomgnn/src/geomgnn/priorv2.py", + "source_sha256": "64057e92e37a04a0231dfdc34df52a20542f88c2b2a3e8c2cc00a32d9ec1d21b", + "sha256": "64057e92e37a04a0231dfdc34df52a20542f88c2b2a3e8c2cc00a32d9ec1d21b", + "rewrites": [] + }, + "rejtail_fv.py": { + "source": "deploy/geomgnn/src/geomgnn/rejtail_fv.py", + "source_sha256": "35659484c44f1c84e3767b33979bb78b972f03d64c05810d81635ee4409ce3ba", + "sha256": "35659484c44f1c84e3767b33979bb78b972f03d64c05810d81635ee4409ce3ba", + "rewrites": [] + }, + "learned_prior.py": { + "source": "deploy/geomgnn/src/geomgnn/learned_prior.py", + "source_sha256": "de9d1351dfbaa93ef1be18ed18f3a3628ba2b477955f58c58db80758163156dc", + "sha256": "de9d1351dfbaa93ef1be18ed18f3a3628ba2b477955f58c58db80758163156dc", + "rewrites": [] + }, + "lp_surrogate.py": { + "source": "deploy/geomgnn/src/geomgnn/lp_surrogate.py", + "source_sha256": "55804c9349a2ca4a74f3ae821a19c4637dbaf16d25b65c8ee70c746b767d2707", + "sha256": "55804c9349a2ca4a74f3ae821a19c4637dbaf16d25b65c8ee70c746b767d2707", + "rewrites": [] + }, + "levelpar.py": { + "source": "deploy/geomgnn/src/geomgnn/levelpar.py", + "source_sha256": "69e7d1199e9642cfef399d5ee6737f4bcd768ef863372065d60082d81398eb22", + "sha256": "e929ecf97131d45533b2bd3b2bec4645935df1fbb13824375f55d10f5dc36729", + "rewrites": [ + { + "pattern": "from geomgnn\\._tlsq", + "replacement": "from squadds.ml.capacitance._core._tlsq", + "count": 2 + }, + { + "pattern": "from geomgnn import", + "replacement": "from squadds.ml.capacitance._core import", + "count": 3 + }, + { + "pattern": "here = os\\.path\\.dirname\\(os\\.path\\.dirname\\(os\\.path\\.abspath\\(__file__\\)\\)\\)", + "replacement": "here = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 4)) # the directory holding squadds", + "count": 1 + }, + { + "pattern": "ex = ProcessPoolExecutor\\(n, mp_context=get_context\\(\\\"spawn\\\"\\), initializer=_init,\\n\\s*initargs=\\(\\[here\\], A._STATE\\[\\\"prior_impl\\\"\\], A._STATE\\[\\\"pr\\\"\\], threads\\)\\)", + "replacement": "from ._spawn import boot\n ini, args = boot(_init, [here], A._STATE[\"prior_impl\"], A._STATE[\"pr\"], threads)\n ex = ProcessPoolExecutor(n, mp_context=get_context(\"spawn\"), initializer=ini, initargs=args)", + "count": 1 + } + ] + }, + "overlap.py": { + "source": "deploy/geomgnn/src/geomgnn/overlap.py", + "source_sha256": "30cb40ead9146603b9c0a32cebc7d79bc762b79c1526b95be3b6deefc3419753", + "sha256": "cf226d87b9a099ca5543d6f4dd4f3706f8fc13bb6d0f2bbb1e76fc52b3630cfb", + "rewrites": [ + { + "pattern": "from geomgnn\\._tlsq", + "replacement": "from squadds.ml.capacitance._core._tlsq", + "count": 5 + }, + { + "pattern": "here = os\\.path\\.dirname\\(os\\.path\\.dirname\\(os\\.path\\.abspath\\(__file__\\)\\)\\)", + "replacement": "here = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 4)) # the directory holding squadds", + "count": 1 + }, + { + "pattern": "ex = ProcessPoolExecutor\\(1, mp_context=get_context\\(\\\"spawn\\\"\\), initializer=_init, initargs=\\(threads, \\[here\\]\\)\\)", + "replacement": "from ._spawn import boot\n ini, args = boot(_init, threads, [here])\n ex = ProcessPoolExecutor(1, mp_context=get_context(\"spawn\"), initializer=ini, initargs=args)", + "count": 1 + } + ] + }, + "winpool.py": { + "source": "deploy/geomgnn/src/geomgnn/winpool.py", + "source_sha256": "c726a7c86737058660600f9f40276843add598f6245d586eb32e206a660f342f", + "sha256": "56e7142019e44e872c65ce283ad9afbd27f4a664cb53c1656295062c4a1d657a", + "rewrites": [ + { + "pattern": "from geomgnn\\._tlsq", + "replacement": "from squadds.ml.capacitance._core._tlsq", + "count": 2 + }, + { + "pattern": "from geomgnn import", + "replacement": "from squadds.ml.capacitance._core import", + "count": 1 + }, + { + "pattern": "here = os\\.path\\.dirname\\(os\\.path\\.dirname\\(os\\.path\\.abspath\\(__file__\\)\\)\\)", + "replacement": "here = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 4)) # the directory holding squadds", + "count": 1 + }, + { + "pattern": "super\\(\\).__init__\\(max_workers, mp_context=get_context\\(\\\"spawn\\\"\\), initializer=_init,\\n\\s*initargs=\\(\\[here\\], A._STATE\\[\\\"prior_impl\\\"\\], A._STATE\\[\\\"pr\\\"\\], state\\)\\)", + "replacement": "from ._spawn import boot\n ini, args = boot(_init, [here], A._STATE[\"prior_impl\"], A._STATE[\"pr\"], state)\n super().__init__(max_workers, mp_context=get_context(\"spawn\"), initializer=ini, initargs=args)", + "count": 1 + } + ] + }, + "fastmom.py": { + "source": "deploy/geomgnn/src/geomgnn/fastmom.py", + "source_sha256": "7447474366ddae654100467125c84ddb7fb503a1c9d4fd1264825bde164de951", + "sha256": "7447474366ddae654100467125c84ddb7fb503a1c9d4fd1264825bde164de951", + "rewrites": [] + }, + "schema_p2d.json": { + "source": "deploy/geomgnn/src/geomgnn/schema_p2d.json", + "source_sha256": "17eba5f7b5d01668019df9301507133dfe4e38689acbde5256f3ade2107df8e9", + "sha256": "17eba5f7b5d01668019df9301507133dfe4e38689acbde5256f3ade2107df8e9", + "rewrites": [] + }, + "_tlsq/__init__.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/__init__.py", + "source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/__init__.py", + "source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "rewrites": [] + } + }, + "_tlsq/embed/__init__.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/__init__.py", + "source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/__init__.py", + "source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "rewrites": [] + } + }, + "_tlsq/embed/fastprior.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/fastprior.py", + "source_sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1", + "sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/fastprior.py", + "source_sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1", + "sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1", + "rewrites": [] + } + }, + "_tlsq/embed/fastprior_loc.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/fastprior_loc.py", + "source_sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b", + "sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/fastprior_loc.py", + "source_sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b", + "sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b", + "rewrites": [] + } + }, + "_tlsq/embed/proxy.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/proxy.py", + "source_sha256": "78d8dffd2fac75632a91ebee151247afe4157716ffb11e624e6b2932c618c86e", + "sha256": "78d8dffd2fac75632a91ebee151247afe4157716ffb11e624e6b2932c618c86e", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/proxy.py", + "source_sha256": "78d8dffd2fac75632a91ebee151247afe4157716ffb11e624e6b2932c618c86e", + "sha256": "78d8dffd2fac75632a91ebee151247afe4157716ffb11e624e6b2932c618c86e", + "rewrites": [] + } + }, + "_tlsq/geometry.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/geometry.py", + "source_sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b", + "sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/geometry.py", + "source_sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b", + "sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b", + "rewrites": [] + } + }, + "_tlsq/uge/__init__.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/__init__.py", + "source_sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22", + "sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/__init__.py", + "source_sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22", + "sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22", + "rewrites": [] + } + }, + "_tlsq/uge/blocks.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/blocks.py", + "source_sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c", + "sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/blocks.py", + "source_sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c", + "sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c", + "rewrites": [], + "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).", + "frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/blocks.py", + "frozen_stage_sha256": "c58313f167f7df0ef0de6b321ab6b7214a661aef10b461e2bf90a60999fb4632" + } + }, + "_tlsq/uge/graph.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/graph.py", + "source_sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa", + "sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/graph.py", + "source_sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa", + "sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa", + "rewrites": [], + "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).", + "frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/graph.py", + "frozen_stage_sha256": "aeb8c58cf6c1d2169eab8a58fba362634d7489f3414f260a9fc55a02048217ee" + } + }, + "_tlsq/uge/localtok.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/localtok.py", + "source_sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd", + "sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/localtok.py", + "source_sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd", + "sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd", + "rewrites": [], + "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).", + "frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/localtok.py", + "frozen_stage_sha256": "8b47bd454353709a29ad996243d0f8b4b0d94991ee43715145af41a912dd9319" + } + }, + "_tlsq/uge/nnk.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/nnk.py", + "source_sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84", + "sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/nnk.py", + "source_sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84", + "sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84", + "rewrites": [], + "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)." + } + }, + "_tlsq/uge/proxies.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/proxies.py", + "source_sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38", + "sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/proxies.py", + "source_sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38", + "sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38", + "rewrites": [] + } + }, + "_tlsq/uge/scene.py": { + "source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/scene.py", + "source_sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285", + "sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285", + "rewrites": [], + "upstream": { + "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/scene.py", + "source_sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285", + "sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285", + "rewrites": [] + } + }, + "layout.py": { + "source": "deploy/tlsq_infer/src/tlsq_infer/layout.py", + "source_sha256": "2f88d25f7984f470a7fc361e54bf054e98c682d667383a6991c59760a08c7113", + "sha256": "3cd0601522056ee82630d2ea829c14bca0e172e7a24a6391433af9b8038fbe95", + "rewrites": [ + { + "pattern": "from \\._vendor\\.scene import _valid", + "replacement": "from ._tlsq.uge.scene import _valid", + "count": 1 + } + ] + }, + "../network.py": { + "source": "deploy/geomgnn/src/geomgnn/pilot_p2.py", + "source_sha256": "c38264c43ab342ba64338892edf23c8abd4b88503b99bce322431efb7db77c77", + "extract": "build_model (lines 89-117), verbatim", + "extract_sha256": "e64a9482d41562c8de1c795a25f63ff21c3db1e19b8e8e60dc585feda2c2fbfa", + "upstream": "scripts/geomfast/pilot_p2.py (frozen geomfast stage)" + } + } +} diff --git a/src/squadds/ml/capacitance/_core/__init__.py b/src/squadds/ml/capacitance/_core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a2138ab6e778c425da52957ced9b0b49924284b --- /dev/null +++ b/src/squadds/ml/capacitance/_core/__init__.py @@ -0,0 +1,6 @@ +"""Frozen inference stage of the planar-capacitance models, ported from tl-squadds (geomgnn 0.1.0); see SOURCES.json. + +Do not edit the numerics here: every file records the sha256 of its tl-squadds source and the import lines rewritten. +""" + +__version__ = "0.1.0" diff --git a/src/squadds/ml/capacitance/_core/_spawn.py b/src/squadds/ml/capacitance/_core/_spawn.py new file mode 100644 index 0000000000000000000000000000000000000000..57bedd55a544bee004a2daa4c491cc99fbba292a --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_spawn.py @@ -0,0 +1,40 @@ +"""Start spawned worker processes without executing ``squadds/__init__.py`` (which imports the database and analysis stack). + +``boot(fn, *args)`` returns ``(initializer, initargs)`` for a ``ProcessPoolExecutor``: the worker registers a bare ``squadds`` +package module, then imports ``fn`` by name and calls ``fn(*args)``; at exit it undoes the prior stack (quiet shutdown). The worker functions and their arguments are unchanged. +""" + +from __future__ import annotations + +import os +import pickle + +_PKG_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 3)) + +_CODE = """ +import importlib, pickle, sys, types +if "squadds" not in sys.modules: + _m = types.ModuleType("squadds") + _m.__path__ = [{pkg!r}] + sys.modules["squadds"] = _m +_f = getattr(importlib.import_module({mod!r}), {name!r}) +_f(*pickle.loads({blob!r})) + + +def _teardown(): + a = sys.modules.get("squadds.ml.capacitance._core.api") + if a is not None and a._STATE.get("stack") is not None: + try: + a._teardown() + except Exception: + pass + + +import atexit +atexit.register(_teardown) +""" + + +def boot(fn, *args) -> tuple: + code = _CODE.format(pkg=_PKG_DIR, mod=fn.__module__, name=fn.__name__, blob=pickle.dumps(args)) + return exec, (code, {}) diff --git a/src/squadds/ml/capacitance/_core/_tlsq/__init__.py b/src/squadds/ml/capacitance/_core/_tlsq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/squadds/ml/capacitance/_core/_tlsq/embed/__init__.py b/src/squadds/ml/capacitance/_core/_tlsq/embed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior.py b/src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior.py new file mode 100644 index 0000000000000000000000000000000000000000..bdc69d0e7732eba10adcfd261f33583c1b358082 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior.py @@ -0,0 +1,925 @@ +"""Local (windowed) MoM prior: PRIOR_SCHEME.md Part III prototype. + +The Maxwell entry C_ij is defined with every other conductor at 0 V, and a ground plane screens the field, so the +entries of a conductor are set by its neighbourhood. The layout is partitioned into windows (recursive bisection of +the conductor sites until the metal edge length inside each window fits a panel budget); a window models its core +conductors (whose matrix rows it provides), the halo conductors within R_g of the core as separate nets at 0 V, the +ground plane cropped by a margin around core + halo, and every farther conductor filled into the ground. Each window +is a strip-merged conductor-anchored mesh (the flagship mesh family, PRIOR_SCHEME.md Part II) solved densely with the +exact near field and one right-hand side per core conductor, optionally Richardson-extrapolated (h and 2 h). Windows +that are translation copies of one another are solved once (geometric hash). Cost: O(number of distinct windows) x +(a bounded dense solve), independent of the chip size; a layout that fits one window is one global solve. +Pairs never co-windowed (farther than R_g apart) are not predicted: NaN in C and True in far_mask. +""" + +from __future__ import annotations + +import hashlib +import time +from concurrent.futures import ProcessPoolExecutor +from multiprocessing import get_context + +import numpy as np +import shapely +from scipy.spatial import cKDTree + +from ..geometry import sample_boundary +from ..uge.blocks import _kratio +from . import proxy as P + +PANELS_PER_EDGE_H = 0.75 # merged panels per (um of metal edge / h), measured on grid_qubit_1 (18.6k at h = 2 um, 50 mm of edges) + + +def _valid(g): + g = shapely.make_valid(g) + parts = [p for p in getattr(g, "geoms", [g]) if p.geom_type in ("Polygon", "MultiPolygon")] + return shapely.union_all(parts) if parts else shapely.Polygon() + + +def gap_of(metals: list) -> float: + tree = shapely.STRtree(metals) + d = np.inf + for i, g in enumerate(metals): + j, dist = tree.query_nearest(g, return_distance=True, exclusive=True, all_matches=False) + if len(dist): + d = min(d, float(dist[0])) + return d + + +def within(geoms: list, targets: list, R: float) -> np.ndarray: + """Boolean (len(geoms),): geometry within distance R of any target (STRtree, O(n log n)).""" + out = np.zeros(len(geoms), bool) + if not targets or not geoms: + return out + tree = shapely.STRtree(geoms) + for t in targets: + out[tree.query(t, predicate="dwithin", distance=R)] = True + return out + + +def plan_windows(G, conds: list, h: float, R_g: float, margin: float, panel_budget: int, global_budget: int | None = None, + split_gain: float = 0.75, level_rings: tuple = ()) -> list: + """Windows (dicts: core, halo, box). One global window (every conductor in the core, no halo, no crop) when the + metal edge length of the whole layout fits global_budget panels; otherwise recursive bisection of the conductor + sites (bbox centres) until the estimated merged panel count of the window fits panel_budget. The estimate weights + the metal edge length by the grading level it will be meshed at (1, 1/2, 1/4, ... beyond each of level_rings um + from the core; ground edges beyond R_g of the members are filled and count 0), so the budget measures the core + content, not the fixed halo + margin overhead. Each split is snapped to the widest coordinate gap between sites in + the central half of the sorted order (cores follow the natural cell structure); a split whose child is not below + split_gain x the parent (a dense cluster) is not made and the window is solved whole (H-matrix above dense_max).""" + sites = np.array([[(b[0] + b[2]) / 2, (b[1] + b[3]) / 2] for b in shapely.bounds(np.array(conds, dtype=object))]) + per_panel = h / PANELS_PER_EDGE_H + all_idx = np.arange(len(conds)) + L_all = G.length + sum(c.length for c in conds) + if L_all <= (global_budget if global_budget is not None else panel_budget) * per_panel: + return [{"core": all_idx, "halo": np.zeros(0, int), "box": None, "n_core": len(conds), "n_halo": 0}] + out = [] + Gb = G.boundary + gtree = shapely.STRtree(list(getattr(Gb, "geoms", [Gb]))) + rings = list(level_rings) + [np.inf] + + def window_of(core): + halo = within(conds, [conds[i] for i in core], R_g) + halo[core] = False + halo = np.nonzero(halo)[0] + x0, y0, x1, y1 = shapely.union_all([conds[i] for i in np.concatenate([core, halo])]).bounds + box = (x0 - margin, y0 - margin, x1 + margin, y1 + margin) + return halo, box + + def est_panels(core, halo, box): + cg = shapely.union_all([conds[i] for i in core]) + members = shapely.union_all([conds[i] for i in np.concatenate([core, halo])]) + b = shapely.box(*box) + gl = shapely.union_all([gtree.geometries[k] for k in gtree.query(b)]) if len(gtree.geometries) else Gb + edges = shapely.union_all([shapely.intersection(gl, b).intersection(members.buffer(R_g)), members.boundary]) + L, prev, w = 0.0, None, 1.0 + for r in rings: + ring = cg.buffer(r) if np.isfinite(r) else b + if prev is not None: + ring = ring.difference(prev) + L += w * shapely.intersection(edges, ring).length + prev, w = (cg.buffer(r) if np.isfinite(r) else b), w / 2 + return L / per_panel + + def rec(idx, n_parent=None): + halo, box = window_of(idx) + n = est_panels(idx, halo, box) + if len(idx) == 1 or n <= panel_budget or (n_parent is not None and n > split_gain * n_parent): + out.append({"core": idx, "halo": halo, "box": box, "est_panels": n}) + return + s = sites[idx] + ax = int(np.argmax(s.max(0) - s.min(0))) + order = idx[np.argsort(s[:, ax], kind="stable")] + x = sites[order, ax] + lo = max(1, len(order) // 4) + hi = max(lo + 1, min(len(order), (3 * len(order)) // 4 + 1)) + gaps = x[lo:hi] - x[lo - 1:hi - 1] + m = lo + int(np.argmax(gaps)) + rec(order[:m], n), rec(order[m:], n) + + rec(all_idx) + for w in out: + w["n_core"], w["n_halo"] = len(w["core"]), len(w["halo"]) + return out + + +def window_metals(G, conds: list, w: dict, fill_um: float = 250.0, keep_um: float = 0.0) -> list: + """[ground, core..., halo...] of window w: ground = chip ground cropped to the box plus every farther conductor + inside the box as ground metal (0 V), whose etched surroundings within fill_um are filled in where they are more + than keep_um from any member (their edges leave the mesh; nothing changes within keep_um of a member).""" + members = np.concatenate([w["core"], w["halo"]]).astype(int) + if w["box"] is None: + return [G] + [conds[i] for i in members] + box = shapely.box(*w["box"]) + far = np.setdiff1d(np.nonzero(within(conds, [box], 0.0))[0], members) + Gw = shapely.intersection(G, box) + if len(far): + chip = shapely.box(*G.bounds) + farg = shapely.union_all([conds[i] for i in far]) + fill = shapely.intersection(shapely.intersection(chip.difference(G), farg.buffer(fill_um)), box) + fill = fill.difference(shapely.union_all([conds[i] for i in members]).buffer(keep_um)) + Gw = shapely.union_all([Gw, shapely.intersection(farg, box), fill]) + return [_valid(Gw)] + [conds[i] for i in members] + + +def anchored_cells_graded(metals: list, h_f: float, core, levels: tuple, grade: float = 2.0, majority: bool = False): + """`proxy.anchored_cells` with the finest panel graded by the distance to the core conductors: h_f within levels[0] + of `core`, 2 h_f up to levels[1], 4 h_f up to levels[2], ... (same lattice; with levels=() identical to the plain + mesh). Returns centres (n, 2), sizes (n, 2), owner (n,).""" + edges = shapely.union_all([g.boundary for g in metals]) + sig = metals[1:] if len(metals) > 1 else metals + ax, ay = shapely.union_all(sig).bounds[:2] + X0, Y0, X1, Y1 = shapely.union_all(metals).bounds + span = max(X1 - X0, Y1 - Y0) + K = max(0, int(np.ceil(np.log2(max(span / 16, h_f) / h_f)))) + h0 = h_f * 2**K + ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0)) + ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0)) + gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1)) + xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0) + gq = P._Geoms(list(metals) + [edges, core]) + lv = np.asarray(levels, float) + tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool) + out_c, out_h, out_o = [], [], [] + while len(xs): + boxes = shapely.box(xs, ys, xs + h, ys + h) + cov, hit, inn, pcs = P._cover(gq, boxes, h, tst, inn) + keep = cov.sum(0) > 1e-3 + xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep] + pcs = [p[keep] for p in pcs] + cx, cy = xs + h / 2, ys + h / 2 + full = cov.max(0) > 0.999 + if len(lv): + maybe = h <= h_f * 2 ** len(lv) * 1.0001 # cells that can be at their last level + hl = np.zeros(len(xs)) + if maybe.any(): + dc = P._distance(gq, len(metals) + 1, boxes[maybe]) + hl[maybe] = h_f * 2.0 ** np.searchsorted(lv, dc, side="right") + last = h <= hl * 1.0001 + else: + last = h <= h_f * 1.0001 + d = np.full(len(xs), np.inf) + far = full & ~last + d[far] = P._distance(gq, len(metals), boxes[far]) + leaf = full & (last | (h <= grade * d + 1e-12)) + out_c.append(np.stack([cx[leaf], cy[leaf]], 1)) + out_h.append(np.stack([h[leaf], h[leaf]], 1)) + out_o.append(cov[:, leaf].argmax(0)) + cut = last & ~leaf + if majority and cut.any(): + take = cut & (cov.max(0) >= 0.5) + out_c.append(np.stack([cx[take], cy[take]], 1)) + out_h.append(np.stack([h[take], h[take]], 1)) + out_o.append(cov[:, take].argmax(0)) + cut = cut & False + if cut.any(): + gs = gq.get() + for k, g in enumerate(gs[:len(metals)]): + shapely.prepare(g) + sel = np.nonzero(cut & (cov[k] > 1e-3))[0] + if not len(sel): + continue + pcs_k = pcs[k][sel] + bb = shapely.bounds(pcs_k) + cen = shapely.get_coordinates(shapely.centroid(pcs_k)) + inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1]) + if not inside.all(): + cen[~inside] = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside])) + out_c.append(cen) + out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6)) + out_o.append(np.full(len(sel), k)) + gq.put(gs) + split = ~leaf & ~last + hs = h[split] / 2 + xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs]) + ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs]) + h = np.concatenate([hs] * 4) + tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4) + return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o) + + +def strip_merge(c, wh, o, metals, h_f: float, lmax_mult: float = 16.0, grade: float = 1.0): + """`proxy.strip_merge` with the strip length bounded by lmax_mult x the panel's own lattice level (max(width across + the edge, h_f), so coarser regions get proportionally longer strips) and by grade x the distance to the nearest + polygon vertex (coarse square cells therefore merge into longer strips than in proxy.strip_merge).""" + lines, S, verts = P._segments(metals) + near = shapely.STRtree(lines).nearest(shapely.points(c)) + d = S[near, 1] - S[near, 0] + horiz = np.abs(d[:, 0]) >= np.abs(d[:, 1]) + dv, _ = P.cKDTree(verts).query(c, workers=-1) + allow = np.minimum(lmax_mult * np.maximum(wh.min(1), h_f), grade * dv) + out_c, out_wh, out_o = [], [], [] + for axis, mask in ((0, horiz), (1, ~horiz)): + if not mask.any(): + continue + idx = np.nonzero(mask)[0] + other = 1 - axis + key = np.stack([o[idx], np.round(c[idx, other], 4), np.round(wh[idx, other], 4)], 1) + order = np.lexsort([c[idx, axis], key[:, 2], key[:, 1], key[:, 0]]) + idx, key = idx[order], key[order] + same = np.all(key[1:] == key[:-1], 1) + lo, hi = c[idx, axis] - wh[idx, axis] / 2, c[idx, axis] + wh[idx, axis] / 2 + adjacent = same & (np.abs(hi[:-1] - lo[1:]) < 1e-6) + start = 0 + while start < len(idx): + end, length, cap = start, wh[idx[start], axis], allow[idx[start]] + while end + 1 < len(idx) and adjacent[end] and length + wh[idx[end + 1], axis] <= min(cap, allow[idx[end + 1]]): + end += 1 + length += wh[idx[end], axis] + cap = min(cap, allow[idx[end]]) + cc, ww = np.zeros(2), np.zeros(2) + cc[axis], cc[other] = 0.5 * (lo[start] + hi[end]), c[idx[start], other] + ww[axis], ww[other] = hi[end] - lo[start], wh[idx[start], other] + out_c.append(cc) + out_wh.append(ww) + out_o.append(o[idx[start]]) + start = end + 1 + return np.array(out_c), np.array(out_wh), np.array(out_o) + + +def solve_window_rows(metals: list, n_core: int, h: float, eps_r: float = 11.45, lmax_mult: float = 16.0, merge_grade: float = 1.0, + grade: float = 2.0, rich: bool = True, dense_max: int = 12000, levels: tuple = ()) -> tuple: + """Rows of the Maxwell matrix for the core conductors (metals[1:1+n_core]): (rows (n_core, len(metals)), info). + levels: distances (um) from the core beyond which the finest panel doubles (core-graded mesh); () = uniform.""" + info = {} + core = shapely.union_all(metals[1:1 + n_core]) + + def one(hh, tag, majority=False): + t = time.perf_counter() + raw = anchored_cells_graded(metals, hh, core, levels, grade, majority=majority) + c, wh, o = strip_merge(*raw, metals, hh, lmax_mult, merge_grade) + info[f"mesh_s_{tag}"], info[f"raw_{tag}"], info[f"panels_{tag}"] = time.perf_counter() - t, len(raw[0]), len(c) + info[f"share_{tag}"] = [float(np.mean(o == 0)), float(np.mean((o >= 1) & (o <= n_core))), float(np.mean(o > n_core))] + t = time.perf_counter() + B = (o[:, None] == np.arange(1, 1 + n_core)[None, :]).astype(float) + if len(c) <= dense_max: + A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) + info[f"assemble_s_{tag}"] = time.perf_counter() - t + t = time.perf_counter() + try: + Q = P._chol_solve(A, B) + except np.linalg.LinAlgError: # cut panels of different nets overlap: whole finest cells by majority (as the flagship) + if majority: + raise + del A + info[f"majority_{tag}"] = True + return one(hh, tag, majority=True) + info[f"solver_{tag}"] = "dense" + else: + H = P._HMatrix(c, wh, eps_r, P.HMAT["leaf"], P.HMAT["eta"], P.HMAT["eps"]) + info[f"assemble_s_{tag}"] = time.perf_counter() - t + t = time.perf_counter() + Xp, _, _ = H.pcg(B[H.perm], P.HMAT["tol"], P.HMAT["maxit"]) + Q = np.empty_like(Xp) + Q[H.perm] = Xp + info[f"solver_{tag}"] = "H-matrix PCG" + info[f"solve_s_{tag}"] = time.perf_counter() - t + return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) # (n_core, n_metals): charge on a with core k at 1 V + + Rf = one(h, "f") + if not rich: + return Rf, info + Rc = one(2 * h, "c") + return 2 * Rf - Rc, info + + +def canonical_hash(metals: list, n_core: int, h: float) -> str: + """Translation-invariant key of a window (lattice anchored to the signal bbox, coordinates rounded to 0.1 nm).""" + x0, y0 = shapely.union_all(metals[1:]).bounds[:2] + tr = [shapely.transform(g, lambda xy: np.round(xy - [x0, y0], 4)) for g in metals] + hsh = hashlib.sha1(f"{n_core}:{h:.9g}:".encode()) + for g in tr: + hsh.update(shapely.to_wkb(g)) + return hsh.hexdigest() + + +def _job(args): + wi, metals, n_core, h, kw = args + rows, info = solve_window_rows(metals, n_core, h, **kw) + return wi, rows, info + + +def local_prior(G, conds: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, rich: bool = True, panel_budget: int = 12000, + halo_gaps: float = 100.0, margin_gaps: float = 100.0, margin_min_um: float = 150.0, fill_um: float = 250.0, + lmax_mult: float = 16.0, merge_grade: float = 1.0, workers: int = 1, cache: bool = True, dense_max: int = 12000, + global_budget: int | None = None, level_gaps: tuple = ()) -> tuple: + """Local prior of a layout (ground G, conductors conds, never merged): (C (N+1, N+1) fF with NaN for far pairs, + far_mask, info). Finest panel h = gap / cells_per_gap; with rich=True the Richardson pair is (h, 2 h). Windows + are solved in parallel on `workers` processes.""" + t_all = time.perf_counter() + metals_all = [G] + list(conds) + gap = gap_of(metals_all) + h = gap / cells_per_gap + R_g, margin = halo_gaps * gap, max(margin_gaps * gap, margin_min_um) + t = time.perf_counter() + wins = plan_windows(G, conds, h, R_g, margin, panel_budget, global_budget, level_rings=tuple(float(g) * gap for g in level_gaps)) + t_plan = time.perf_counter() - t + t = time.perf_counter() + mats = [window_metals(G, conds, w, fill_um, keep_um=R_g) for w in wins] + keys = [canonical_hash(m, w["n_core"], h) if cache else str(i) for i, (m, w) in enumerate(zip(mats, wins))] + t_build = time.perf_counter() - t + uniq = {} + for i, k in enumerate(keys): + uniq.setdefault(k, i) + kw = dict(eps_r=eps_r, lmax_mult=lmax_mult, merge_grade=merge_grade, rich=rich, dense_max=dense_max, + levels=tuple(float(g) * gap for g in level_gaps)) + jobs = [(i, mats[i], wins[i]["n_core"], h, kw) for i in uniq.values()] + t = time.perf_counter() + if workers > 1 and len(jobs) > 1: + with ProcessPoolExecutor(workers, mp_context=get_context("fork")) as ex: + res = {wi: (rows, info) for wi, rows, info in ex.map(_job, jobs)} + else: + res = {wi: (rows, info) for wi, rows, info in map(_job, jobs)} + t_solve = time.perf_counter() - t + N = len(conds) + 1 + acc, cnt = np.zeros((N, N)), np.zeros((N, N)) + for i, w in enumerate(wins): + rows, _ = res[uniq[keys[i]]] + idx = np.concatenate([[0], w["core"] + 1, w["halo"] + 1]).astype(int) + for k, ci in enumerate(w["core"] + 1): + acc[ci, idx] += rows[k] + cnt[ci, idx] += 1 + C = np.full((N, N), np.nan) + have = cnt > 0 + C[have] = acc[have] / cnt[have] + # symmetrise: mean of the two estimates when both exist, the one available otherwise; ground row from the columns + S = np.where(have & have.T, 0.5 * (np.nan_to_num(C) + np.nan_to_num(C.T)), np.where(have, C, C.T)) + S[0, 0] = np.nan + far = ~(have | have.T) + np.fill_diagonal(far, False) + infos = [res[j][1] for j in uniq.values()] + info = {"n_windows": len(wins), "n_unique": len(uniq), "h_um": h, "min_gap_um": gap, "R_g_um": R_g, "margin_um": margin, + "panels_f": [i["panels_f"] for i in infos], "est_panels": [w.get("est_panels", 0) for w in wins], "raw_f": [i["raw_f"] for i in infos], + "panels_c": [i.get("panels_c", 0) for i in infos], "cores": [w["n_core"] for w in wins], "halos": [w["n_halo"] for w in wins], + "solvers": sorted({i["solver_f"] for i in infos}), "n_far_pairs": int(far[np.triu_indices(N, 1)].sum()), + "mesh_s": sum(i["mesh_s_f"] + i.get("mesh_s_c", 0.0) for i in infos), + "assemble_s": sum(i["assemble_s_f"] + i.get("assemble_s_c", 0.0) for i in infos), + "solve_s": sum(i["solve_s_f"] + i.get("solve_s_c", 0.0) for i in infos), + "level_gaps": list(level_gaps), "plan_s": t_plan, "build_s": t_build, "windows_wall_s": t_solve, "total_s": time.perf_counter() - t_all, "rich": rich} + return S, far, info + + +# ---------------------------------------------------------------- flagship-fast: the cheap prior (PRIOR_SCHEME.md Part III, sections 12 and 16) +# Hybrid H = micro-MoM (`micro_mom`: the flagship mesh family at a fixed panel budget per window, dense Cholesky) for self, +# ground and co-windowed pairs + the closed-form edge-coupling prior (`formula_prior`) for pairs never co-windowed. +# Mirrored verbatim (function sources) in deploy/tlsq_infer/src/tlsq_infer/_vendor/fastprior.py. + +# formula constants: frozen 2026-10-09, not tuned on labels +FORMULA_STEP_UM = 0.25 # boundary sample step (as the pair tokens) +FORMULA_R_GAPS = 150.0 # pairs farther apart than this (in smallest gaps) use the bounding-box form +FORMULA_SCREEN_UM = 1.0 # the screening factor is evaluated every FORMULA_SCREEN_UM of boundary and held in between +LITE_REFINE = 3 # rejected window solves: refine h by 2 up to this many times before majority-owned cells +LITE_LEVEL_GAPS = (10.0, 20.0, 40.0, 80.0) # windows of large layouts: finest panel within 10 gaps of the core, doubling beyond 10/20/40/80 +LITE_WINDOW_BUDGET = 2.0 # windows of large layouts: panel budget = this x the budget of the one-window (component) prior +LITE_WINDOW_PPG = [None] # windows of large layouts: panels per smallest gap of the finest level instead of a budget (None = budget; PRIOR_SCHEME.md 14.4) +LITE_MAX_CORE = [None] # windows of large layouts: conductors per core (None = the max_core argument; PRIOR_SCHEME.md 14.4.2) +LITE_GROWTH = 2.0 # merged panels per halving of h (measured 1.6-2.2 on the training families) +ALPHA_GAP_SHARE = 0.52 # dipole far pairs: perimeter x gap band share of the effective area; fit 0.519 (median log-ratio 0 vs the global gap/3 MoM, 68 cross-pocket pairs > 50 gaps of grid_qubit_1; PRIOR_SCHEME.md 14.2) +DIPOLE_K = 8 # nearest boundary samples searched for the nearest other conductor (gbar) +ROW_SUM_EPS = 0.0143 # training median of 1 - sum_j |C_ij| / C_ii (self = row sum / (1 - eps)) +EPS0_FF_UM = 8.8541878128e-3 + + +def plan_cores(sites: np.ndarray, max_core: int = 8) -> list: + """Cores (index arrays) by recursive bisection of the conductor sites (n, 2) along the longer extent until each core + has <= max_core conductors; each split is snapped to the widest coordinate gap between sites in the central half + of the sorted order (ties broken by the other coordinate, so the cores do not depend on the conductor order).""" + out = [] + + def rec(idx): + if len(idx) <= max_core: + out.append(idx) + return + s = sites[idx] + ax = int(np.argmax(s.max(0) - s.min(0))) + order = idx[np.lexsort((s[:, 1 - ax], s[:, ax]))] + x = sites[order, ax] + lo = max(1, len(order) // 4) + hi = max(lo + 1, min(len(order), (3 * len(order)) // 4 + 1)) + m = lo + int(np.argmax(x[lo:hi] - x[lo - 1:hi - 1])) + rec(order[:m]), rec(order[m:]) + + rec(np.arange(len(sites))) + return out + + +def _rot90(k: int): + """Exact rotation of coordinates by k x 90 degrees (swaps and sign flips only).""" + def f(xy): + x, y = xy[:, 0], xy[:, 1] + return np.stack([(x, y), (-y, x), (-x, -y), (y, -x)][k % 4], 1) + return f + + +def canonical_frames(G, conds: list) -> list: + """The layout in canonical frames, so that the lattice-anchored mesh (and hence the prior) does not depend on the + position, the 90-degree orientation or the conductor order of the input: rotations by k x 90 degrees whose + rotation-invariant key (signal bounding box, sorted conductor centroids and convex-hull vertices about the box + centre, ground bounds, rounded to 1 nm) is smallest (several when the layout is symmetric), translation of the signal + bounding box corner to the origin, coordinates rounded to 1e-6 um, collinear vertices removed (`shapely.simplify(0)`), + rings in normal form (`shapely.normalize`), conductors sorted by (centroid, area). Returns [(G, conds, order)]: + conds[k] of a frame is input conductor order[k].""" + keys = [] + for k in range(4): + f = _rot90(k) + sig = [shapely.transform(c, f) for c in conds] + b = shapely.bounds(np.array(sig, dtype=object)) + x0, y0, x1, y1 = b[:, 0].min(), b[:, 1].min(), b[:, 2].max(), b[:, 3].max() + cen = shapely.get_coordinates(shapely.centroid(np.array(sig, dtype=object))) - [(x0 + x1) / 2, (y0 + y1) / 2] + hull = shapely.get_coordinates(shapely.convex_hull(shapely.union_all(sig)))[:-1] - [(x0 + x1) / 2, (y0 + y1) / 2] + gb = np.round(np.array(shapely.transform(G, f).bounds) - [(x0 + x1) / 2, (y0 + y1) / 2] * 2, 3) + key = ((round(x1 - x0, 3), round(y1 - y0, 3)) + tuple(sorted(map(tuple, np.round(cen, 3).tolist()))) + + tuple(sorted(map(tuple, np.round(hull, 3).tolist()))) + tuple(gb.tolist())) + keys.append((key, k, x0, y0)) + best = min(kk[0] for kk in keys) + out = [] + for key, k, x0, y0 in keys: + if key != best: + continue + f = _rot90(k) + + def to(g, f=f, x0=x0, y0=y0): + return shapely.normalize(shapely.simplify(shapely.transform(g, lambda xy: np.round(f(xy) - [x0, y0], 6)), 0.0)) + + cs = [to(c) for c in conds] + cen = shapely.get_coordinates(shapely.centroid(np.array(cs, dtype=object))) + order = np.lexsort((np.round([c.area for c in cs], 6), np.round(cen[:, 1], 6), np.round(cen[:, 0], 6))) + out.append((to(G), [cs[i] for i in order], order)) + return out + + +def _gap_size(metals: list) -> tuple: + """(smallest gap, layout size) exactly as mom_capacitance_gds_flagship computes them (all pairs; small layouts).""" + bbox = shapely.union_all(metals).bounds + size = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) + gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) + return gap, size + + +def _graded_mesh(metals: list, n_core: int, h: float, levels: tuple, majority: bool = False) -> tuple: + """Core-graded flagship-family mesh (`anchored_cells_graded` + `strip_merge`): finest panel h within levels[0] of the + core conductors (metals[1:1 + n_core]), doubling beyond each level. Returns (centres, sizes, owners, h, raw count).""" + raw = anchored_cells_graded(metals, h, shapely.union_all(metals[1:1 + n_core]), levels, majority=majority) + c, wh, o = strip_merge(*raw, metals, h) + return c, wh, o, h, len(raw[0]) + + +def _lite_mesh(metals: list, h: float, budget: float, n_core: int = 0, levels: tuple = ()) -> tuple: + """Flagship-family mesh at the finest lattice level h 2^k predicted to fit the budget: a probe mesh at the level + estimated (2 merged panels per h of metal edge) to hold ~budget / 4 panels, then the level LITE_GROWTH^j finer + predicted to hold <= budget panels (each halving of h multiplies the panels by ~LITE_GROWTH), doubled while it does + not fit. levels (um from the n_core core conductors): core-graded mesh (`_graded_mesh`); () = uniform + (`proxy.mesh_flagship`). With an unbounded budget: the mesh at h. Returns (centres, sizes, owners, h, raw count).""" + def mesh(hh): + if not levels: + return P.mesh_flagship(metals, hh, budget) + while True: + r = _graded_mesh(metals, n_core, hh, levels) + if len(r[0]) <= budget: + return r + hh *= 2.0 + + if not np.isfinite(budget): + return mesh(h) + L = sum(g.length for g in metals) + k = max(0, int(np.ceil(np.log2(max(2.0 * L / (h * budget / 4), 1.0))))) + probe = mesh(h * 2.0**k) + j = min(int(np.floor(np.log(budget / len(probe[0])) / np.log(LITE_GROWTH))), int(round(np.log2(probe[3] / h)))) + return probe if j <= 0 else mesh(probe[3] / 2.0**j) + + +def _sym_solve(A, B): + """Solve with the lower triangle of the Fortran-ordered A from `proxy._assemble`: Cholesky, or the symmetric + indefinite (Bunch-Kaufman) factorisation when A is not positive definite.""" + try: + return P._chol_solve(A.copy(order="F"), B) + except np.linalg.LinAlgError: + from scipy.linalg import solve + return solve(A, B, lower=True, assume_a="sym", overwrite_a=True, check_finite=False) + + +def _window_solve(metals: list, n_core: int, h: float, budget: float, eps_r: float, all_rhs: bool, levels: tuple = ()) -> tuple: + """Flagship-family mesh of one window at the lattice level of h that fits the budget (`_lite_mesh`), exact near + field, dense Cholesky (H-matrix PCG above DENSE_MAX panels); right-hand sides: every metal (all_rhs, as + `proxy._cap_flagship`) or the n_core core conductors; levels: core-graded mesh (`_lite_mesh`). A solve is rejected + when the system is not positive definite, a metal has no panel or (all_rhs) a mutual entry is not negative (cut + panels of different conductors overlapping on a lattice coarser than the features); the mesh is then refined (h / 2, budget lifted) up to LITE_REFINE times, and finally + meshed with majority-owned finest cells (as the flagship). Returns (R (n_rhs, n_metals) charges per metal, info).""" + cols = np.arange(len(metals)) if all_rhs else np.arange(1, 1 + n_core) + t_mesh = t_asm = t_sol = 0.0 + hh, cap, refined, majority = h, budget, 0, False + while True: + t = time.perf_counter() + if not refined: + c, wh, o, hh, n_raw = _lite_mesh(metals, hh, cap, n_core, levels) + elif levels: + c, wh, o, hh, n_raw = _graded_mesh(metals, n_core, hh, levels, majority) + else: + c, wh, o, hh, n_raw = P.mesh_flagship(metals, hh, cap, majority=majority) + t_mesh += time.perf_counter() - t + t = time.perf_counter() + try: + if len(c) <= P.DENSE_MAX: + A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) + t_asm += time.perf_counter() - t + t = time.perf_counter() + Bm = (o[:, None] == cols[None, :]).astype(float) + if all_rhs: + Q = P._chol_solve(A, Bm) + else: # windows: an indefinite system (overlapping cut panels on the coarse graded levels) is solved by LDL^T + Q = _sym_solve(A, Bm) + else: + Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)[:, cols] + R = np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) + off = np.ones(R.shape, bool) + off[np.arange(len(cols)), cols] = False + ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and (not all_rhs or np.all(R[off] < 0))) + except np.linalg.LinAlgError: + ok = False + t_sol += time.perf_counter() - t + if ok or majority: + break + if refined < LITE_REFINE: + hh, cap, refined = hh / 2, np.inf, refined + 1 + else: + majority = True + return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, + "assemble_s": t_asm, "solve_s": t_sol} + + +def _lite_window(G, conds: list, core, R_g: float, margin: float, fill_um: float, tree, etched) -> tuple: + """Window of a core: ([ground, core..., halo...], halo). Halo = conductors within R_g of a core conductor (separate + nets at 0 V); ground = chip ground clipped to the core + halo box widened by margin, plus every farther conductor in + the box as ground metal with its etched surroundings within fill_um filled where farther than R_g from a member.""" + hit = tree.query([conds[i] for i in core], predicate="dwithin", distance=R_g)[1] + halo = np.setdiff1d(np.unique(hit), core) + members = np.concatenate([core, halo]).astype(int) + b = shapely.bounds(np.array([conds[i] for i in members], dtype=object)) + box = (b[:, 0].min() - margin, b[:, 1].min() - margin, b[:, 2].max() + margin, b[:, 3].max() + margin) + far = np.setdiff1d(tree.query(shapely.box(*box), predicate="intersects"), members) + Gw = shapely.clip_by_rect(G, *box) + if len(far): + farg = shapely.clip_by_rect(shapely.union_all([conds[i] for i in far]), *box) + fill = shapely.intersection(shapely.clip_by_rect(etched, *box), farg.buffer(fill_um, quad_segs=4)) + fill = fill.difference(shapely.union_all([conds[i] for i in members]).buffer(R_g, quad_segs=4)) + Gw = shapely.union_all([Gw, farg, fill]) + return [_valid(Gw)] + [conds[i] for i in members], halo + + +_LITE_BUDGET_USED: list = [0.0] +_LITE: dict = {} # layout of the running micro_mom call, inherited by forked window workers + + +def _lite_job(k: int) -> tuple: + L = _LITE + t = time.perf_counter() + metals, halo = _lite_window(L["G"], L["conds"], L["cores"][k], L["R_g"], L["margin"], L["fill_um"], L["tree"], L["etched"]) + t_build = time.perf_counter() - t + bx = shapely.bounds(metals[0]) + h = max(L["h"], max(bx[2] - bx[0], bx[3] - bx[1]) / 4096) + budget = L["budget"] + if LITE_WINDOW_PPG[0]: # resolution-controlled windows (PRIOR_SCHEME.md 14.4): finest panel gap / ppg, no budget + h, budget = L["gap"] / LITE_WINDOW_PPG[0], np.inf + R, info = _window_solve(metals, len(L["cores"][k]), h, budget, L["eps_r"], False, L["levels"]) + info.update(build_s=t_build, n_halo=len(halo), n_core=len(L["cores"][k])) + return k, halo, R, info + + +def micro_mom(G, conds: list, eps_r: float = 11.45, budget: float = 1500, cells_per_gap: float = 3.0, max_core: int = 8, + halo_gaps: float = 100.0, margin_gaps: float = 100.0, margin_min_um: float = 150.0, fill_um: float = 250.0, + workers: int = 1, level_gaps: tuple = LITE_LEVEL_GAPS, window_budget: float | None = None, canonical: bool = True) -> tuple: + """Cheap micro-MoM prior (PRIOR_SCHEME.md section 12, M / hybrid H): (C (N+1, N+1) fF Maxwell, far_mask, info). + <= max_core conductors: one global window = the layout as given, h = max(gap / cells_per_gap, size / 4096) doubled + on the flagship lattice until the merged mesh has <= budget panels, every metal excited (with budget = inf this is + `proxy.mom_capacitance_gds_flagship(rich=False)` bit for bit; `_lite_mesh` picks the level). More conductors: cores of <= max_core by bisection, + one window per core (halo within halo_gaps, ground clipped at margin_gaps), entry (i, j) = mean of the two window + estimates when both exist (a non-negative window estimate is not used), ground row from the columns, C_00 = row sum / + (1 - ROW_SUM_EPS); pairs never co-windowed (far_mask, > halo_gaps apart) in different ground pockets take the screened + dipole value (`dipole_far`), in the same pocket the closed form (`formula_prior`, quadrature step one smallest gap). level_gaps: core-graded window + meshes (finest panel within level_gaps[0] smallest gaps of the core, doubling beyond each level); window systems that + are not positive definite are solved by LDL^T; window budget = window_budget or LITE_WINDOW_BUDGET x budget. Windows + run on `workers` forked processes. canonical: solved in the `canonical_frames` (mean over them when the layout is + symmetric; invariant to translation, 90-degree rotation and conductor order), returned in the input order.""" + t_all = time.perf_counter() + if canonical: # mean over the canonical frames (one unless the layout is symmetric), in the input order + runs = [] + for Gc, cc, order in canonical_frames(G, conds): + C, far, info = micro_mom(Gc, cc, eps_r, budget, cells_per_gap, max_core, halo_gaps, margin_gaps, margin_min_um, fill_um, + workers, level_gaps, window_budget, canonical=False) + inv = np.r_[0, np.argsort(order) + 1] + runs.append((C[np.ix_(inv, inv)], far[np.ix_(inv, inv)], info)) + C = runs[0][0] if len(runs) == 1 else sum(r[0] for r in runs) / len(runs) + far = np.logical_or.reduce([r[1] for r in runs]) + info = runs[0][2] + for k in ("mesh_s", "assemble_s", "solve_s", "build_s", "formula_s"): + info[k] = sum(r[2][k] for r in runs) + info["n_frames"] = len(runs) + info["total_s"] = time.perf_counter() - t_all + return C, far, info + metals = [G] + list(conds) + N = len(metals) + far = np.zeros((N, N), bool) + if len(conds) <= max_core: + gap, size = _gap_size(metals) + h = max(gap / cells_per_gap, size / 4096) + R, wi = _window_solve(metals, len(conds), h, budget, eps_r, True) + C = 0.5 * (R + R.T) + info = {"n_windows": 1, "min_gap_um": gap, "h_um": [wi["h_um"]], "panels": [wi["panels"]], "panels_per_gap": [gap / wi["h_um"]], + "majority": [wi["majority"]], "refined": [wi["refined"]], "mesh_s": wi["mesh_s"], "assemble_s": wi["assemble_s"], "solve_s": wi["solve_s"], + "build_s": 0.0, "plan_s": 0.0, "formula_s": 0.0, "n_far_pairs": 0, "budget": budget} + info["total_s"] = time.perf_counter() - t_all + return C, far, info + t = time.perf_counter() + gap = gap_of(metals) + R_g, margin = halo_gaps * gap, max(margin_gaps * gap, margin_min_um) + b = shapely.bounds(np.array(conds, dtype=object)) + cores = plan_cores(np.stack([(b[:, 0] + b[:, 2]) / 2, (b[:, 1] + b[:, 3]) / 2], 1), LITE_MAX_CORE[0] or max_core) + tree = shapely.STRtree(conds) + etched = shapely.box(*G.bounds).difference(G) + _LITE.clear() + _LITE.update(G=G, conds=conds, cores=cores, R_g=R_g, margin=margin, fill_um=fill_um, tree=tree, etched=etched, + h=gap / cells_per_gap, gap=gap, budget=LITE_WINDOW_BUDGET * budget if window_budget is None else window_budget, eps_r=eps_r, + levels=tuple(float(x) * gap for x in level_gaps)) + _LITE_BUDGET_USED[:] = [_LITE["budget"]] + t_plan = time.perf_counter() - t + t = time.perf_counter() + if workers > 1 and len(cores) > 1: + with ProcessPoolExecutor(min(workers, len(cores)), mp_context=get_context("fork")) as ex: + res = list(ex.map(_lite_job, range(len(cores)))) + else: + res = [_lite_job(k) for k in range(len(cores))] + t_win = time.perf_counter() - t + _LITE.clear() + acc, cnt = np.zeros((N, N)), np.zeros((N, N)) + for k, halo, R, _ in res: + idx = np.concatenate([[0], cores[k] + 1, halo + 1]).astype(int) + for r, ci in enumerate(cores[k] + 1): + use = (R[r] < 0) | (idx == ci) # a non-negative mutual estimate of a window (tiny far entries) is not used + acc[ci, idx[use]] += R[r][use] + cnt[ci, idx[use]] += 1 + have = cnt > 0 + Cw = np.where(have, acc / np.where(have, cnt, 1), 0.0) + C = np.where(have & have.T, 0.5 * (Cw + Cw.T), np.where(have, Cw, Cw.T)) + far = ~(have | have.T) + np.fill_diagonal(far, False) + t = time.perf_counter() + iu = np.nonzero(np.triu(far, 1)) + t_dip, n_dip = 0.0, 0 + if len(iu[0]): + pid = np.r_[-10**9, pocket_ids(G, conds)] + cross = pid[iu[0]] != pid[iu[1]] # different ground pockets: screened dipole; same pocket: closed form + if (~cross).any(): + F, _ = formula_prior(G, conds, eps_r, step_um=max(FORMULA_STEP_UM, gap), pairs=np.stack(iu, 1)[~cross], gap=gap, workers=workers) + C[iu[0][~cross], iu[1][~cross]] = F[iu[0][~cross], iu[1][~cross]] + if cross.any(): + t_dip = time.perf_counter() + C[iu[0][cross], iu[1][cross]] = dipole_far(G, conds, np.stack(iu, 1)[cross], eps_r, gap) + t_dip, n_dip = time.perf_counter() - t_dip, int(cross.sum()) + C[iu[1], iu[0]] = C[iu] + t_form = time.perf_counter() - t + C[0, 0] = np.abs(C[0, 1:]).sum() / (1 - ROW_SUM_EPS) + infos = [r[3] for r in res] + info = {"n_windows": len(cores), "min_gap_um": gap, "R_g_um": R_g, "margin_um": margin, "h_um": [i["h_um"] for i in infos], + "panels": [i["panels"] for i in infos], "panels_per_gap": [gap / i["h_um"] for i in infos], + "majority": [i["majority"] for i in infos], "refined": [i["refined"] for i in infos], "cores": [i["n_core"] for i in infos], "halos": [i["n_halo"] for i in infos], + "mesh_s": sum(i["mesh_s"] for i in infos), "assemble_s": sum(i["assemble_s"] for i in infos), + "solve_s": sum(i["solve_s"] for i in infos), "build_s": sum(i["build_s"] for i in infos), "plan_s": t_plan, + "windows_wall_s": t_win, "formula_s": t_form, "n_far_pairs": int(len(iu[0])), "dipole_s": t_dip, + "n_dipole_pairs": n_dip, "budget": _LITE_BUDGET_USED[0], + "workers": workers, "level_gaps": list(level_gaps)} + info["total_s"] = time.perf_counter() - t_all + return C, far, info + + +def pocket_ids(G, conds: list) -> np.ndarray: + """Ground pocket of every conductor: index of the interior ring of the ground metal that contains it (STRtree of the + rings' polygons, `within`); a conductor in no ring gets its own id (-1 - k).""" + rings = [shapely.Polygon(r) for p in getattr(G, "geoms", [G]) for r in p.interiors] + out = -1 - np.arange(len(conds)) + if rings: + c, r = shapely.STRtree(rings).query(list(conds), predicate="within") + out[c] = r + return out + + +def _edge_samples(geoms: list, step: float) -> tuple: + """Points every <= step along every polygon edge of geoms (vertices included), with the index of their geometry: + (points (n, 2), owner (n,)). Vectorised over all edges (no per-ring interpolation).""" + segs, sown = [], [] + for k, g in enumerate(geoms): + for p in getattr(g, "geoms", [g]): + for ring in [p.exterior, *p.interiors]: + xy = np.asarray(ring.coords) + segs.append(np.stack([xy[:-1], xy[1:]], 1)) + sown.append(np.full(len(xy) - 1, k)) + S, sown = np.concatenate(segs), np.concatenate(sown) + L = np.sqrt(((S[:, 1] - S[:, 0]) ** 2).sum(1)) + n = np.maximum(1, np.ceil(L / step).astype(int)) + seg = np.repeat(np.arange(len(S)), n) + t = (np.arange(n.sum()) - np.repeat(np.cumsum(n) - n, n)) / np.repeat(n, n) + return S[seg, 0] + t[:, None] * (S[seg, 1] - S[seg, 0]), sown[seg] + + +def dipole_far(G, conds: list, pairs, eps_r: float = 11.45, gap: float | None = None) -> np.ndarray: + """Screened-dipole far couplings (PRIOR_SCHEME.md 14.2): for metal-index pairs (k, 2) (1 = first conductor), + C_ij = -(1 + eps_r) eps0 At_i At_j / (2 pi d_eff^3), d_eff^2 = d^2 + a_i^2 + a_j^2, a = sqrt(At / pi), d = centroid + distance, At = A + ALPHA_GAP_SHARE x P x gbar with gbar the mean distance from i's edge samples (step one gap) to the + nearest other metal: ground edge samples (step gap / 4) by one k-d tree, other conductors by one k-d tree of all + conductor samples with owner labels (DIPOLE_K neighbours). Returns the values (k,).""" + metals = [G] + list(conds) + gap = gap_of(metals) if gap is None else gap + pairs = np.asarray(pairs, int).reshape(-1, 2) + pts, own = _edge_samples(list(conds), gap) + own = own + 1 + sel = np.isin(own, np.unique(pairs)) + q = pts[sel] + dg, _ = cKDTree(_edge_samples([G], gap / 4)[0]).query(q) + d, idx = cKDTree(pts).query(q, k=min(DIPOLE_K, len(own))) + if d.ndim == 1: + d, idx = d[:, None], idx[:, None] + d = np.where(own[np.minimum(idx, len(own) - 1)] != own[sel][:, None], d, np.inf).min(1) + gbar = np.bincount(own[sel], np.minimum(dg, d), len(metals)) / np.maximum(np.bincount(own[sel], minlength=len(metals)), 1) + area = np.array([g.area for g in metals]) + perim = np.array([g.length for g in metals]) + At = area + ALPHA_GAP_SHARE * perim * gbar + cen = shapely.get_coordinates(shapely.centroid(np.array(metals, dtype=object))) + a, b = pairs[:, 0], pairs[:, 1] + d2 = ((cen[a] - cen[b]) ** 2).sum(1) + (At[a] + At[b]) / np.pi + return -(1 + eps_r) * EPS0_FF_UM * At[a] * At[b] / (2 * np.pi * d2 ** 1.5) + + +def _ground_segments(G): + """Edge segments (m, 2, 2) of the ground metal and an STRtree over them.""" + _, S, _ = P._segments([G]) + return S, shapely.STRtree(shapely.linestrings(S)) + + +def _metal_length(A: np.ndarray, B: np.ndarray, S: np.ndarray, tree) -> np.ndarray: + """Length of ground metal crossed by each segment A[k] -> B[k] (endpoints off the metal): crossings with the ground + edges (STRtree) sorted along the segment, alternate inside / outside intervals summed.""" + out = np.zeros(len(A)) + if not len(A): + return out + li, gi = tree.query(shapely.linestrings(np.stack([A, B], 1)), predicate="intersects") + if not len(li): + return out + p, r = A[li], B[li] - A[li] + q, s = S[gi, 0], S[gi, 1] - S[gi, 0] + den = r[:, 0] * s[:, 1] - r[:, 1] * s[:, 0] + ok = np.abs(den) > 1e-12 + li, t = li[ok], np.clip(((q - p)[ok, 0] * s[ok, 1] - (q - p)[ok, 1] * s[ok, 0]) / den[ok], 0.0, 1.0) + order = np.lexsort((t, li)) + li, t = li[order], t[order] + start = np.r_[0, np.nonzero(np.diff(li))[0] + 1] + n = np.diff(np.r_[start, len(li)]) + rank = np.arange(len(li)) - np.repeat(start, n) + keep = rank < np.repeat(n // 2 * 2, n) + sgn = np.where(rank % 2 == 1, 1.0, -1.0) + out += np.bincount(li[keep], weights=(sgn * t)[keep], minlength=len(A)) + return out * np.sqrt(((B - A) ** 2).sum(1)) + + +def _cps_m(d, w1, w2): + """Coplanar-strip modulus (as `blocks.edge_features`; w = inf for the ground).""" + if np.isinf(w1) or np.isinf(w2): + wf = w2 if np.isinf(w1) else w1 + return d / (d + wf) + return d * (d + w1 + w2) / ((d + w1) * (d + w2)) + + +_FORM: dict = {} # samples and trees of the running formula_prior call, inherited by forked row workers + + +def _formula_row(i: int) -> tuple: + """Row i of the directed sums I[i, j] of `formula_prior` (j = the near metals of i; ground last term included).""" + F = _FORM + pts, kd, near, width, R, k, step_um, every = F["pts"], F["kd"], F["near"], F["width"], F["R"], F["k"], F["step"], F["every"] + I = np.zeros(near.shape[0]) + dmin_other, dG = np.full(len(pts[i]), np.inf), None + for j in np.nonzero(near[i])[0]: + d, idx = kd[j].query(pts[i], distance_upper_bound=R if j > 0 else np.inf) + ok = np.isfinite(d) + if j > 0: + dmin_other = np.minimum(dmin_other, d) + else: + dG = d + if not ok.any(): + continue + dd = np.maximum(d[ok], 0.05) + if j == 0: + S = np.ones(ok.sum()) + else: + sel = np.arange(0, ok.sum(), every) + A = pts[i][ok][sel] + lg = _metal_length(A, pts[j][idx[ok][sel]], F["SG"], F["gtree"]) + S = np.exp(-lg / (dd[sel] + min(width[i], width[j])))[np.arange(ok.sum()) // every] + I[j] = k * np.sum(step_um * _kratio(_cps_m(dd, width[i], width[j])) * S) + if dG is not None: + share = float(np.mean(dG <= dmin_other)) + I[0] += 8 * EPS0_FF_UM * (1 + F["eps_r"]) / 2 * np.sqrt(F["area"][i] / np.pi) * share + return i, I + + +def formula_prior(G, conds: list, eps_r: float = 11.45, step_um: float = FORMULA_STEP_UM, R_gaps: float = FORMULA_R_GAPS, + pairs=None, gap: float | None = None, screen_um: float = FORMULA_SCREEN_UM, workers: int = 1, + max_core: int = 8) -> tuple: + """Closed-form edge-coupling prior (PRIOR_SCHEME.md section 12, F): (C (N+1, N+1) fF Maxwell, info). No mesh, no solve. + C_ij = eps0 (1 + eps_r) / 2 x mean over the directions (i, j), (j, i) of sum_p K(k') / K(k) S(p) step over the boundary + samples p of i (modulus of the local widths 2 A / P and the distance to the nearest sample of j, within R_gaps + smallest gaps; the ground without a bound), S(p) = exp(-l_G / (d + w_min)) with l_G the ground metal crossed on p -> nearest point of j. C_iG: the + same sum against the ground edge (S = 1) + 8 eps0 eps_eff sqrt(A_i / pi) x (share of i's samples nearest to the + ground). Pairs farther than R_gaps: the same form on the bounding boxes (facing length (P_i + P_j) / 2, distance of + the boxes, l_G = ground area fraction x distance). Self terms: row sums / (1 - ROW_SUM_EPS). pairs (k, 2) of metal + indices (0 = ground): only those mutual entries (the rest 0, no self terms). More than max_core conductors: the + quadrature step is at least gap / 4 and the screening spacing at least one gap (numerically equivalent: median + 0.02 %, max 1.2 % on the grids vs 0.25 um), rows on `workers` forked processes.""" + t0 = time.perf_counter() + metals = [G] + list(conds) + N = len(metals) + gap = gap_of(metals) if gap is None else gap + if len(conds) > max_core: + step_um, screen_um = max(step_um, gap / 4), max(screen_um, gap) + R = R_gaps * gap + k = EPS0_FF_UM * (1 + eps_r) / 2 + want = np.zeros((N, N), bool) + if pairs is None: + want[np.triu_indices(N, 1)] = True + else: + pairs = np.sort(np.asarray(pairs, int).reshape(-1, 2), 1) + want[pairs[:, 0], pairs[:, 1]] = True + area = np.array([g.area for g in metals]) + perim = np.array([g.length for g in metals]) + width = np.r_[np.inf, 2 * area[1:] / perim[1:]] + tree = shapely.STRtree(list(conds)) + near = np.zeros((N, N), bool) + a, b = tree.query(list(conds), predicate="dwithin", distance=R) + near[a + 1, b + 1] = True + near[0, 1:] = near[1:, 0] = True + np.fill_diagonal(near, False) + near &= want | want.T + gx0, gy0, gx1, gy1 = G.bounds + need = np.unique(np.nonzero(near)[0]) + pts, kd = {}, {} + for i in np.unique(np.r_[need, np.nonzero(near.any(0))[0]]): + p = sample_boundary(metals[i], step_um) + if i == 0: # ground edge = boundary of the etched region (not the chip outline) + on = (np.abs(p[:, 0] - gx0) < 1e-6) | (np.abs(p[:, 0] - gx1) < 1e-6) | (np.abs(p[:, 1] - gy0) < 1e-6) | (np.abs(p[:, 1] - gy1) < 1e-6) + p = p[~on] + pts[i] = p + kd[i] = cKDTree(p) + SG, gtree = _ground_segments(G) + _FORM.clear() + _FORM.update(pts=pts, kd=kd, near=near, width=width, area=area, R=R, k=k, step=step_um, eps_r=eps_r, + every=max(1, int(round(screen_um / step_um))), SG=SG, gtree=gtree) + rows = [i for i in need if i > 0] + if workers > 1 and len(rows) > 1: + with ProcessPoolExecutor(min(workers, len(rows)), mp_context=get_context("fork")) as ex: + res = list(ex.map(_formula_row, rows, chunksize=max(1, len(rows) // (4 * workers)))) + else: + res = [_formula_row(i) for i in rows] + _FORM.clear() + I = np.zeros((N, N)) + for i, row in res: + I[i] = row + C = np.zeros((N, N)) + iu = np.nonzero(np.triu(near, 1)) + gnd = iu[0] == 0 + C[iu] = np.where(gnd, I[iu[1], iu[0]], 0.5 * (I[iu] + I[iu[1], iu[0]])) + fa, fb = np.nonzero(np.triu(want & ~near & ~near.T, 1)) + if len(fa): + bb = shapely.bounds(np.array(metals, dtype=object)) + dx = np.maximum(0.0, np.maximum(bb[fa, 0] - bb[fb, 2], bb[fb, 0] - bb[fa, 2])) + dy = np.maximum(0.0, np.maximum(bb[fa, 1] - bb[fb, 3], bb[fb, 1] - bb[fa, 3])) + dd = np.maximum(np.hypot(dx, dy), 0.05) + fG = G.area / max(shapely.box(*G.bounds).area, 1e-12) + w1, w2 = width[fa], width[fb] + m = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) + S = np.exp(-fG * dd / (dd + np.minimum(w1, w2))) + C[fa, fb] = k * 0.5 * (perim[fa] + perim[fb]) * _kratio(m) * S + C = -(C + C.T) + info = {"n_sampled_pairs": int(len(iu[0])), "n_bbox_pairs": int(len(fa)), "min_gap_um": gap, "step_um": step_um, + "samples": int(sum(len(p) for p in pts.values()))} + if pairs is None: + np.fill_diagonal(C, np.abs(C).sum(1) / (1 - ROW_SUM_EPS)) + info["total_s"] = time.perf_counter() - t0 + return C, info diff --git a/src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior_loc.py b/src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior_loc.py new file mode 100644 index 0000000000000000000000000000000000000000..192c71d44cbb0044b22f60215cfbe9100bde288c --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior_loc.py @@ -0,0 +1,210 @@ +"""Local-gap (graded) lite micro-MoM prior: PRIOR_SCHEME.md Amendment MESH (2026-10-11). + +The lite prior meshes every metal edge at h = gap / ppg with gap the layout's global smallest conductor gap. A sliver +(exp12: the 35 nm end slit of a pad lead, 10.2 um long) therefore sets the whole mesh, and h sits on the size / 4096 +floor at every ppg (the resolution knob is dead). Here the panel size is set by the LOCAL gap of each quadtree cell: + + h(cell) = clamp(local_gap(cell) / ppg, h_floor, H), H = G_ref / ppg, h_floor = size / FLOOR_DIV + +local_gap(cell) = min over the metals k the cell touches and the other metals j of distance(cell & metal_k, metal_j) +(the gap of the edge stretch inside the cell, never smaller than the global smallest gap); G_ref = the smallest pair +gap among conductor pairs whose gap is >= SLIVER_UM ("sliver" pairs only refine their own neighbourhood). Same lattice +(H 2^-k, anchored to the signal bounding box), exact cut panels, strip merge bounded by each panel's own size, slab +kernel and exact near field as `fastprior.micro_mom`. A layout without a sliver pair is passed to `fastprior.micro_mom` +unchanged (bit-identical prior). Resolution descriptor: proxy_min_gap_um = G_ref, proxy_h_min_um = H (log ppg). +""" + +from __future__ import annotations + +import time + +import numpy as np +import shapely + +from . import fastprior as F +from . import proxy as P + +SLIVER_UM = 0.25 # pair gaps below this are slivers (no labelled layout has a gap in [0.04, 1.99] um; exp12 slits 34.9-35.6 nm) +FLOOR_DIV = 4096 # h_floor = layout size / FLOOR_DIV (the existing floor) + + +def ref_gap(metals: list, sliver: float = SLIVER_UM) -> tuple: + """(G_ref, smallest gap, layout size, number of sliver pairs). G_ref = smallest pair gap >= sliver; when every pair + is a sliver, the edge-length-weighted 5th percentile of the local gap of the boundary (0.25 um samples).""" + gmin, size = F._gap_size(metals) + n = len(metals) + d = np.array([shapely.distance(metals[i], metals[j]) for i in range(n) for j in range(i + 1, n)]) + ok = d >= sliver + if ok.any(): + return float(d[ok].min()), float(gmin), float(size), int((~ok).sum()) + lg = [] + for i, g in enumerate(metals): + others = shapely.union_all([metals[k] for k in range(n) if k != i]) + for ln in getattr(g.boundary, "geoms", [g.boundary]): + pts = shapely.line_interpolate_point(ln, np.arange(0, ln.length, 0.25)) + lg.append(shapely.distance(pts, others)) + return float(max(np.percentile(np.concatenate(lg), 5), gmin)), float(gmin), float(size), int((~ok).sum()) + + +def _local_gap(metals: list, boxes, hit, inn, pcs, sel) -> np.ndarray: + """local_gap of the cells sel (indices): min over touched metals k and other metals j of distance(cell & k, j).""" + lg = np.full(len(sel), np.inf) + m = len(metals) + for k in range(m): + t = hit[k, sel] + if not t.any(): + continue + ix = sel[t] + geo = np.where(inn[k, ix], boxes[ix], pcs[k][ix]) + bad = np.array([g is None for g in geo]) + geo[bad] = boxes[ix][bad] + dk = np.full(len(ix), np.inf) + for j in range(m): + if j != k: + dk = np.minimum(dk, shapely.distance(geo, metals[j])) + lg[t] = np.minimum(lg[t], dk) + return lg + + +def anchored_cells_local(metals: list, H: float, h_floor: float, ppg: float, grade: float = 2.0, majority: bool = False): + """`proxy.anchored_cells` on the lattice of H (anchored to the signal bounding box) with the finest level of every + cell set by its local gap: a cell (cut or whole) is final once h <= clamp(local_gap / ppg, h_floor, H). Returns + centres (n, 2), sizes (n, 2), owner (n,).""" + edges = shapely.union_all([g.boundary for g in metals]) + sig = metals[1:] if len(metals) > 1 else metals + ax, ay = shapely.union_all(sig).bounds[:2] + X0, Y0, X1, Y1 = shapely.union_all(metals).bounds + span = max(X1 - X0, Y1 - Y0) + K = max(0, int(np.ceil(np.log2(max(span / 16, H) / H)))) + h0 = H * 2**K + ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0)) + ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0)) + gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1)) + xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0) + gq = P._Geoms(list(metals) + [edges]) + tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool) + out_c, out_h, out_o = [], [], [] + while len(xs): + boxes = shapely.box(xs, ys, xs + h, ys + h) + cov, hit, inn, pcs = P._cover(gq, boxes, h, tst, inn) + keep = cov.sum(0) > 1e-3 + xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep] + pcs = [p[keep] for p in pcs] + cx, cy = xs + h / 2, ys + h / 2 + full = cov.max(0) > 0.999 + cand = h <= H * 1.0001 + last = cand & (h <= h_floor * 1.0001) + need = np.nonzero(cand & ~last)[0] + if len(need): + tgt = np.clip(_local_gap(metals, boxes, hit, inn, pcs, need) / ppg, h_floor, H) + last[need] = h[need] <= tgt * 1.0001 + d = np.full(len(xs), np.inf) + far = full & ~last + d[far] = P._distance(gq, len(metals), boxes[far]) + leaf = full & (last | (h <= grade * d + 1e-12)) + out_c.append(np.stack([cx[leaf], cy[leaf]], 1)) + out_h.append(np.stack([h[leaf], h[leaf]], 1)) + out_o.append(cov[:, leaf].argmax(0)) + cut = last & ~leaf + if majority and cut.any(): + take = cut & (cov.max(0) >= 0.5) + out_c.append(np.stack([cx[take], cy[take]], 1)) + out_h.append(np.stack([h[take], h[take]], 1)) + out_o.append(cov[:, take].argmax(0)) + cut = cut & False + if cut.any(): + gs = gq.get() + for k, g in enumerate(gs[:len(metals)]): + shapely.prepare(g) + sel = np.nonzero(cut & (cov[k] > 1e-3))[0] + if not len(sel): + continue + pcs_k = pcs[k][sel] + bb = shapely.bounds(pcs_k) + cen = shapely.get_coordinates(shapely.centroid(pcs_k)) + inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1]) + if not inside.all(): + cen[~inside] = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside])) + out_c.append(cen) + out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6)) + out_o.append(np.full(len(sel), k)) + gq.put(gs) + split = ~leaf & ~last + hs = h[split] / 2 + xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs]) + ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs]) + h = np.concatenate([hs] * 4) + tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4) + return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o) + + +def mesh_local(metals: list, H: float, h_floor: float, ppg: float, majority: bool = False) -> tuple: + """Strip-merged local mesh (strip length <= 16 x the panel's own size and <= the distance to the nearest vertex). + Returns (centres, sizes, owners, raw count).""" + raw = anchored_cells_local(metals, H, h_floor, ppg, majority=majority) + c, wh, o = F.strip_merge(*raw, metals, h_floor) + return c, wh, o, len(raw[0]) + + +def _solve(metals: list, H: float, h_floor: float, ppg: float, eps_r: float) -> tuple: + """`fastprior._window_solve(all_rhs=True)` on the local mesh: rejected solves (not PD, a metal without a panel, a + non-negative mutual entry) refine (H, h_floor) / 2 up to LITE_REFINE times, then majority-owned cut cells.""" + t_mesh = t_sol = 0.0 + cols = np.arange(len(metals)) + refined, majority = 0, False + while True: + t = time.perf_counter() + c, wh, o, n_raw = mesh_local(metals, H, h_floor, ppg, majority) + t_mesh += time.perf_counter() - t + t = time.perf_counter() + try: + if len(c) <= P.DENSE_MAX: + A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) + Q = P._chol_solve(A, (o[:, None] == cols[None, :]).astype(float)) + del A + else: + Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r) + R = np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) + off = ~np.eye(len(metals), dtype=bool) + ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and np.all(R[off] < 0)) + except np.linalg.LinAlgError: + ok = False + t_sol += time.perf_counter() - t + if ok or majority: + break + if refined < F.LITE_REFINE: + H, h_floor, refined = H / 2, h_floor / 2, refined + 1 + else: + majority = True + return R, {"H_um": H, "h_floor_um": h_floor, "h_min_um": float(wh.min()), "panels": len(c), "raw": n_raw, + "refined": refined, "majority": majority, "mesh_s": t_mesh, "solve_s": t_sol} + + +def micro_mom_loc(G, conds: list, eps_r: float = 11.45, ppg: float = 3.0, sliver: float = SLIVER_UM, + floor_div: float = FLOOR_DIV, canonical: bool = True) -> tuple: + """Local-gap lite prior of a <= 8-conductor layout: (C (N+1, N+1) fF, far_mask (all False), info). Layouts without a + sliver pair: `fastprior.micro_mom(budget=inf, cells_per_gap=ppg)` (the existing liteppg prior, bit-identical). + Mean over the canonical frames of symmetric layouts, returned in the input order (as micro_mom).""" + t_all = time.perf_counter() + metals = [G] + list(conds) + gref, gmin, size, n_sl = ref_gap(metals, sliver) + if n_sl == 0 or len(conds) > 8: # no sliver (or windows: out of scope) -> the existing prior + C, far, info = F.micro_mom(G, conds, eps_r, budget=np.inf, cells_per_gap=ppg) + info.update(local=False, G_ref_um=float(info["min_gap_um"]), H_um=float(min(info["h_um"])), n_sliver_pairs=n_sl) + return C, far, info + runs = [] + frames = F.canonical_frames(G, conds) if canonical else [(G, list(conds), np.arange(len(conds)))] + for Gc, cc, order in frames: + R, wi = _solve([Gc] + list(cc), gref / ppg, size / floor_div, ppg, eps_r) + C = 0.5 * (R + R.T) + inv = np.r_[0, np.argsort(order) + 1] + runs.append((C[np.ix_(inv, inv)], wi)) + C = sum(r[0] for r in runs) / len(runs) + wi = runs[0][1] + info = {"local": True, "n_windows": 1, "n_frames": len(runs), "min_gap_um": gref, "G_ref_um": gref, "gmin_um": gmin, + "n_sliver_pairs": n_sl, "H_um": wi["H_um"], "h_floor_um": wi["h_floor_um"], "h_um": [wi["H_um"]], + "h_min_um": wi["h_min_um"], "panels": [wi["panels"]], "panels_per_gap": [gref / wi["H_um"]], + "majority": [wi["majority"]], "refined": [wi["refined"]], + "mesh_s": sum(r[1]["mesh_s"] for r in runs), "solve_s": sum(r[1]["solve_s"] for r in runs)} + info["total_s"] = time.perf_counter() - t_all + return C, np.zeros(C.shape, bool), info diff --git a/src/squadds/ml/capacitance/_core/_tlsq/embed/proxy.py b/src/squadds/ml/capacitance/_core/_tlsq/embed/proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..27f8c4401fead85b91d59edf40669bde07d69e59 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/embed/proxy.py @@ -0,0 +1,944 @@ +"""Cheap physics proxy: thin-film method-of-moments capacitance on the metal masks. + +Planar conductors of negligible thickness on a dielectric half-space: the quasi-static Green's function is +1 / (4 pi eps0 eps_eff r) with eps_eff = (eps_r + 1) / 2. The metal is discretised into square cells (pulse basis, +point matching); a uniformly charged square of side a has self-potential q / (4 pi eps0 eps_eff) * 4 ln(1 + sqrt 2) / a. +Solving P q = v for each conductor at 1 V (others at 0 V) gives the full Maxwell capacitance matrix, including +shielding and other non-local effects that local descriptors cannot represent. Truncation: the ground plane is +represented only inside the design window (a proxy, not a replacement for Q3D). + +v2 (`mom_capacitance_gds`) works on the exact GDS polygons with the whole ground plane and an adaptive quadtree mesh +(cells no larger than `grade` x their distance to a metal edge, edge cells down to ~1/3 of the smallest gap). On the +gallery designs it reaches 5-6 % (NCAP, star) and 12 % (concentric) median error with no training, vs 14-32 % for v1. +""" + +from __future__ import annotations + +import os +import queue +import threading +from concurrent.futures import ThreadPoolExecutor +from functools import partial + +import numpy as np +import shapely +from scipy.linalg import cho_factor, cho_solve +from scipy.spatial import cKDTree + +EPS0_FF_PER_UM = 8.8541878128e-3 +SELF = 4 * np.log(1 + np.sqrt(2)) +NUM_THREADS = 0 # threads of the mesh / assembly pool and of the concurrent v3-rich solves; 0 = torch.get_num_threads() +_LOCK = threading.Lock() +_POOL: list = [] # [(threads, executor)] +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_POOL.clear) # a forked worker must not reuse the parent's pool threads + + +def _nthreads() -> int: + if NUM_THREADS: + return NUM_THREADS + try: + import torch + except ImportError: + return 1 + return torch.get_num_threads() + + +def _run(tasks: list) -> list: + """Results of the zero-argument callables in order, on the thread pool when more than one thread is allowed (numpy + ufuncs and shapely's vectorised functions release the GIL). Tasks never wait on other pool tasks.""" + n = _nthreads() + if n < 2 or len(tasks) < 2: + return [t() for t in tasks] + with _LOCK: + if not _POOL or _POOL[0][0] != n: + _POOL[:] = [(n, ThreadPoolExecutor(n, thread_name_prefix="tlsq-mom"))] + pool = _POOL[0][1] + return list(pool.map(lambda t: t(), tasks)) + + +def _spans(n: int, size: int) -> list: + return [(a, min(a + size, n)) for a in range(0, n, size)] + + +class _Geoms: + """Private copies of geometries (exact WKB round trip) handed out to one pool task at a time and made on demand: GEOS + prepared geometries keep mutable search state and must not be shared between threads (nor with a concurrent solve).""" + + def __init__(self, geoms: list): + self.wkb, self.free = shapely.to_wkb(geoms), queue.SimpleQueue() + + def get(self) -> list: + try: + return self.free.get_nowait() + except queue.Empty: + return list(shapely.from_wkb(self.wkb)) + + def put(self, gs: list) -> None: + self.free.put(gs) + + +def _cover(gq, boxes, h, tst, inn): + """Coverage area(box & metal) / h^2 of every box by every metal (m, n), evaluated exactly only where a box straddles a + metal: a box properly inside a metal covers 1 and a box disjoint from it 0 (same decisions as the exact areas). tst + (m, n): metals the box can touch (its parent did); inn (m, n): metals the box lies properly inside (from its parent). + Returns cov, hit (box intersects the metal), inn, and per metal the pieces box & metal where they were computed.""" + m, n = tst.shape + cov, hit, inn = inn.astype(float), inn.copy(), inn.copy() + pcs = [np.empty(n, dtype=object) for _ in range(m)] + work = [(k, ix[a:b]) for k in range(m) for ix in [np.nonzero(tst[k])[0]] for a, b in _spans(len(ix), 256)] + + def task(k, ix): + gs = gq.get() + try: + g = gs[k] + shapely.prepare(g) + b = boxes[ix] + ht = shapely.intersects(g, b) + it = shapely.contains_properly(g, b) + p = shapely.intersection(b[ht & ~it], g) + return ht, it, p, shapely.area(p) + finally: + gq.put(gs) + + for (k, ix), (ht, it, p, a) in zip(work, _run([partial(task, k, ix) for k, ix in work])): + hit[k, ix], inn[k, ix] = ht, it + cov[k, ix[it]] = 1.0 + s = ix[ht & ~it] + cov[k, s] = a / h[s] ** 2 + pcs[k][s] = p + return cov, hit, inn, pcs + + +def _distance(gq, j: int, geoms) -> np.ndarray: + """shapely.distance(geoms, geometry j of the queue), in chunks on the pool.""" + def task(a, b): + gs = gq.get() + try: + return shapely.distance(geoms[a:b], gs[j]) + finally: + gq.put(gs) + return np.concatenate([np.zeros(0)] + _run([partial(task, a, b) for a, b in _spans(len(geoms), 256)])) + + + + +def mom_capacitance(masks: np.ndarray, window_um: float, eps_r: float = 11.45, cells: int = 64) -> np.ndarray: + """masks: (n_cond, R, R) coverage in [0, 1] (channel 0 = ground). Returns the (n_cond, n_cond) Maxwell C in fF.""" + nc, R, _ = masks.shape + f = R // cells + cov = masks.reshape(nc, cells, f, cells, f).mean((2, 4)) # coverage per coarse cell + owner = np.where(cov.max(0) >= 0.5, cov.argmax(0), -1) + ii, jj = np.nonzero(owner >= 0) + lab = owner[ii, jj] + a = window_um / cells + xy = np.stack([(jj + 0.5) * a, (ii + 0.5) * a], 1) + d = np.sqrt(((xy[:, None, :] - xy[None, :, :]) ** 2).sum(-1)) + np.fill_diagonal(d, 1.0) + P = 1.0 / d + np.fill_diagonal(P, SELF / a) + P /= 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2 + B = (lab[:, None] == np.arange(nc)[None, :]).astype(float) # conductor b at 1 V + Q = cho_solve(cho_factor(P, lower=True), B) + C = np.stack([Q[lab == a_].sum(0) for a_ in range(nc)]) # C[a, b] = charge on a with b at 1 V + return 0.5 * (C + C.T) + + +def quadtree_cells(metals: list, bbox, h0: float, h_min: float, grade: float = 2.0, limit: int | None = None): + """Square cells covering the metal polygons: a cell is kept whole when it lies inside one conductor and is no larger + than `grade` x its distance to the nearest metal edge; edge cells are split down to h_min, where they go to the + conductor covering >= 50 % of them. Returns centres (n, 2), sides (n,), owner (n,); None once more than `limit` cells.""" + edges = shapely.union_all([g.boundary for g in metals]) + x0, y0, x1, y1 = bbox + nx, ny = int(np.ceil((x1 - x0) / h0)), int(np.ceil((y1 - y0) / h0)) + gx, gy = np.meshgrid(x0 + h0 * np.arange(nx), y0 + h0 * np.arange(ny)) + xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0) + gq = _Geoms(list(metals) + [edges]) + tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool) + out_c, out_h, out_o, count = [], [], [], 0 + while len(xs): + boxes = shapely.box(xs, ys, xs + h, ys + h) + cov, hit, inn, _ = _cover(gq, boxes, h, tst, inn) + keep = cov.sum(0) > 1e-3 + xs, ys, h, cov, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], hit[:, keep], inn[:, keep] + cx, cy = xs + h / 2, ys + h / 2 + full = cov.max(0) > 0.999 + d = np.full(len(xs), np.inf) # the edge distance only decides for cells inside one conductor + d[full] = _distance(gq, len(metals), shapely.points(cx[full], cy[full])) + leaf = full & (h <= grade * d + 1e-12) + last = h <= h_min * 1.0001 + take_last = last & ~leaf & (cov.max(0) >= 0.5) + acc = leaf | take_last + out_c.append(np.stack([cx[acc], cy[acc]], 1)) + out_h.append(h[acc]) + out_o.append(cov[:, acc].argmax(0)) + count += int(acc.sum()) + if limit is not None and count > limit: + return None + split = ~acc & ~last + hs = h[split] / 2 + xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs]) + ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs]) + h = np.concatenate([hs] * 4) + tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4) + return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o) + + +def anchored_cells(metals: list, h_f: float, grade: float = 2.0, majority: bool = False, limit: int | None = None): + """v3 mesh: quadtree on a lattice anchored to the signal conductors, independent of the chip size and position. + + Finest cells have side h_f; coarse cells are h_f * 2^k on the same lattice (origin = lower-left corner of the + signal conductors' bounding box), so the cells near the conductors do not change when the ground plane grows, + shrinks or the layout is translated. A cell is kept whole when it lies inside one conductor and is no larger than + `grade` x the distance from the cell to the nearest metal edge (cells touching an edge reach h_f); finest-level cells that straddle an edge are cut along the exact + polygon boundaries into one panel per metal (no rounding of gaps to the grid). + Returns centres (n, 2), sizes (n, 2) = (width, height) of each panel, owner (n,); None once the mesh has more + than `limit` cells.""" + edges = shapely.union_all([g.boundary for g in metals]) + sig = metals[1:] if len(metals) > 1 else metals + ax, ay = shapely.union_all(sig).bounds[:2] + X0, Y0, X1, Y1 = shapely.union_all(metals).bounds + span = max(X1 - X0, Y1 - Y0) + K = max(0, int(np.ceil(np.log2(max(span / 16, h_f) / h_f)))) + h0 = h_f * 2**K + ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0)) + ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0)) + gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1)) + xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0) + gq = _Geoms(list(metals) + [edges]) + tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool) + out_c, out_h, out_o, count = [], [], [], 0 + while len(xs): + boxes = shapely.box(xs, ys, xs + h, ys + h) + cov, hit, inn, pcs = _cover(gq, boxes, h, tst, inn) + keep = cov.sum(0) > 1e-3 + xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep] + pcs = [p[keep] for p in pcs] + cx, cy = xs + h / 2, ys + h / 2 + full = cov.max(0) > 0.999 + last = h <= h_f * 1.0001 + d = np.full(len(xs), np.inf) # the edge distance only decides for whole cells above the finest level + far = full & ~last + d[far] = _distance(gq, len(metals), boxes[far]) + leaf = full & (last | (h <= grade * d + 1e-12)) + out_c.append(np.stack([cx[leaf], cy[leaf]], 1)) + out_h.append(np.stack([h[leaf], h[leaf]], 1)) + out_o.append(cov[:, leaf].argmax(0)) + count += int(leaf.sum()) + cut = last & ~leaf + if majority and cut.any(): + take = cut & (cov.max(0) >= 0.5) + out_c.append(np.stack([cx[take], cy[take]], 1)) + out_h.append(np.stack([h[take], h[take]], 1)) + out_o.append(cov[:, take].argmax(0)) + count += int(take.sum()) + cut = cut & False + if cut.any(): + gs = gq.get() + for k, g in enumerate(gs[:-1]): + shapely.prepare(g) + sel = np.nonzero(cut & (cov[k] > 1e-3))[0] + if not len(sel): + continue + pcs_k = pcs[k][sel] # box & metal, computed by _cover (straddling cells only reach this level uncut) + bb = shapely.bounds(pcs_k) + cen = shapely.get_coordinates(shapely.centroid(pcs_k)) + inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1]) + if not inside.all(): + rp = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside])) + cen[~inside] = rp + out_c.append(cen) + out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6)) + out_o.append(np.full(len(sel), k)) + count += len(sel) + gq.put(gs) + if limit is not None and count > limit: + return None + split = ~leaf & ~last + hs = h[split] / 2 + xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs]) + ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs]) + h = np.concatenate([hs] * 4) + tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4) + return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o) + + +def mom_mesh(metals: list, max_cells: int = 8000, h_min: float | None = None, grade: float = 2.0, cells_per_gap: float = 3.0, + mesh: str = "v2", offset: tuple = (0.0, 0.0)): + """Mesh for the thin-film MoM. mesh="v3": conductor-anchored lattice with exact edge panels + (`anchored_cells`); mesh="v2" (default, published priors): the original chip-anchored quadtree (reproduces the published v2 priors). + Returns (centres, sides, owner, h_min).""" + bbox = shapely.union_all(metals).bounds + size = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) + if h_min is None: + gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) + h_min = max(gap / cells_per_gap, size / 4096) + if mesh == "v2" and any(offset): + h0 = size / 16 + bbox = (bbox[0] - offset[0] * h0, bbox[1] - offset[1] * h0, bbox[2] + h0, bbox[3] + h0) + while True: + if mesh == "v3": + r = anchored_cells(metals, h_min, grade, limit=max_cells) + else: + r = quadtree_cells(metals, bbox, size / 16, h_min, grade, limit=max_cells) + if r is not None: + return (*r, h_min) + h_min *= 1.5 if mesh == "v2" else 2.0 # v3: stay on the same lattice + + +def rect_self(a, b): + """Potential at the centre of a uniformly charged a x b rectangle per unit charge, times 4 pi eps (= SELF / a for a + square).""" + r = np.sqrt(a**2 + b**2) + return (2 * a * np.log((b + r) / a) + 2 * b * np.log((a + r) / b)) / (a * b) + + +def _mom_solve_torch(c, h, o, n_metals, eps_r, dev): + """Same assembly and Cholesky solve as `mom_solve`, in float64 torch on `dev` (opt-in via TLSQ_MOM_DEVICE).""" + import torch + + t = lambda x: torch.as_tensor(np.ascontiguousarray(x), dtype=torch.float64, device=dev) # noqa: E731 + wh = np.stack([h, h], 1) if h.ndim == 1 else h + C, WH = t(c), t(wh) + hm = WH.max(1).values + d = torch.cdist(C, C) + d.fill_diagonal_(1.0) + P = 1.0 / d + near = d < 1.5 * torch.maximum(hm[:, None], hm[None, :]) + near.fill_diagonal_(False) + del d + ii, jj = torch.nonzero(near, as_tuple=True) + del near + if len(ii): + off = (torch.arange(3, dtype=torch.float64, device=dev) - 1) / 3 + ox, oy = torch.meshgrid(off, off, indexing="xy") + sx = C[jj, 0, None] + ox.reshape(-1)[None] * WH[jj, 0, None] + sy = C[jj, 1, None] + oy.reshape(-1)[None] * WH[jj, 1, None] + r = torch.sqrt((C[ii, 0, None] - sx) ** 2 + (C[ii, 1, None] - sy) ** 2) + P[ii, jj] = (1.0 / torch.clamp(r, min=1e-9)).mean(1) + P = 0.5 * (P + P.T) + diag = t(rect_self(wh[:, 0], wh[:, 1]) if h.ndim == 2 else SELF / h) + P.diagonal().copy_(diag) + P /= 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2 + B = t((o[:, None] == np.arange(n_metals)[None, :]).astype(float)) + L, info = torch.linalg.cholesky_ex(P) + del P + if int(info): + raise np.linalg.LinAlgError(f"{int(info)}-th leading minor not positive definite") + return torch.cholesky_solve(B, L).cpu().numpy() + + +def _mom_solve_gpu_slot(c, h, o, n_metals, eps_r): + """GPU solve if one of TLSQ_MOM_GPU_SLOTS slots (file locks shared by the worker processes) is free and the solve + fits; None means: solve on the CPU instead.""" + import fcntl + import os + import tempfile + + import torch + + slots = int(os.environ.get("TLSQ_MOM_GPU_SLOTS", "3")) + tag = os.environ.get("SLURM_JOB_ID", "local") + for k in range(slots): + f = open(os.path.join(tempfile.gettempdir(), f"tlsq_gpu_{tag}_{k}.lock"), "w") + try: + fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + f.close() + continue + try: + return _mom_solve_torch(c, h, o, n_metals, eps_r, os.environ["TLSQ_MOM_DEVICE"]) + except RuntimeError as e: # includes torch.OutOfMemoryError + if "out of memory" not in str(e).lower(): + raise + return None + finally: + torch.cuda.empty_cache() + fcntl.flock(f, fcntl.LOCK_UN) + f.close() + return None + + +def _G(x, y): + """Antiderivative of 1 / sqrt(x^2 + y^2) over x and y: x asinh(y / |x|) + y asinh(x / |y|) (0 on the axes).""" + ax, ay = np.abs(x), np.abs(y) + with np.errstate(divide="ignore", invalid="ignore"): + g1 = np.where(ax > 0, x * np.arcsinh(y / np.where(ax > 0, ax, 1.0)), 0.0) + g2 = np.where(ay > 0, y * np.arcsinh(x / np.where(ay > 0, ay, 1.0)), 0.0) + return g1 + g2 + + +def rect_potential(p, cq, wh): + """Exact potential (x 4 pi eps) at points p (n, 2) of uniformly charged rectangles (unit total charge) centred at cq + with sizes wh (n, 2): (1 / (w h)) * integral of 1 / r over the rectangle. Equals rect_self at the centre.""" + x1, x2 = cq[:, 0] - wh[:, 0] / 2 - p[:, 0], cq[:, 0] + wh[:, 0] / 2 - p[:, 0] + y1, y2 = cq[:, 1] - wh[:, 1] / 2 - p[:, 1], cq[:, 1] + wh[:, 1] / 2 - p[:, 1] + return (_G(x2, y2) - _G(x1, y2) - _G(x2, y1) + _G(x1, y1)) / (wh[:, 0] * wh[:, 1]) + + +def _mom_solve_exact_near(c, wh, o, n_metals, eps_r): + """v3 panels: exact rectangle potential for near pairs (d < 1.5 max side) instead of the 3x3 point average. Used only + when the 3x3 system is not positive definite (sliver edge panels on long fine combs), so priors that solved before + are unchanged.""" + P = _assemble(c, wh, rect_self(wh[:, 0], wh[:, 1]), eps_r, rect_potential) + B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float) + return _chol_solve(P, B) + + +def mom_solve(c, h, o, n_metals: int, eps_r: float = 11.45): + """mom_solve_quad; for v3 panels (h of shape (n, 2)) a non-positive-definite system is re-solved with the exact + near field (`_mom_solve_exact_near`).""" + try: + return mom_solve_quad(c, h, o, n_metals, eps_r) + except np.linalg.LinAlgError: + if h.ndim != 2: + raise + print("v3: 3x3 near-field system not positive definite, exact near field", flush=True) + return _mom_solve_exact_near(c, h, o, n_metals, eps_r) + + +def mom_solve_quad(c, h, o, n_metals: int, eps_r: float = 11.45): + """Point-matching solve on a mesh from `mom_mesh`: cell charges Q (n_cells, n_metals) for each conductor at 1 V. + h: square sides (n,) or panel (width, height) (n, 2). Set TLSQ_MOM_DEVICE=cuda to assemble and solve on a GPU.""" + import os + + if os.environ.get("TLSQ_MOM_DEVICE") and SUBSTRATE["model"] == "halfspace": # the torch path has no image correction + Q = _mom_solve_gpu_slot(c, h, o, n_metals, eps_r) + if Q is not None: + return Q + wh = np.stack([h, h], 1) if h.ndim == 1 else h + P = _assemble(c, wh, rect_self(wh[:, 0], wh[:, 1]) if h.ndim == 2 else SELF / h, eps_r, _near_quad) + B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float) + return _chol_solve(P, B) + + +def _near_quad(p, cq, wh): + """Potential (x 4 pi eps) at points p of the panels centred at cq with sizes wh: mean of 1 / r over a 3x3 sample of the + panel (point matching is poor for close, unequal cells).""" + off = (np.arange(3) - 1) / 3 + ox, oy = np.meshgrid(off, off) + sx = cq[:, 0, None] + ox.ravel()[None] * wh[:, 0, None] + sy = cq[:, 1, None] + oy.ravel()[None] * wh[:, 1, None] + r = np.sqrt((p[:, 0, None] - sx) ** 2 + (p[:, 1, None] - sy) ** 2) + return (1.0 / np.maximum(r, 1e-9)).mean(1) + + +def _near_pairs(c, hm): + """Pairs i < j with |c_i - c_j| < 1.5 max(hm_i, hm_j): candidates from k-d trees per cell-size class, kept by the same + floating-point test as the dense mask.""" + n = len(c) + tree, lev, key = cKDTree(c), np.floor(np.log2(hm)), [np.zeros(0, np.int64)] + for L in np.unique(lev): + sel = np.nonzero(lev == L)[0] + pr = cKDTree(c[sel]).sparse_distance_matrix(tree, 1.5 * hm[sel].max() * (1 + 1e-9), output_type="ndarray") + a, b = sel[pr["i"]], pr["j"] + key.append(np.minimum(a, b) * n + np.maximum(a, b)) + key = np.unique(np.concatenate(key)) + ii, jj = key // n, key % n + ok = (ii != jj) & (np.sqrt((c[ii, 0] - c[jj, 0]) ** 2 + (c[ii, 1] - c[jj, 1]) ** 2) < 1.5 * np.maximum(hm[ii], hm[jj])) + return ii[ok], jj[ok] + + +SUBSTRATE = {"model": "slab_open", "t_um": 350.0} # MoM Green's function (PRIOR_SCHEME.md 14.6): "slab_open" (default since 2026-10-10: 350 um substrate, vacuum below), "halfspace" (released models' priors), "slab_pec" +_IMG_CACHE: dict = {} +_IMG_GRID: dict = {} + + +class substrate: + """Context manager: the MoM Green's function inside the block (`SUBSTRATE`): model "slab_open" (default since + 2026-10-10, PRIOR_SCHEME.md 14.6), "halfspace" (the kernel of the priors the released models were trained on) or + "slab_pec"; t_um the substrate thickness (None: unchanged).""" + + def __init__(self, model: str | None, t_um: float | None = None): + self.new = {k: v for k, v in (("model", model), ("t_um", t_um)) if v is not None} + + def __enter__(self): + self.old = dict(SUBSTRATE) + SUBSTRATE.update(self.new) + return self + + def __exit__(self, *exc): + SUBSTRATE.clear() + SUBSTRATE.update(self.old) + + +def _image_correction(d, eps_r: float, exact: bool = False): + """Finite-substrate correction to the half-space kernel 1 / d (same units): sum_n w_n / sqrt(d^2 + D_n^2) for panels on the + top face of a slab of thickness t (SUBSTRATE): "slab_open" = vacuum below (w_n = K^2n + K^(2n-1), D_n = 2 n t, + K = (eps_r - 1) / (eps_r + 1); weights sum to eps_eff - 1, so the kernel tends to the vacuum one for d >> eps_r t), + "slab_pec" = metal backside (w_n = -(1 + K) (-K)^(n-1); weights sum to -1). Images up to K^2n < 1e-4, the remaining + weight as one more image; tabulated on a uniform grid of t / 1000 up to 100 mm and interpolated linearly (dense + assembly), or summed exactly (exact=True: the H-matrix kernel, whose ACA blocks need a smooth kernel). None for the + half-space (the published kernel).""" + m = SUBSTRATE["model"] + if m == "halfspace": + return None + key = (m, float(SUBSTRATE["t_um"]), float(eps_r)) + if key not in _IMG_CACHE: + K, t = (eps_r - 1) / (eps_r + 1), float(SUBSTRATE["t_um"]) + n = np.arange(1, 400) + nmax = int(np.argmax(K ** (2 * n) < 1e-4)) + 1 + n = n[:nmax] + if m == "slab_open": + w, total = K ** (2 * n) + K ** (2 * n - 1), K / (1 - K) + else: + w, total = -(1 + K) * (-K) ** (n - 1), -1.0 + w, D = np.r_[w, total - w.sum()], np.r_[2 * n * t, 2 * (nmax + 1) * t] + du = t / 1000 + u = np.arange(0.0, 1e5 + 2 * du, du) + T = (w[None, :] / np.sqrt(u[:, None] ** 2 + D[None, :] ** 2)).sum(1) + _IMG_CACHE[key] = (du, T, w, D) + du, T = _IMG_CACHE[key][:2] + if exact: + w, D = _IMG_CACHE[key][2:] + d2 = np.asarray(d, float) ** 2 + return sum(wn / np.sqrt(d2 + Dn * Dn) for wn, Dn in zip(w, D)) + if key not in _IMG_GRID: + _IMG_GRID[key] = du * np.arange(len(T)) + return np.interp(d, _IMG_GRID[key], T) + + +def _assemble(c, wh, diag, eps_r: float, near): + """Interaction matrix / (4 pi eps0 eps_eff) for the lower Cholesky factorisation: far pairs 1 / d, near pairs (d < 1.5 + max side) the symmetrised near(p, cq, wh) potential, diagonal `diag`; the same numbers as the dense construction. + Built in row blocks on the pool threads without n x n temporaries, and only the half the factorisation reads: returns + a Fortran-ordered matrix whose lower triangle holds the entries (its upper triangle is not initialised).""" + n = len(c) + k = 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2 + A = np.empty((n, n)) + x, y = c[:, 0], c[:, 1] + + def rows(r0, r1): + d = x[r0:r1, None] - x[None, r0:] + np.multiply(d, d, out=d) + t = y[r0:r1, None] - y[None, r0:] + np.multiply(t, t, out=t) + d += t + np.sqrt(d, out=d) + corr = _image_correction(d, eps_r) + d[np.arange(r1 - r0), np.arange(r1 - r0)] = 1.0 + out = A[r0:r1, r0:] + np.divide(1.0, d, out=out) + if corr is not None: + out += corr + out /= k + + _run([partial(rows, a, b) for a, b in _spans(n, 64)]) + ii, jj = _near_pairs(c, wh.max(1)) + img = _image_correction(np.zeros(1), eps_r) + if len(ii): + A[ii, jj] = 0.5 * (near(c[ii], c[jj], wh[jj]) + near(c[jj], c[ii], wh[ii])) / k + if img is not None: + A[ii, jj] += _image_correction(np.sqrt(((c[ii] - c[jj]) ** 2).sum(1)), eps_r) / k + A[np.arange(n), np.arange(n)] = diag / k if img is None else (diag + img[0]) / k + return A.T + + +def _chol_solve(P, B): + """Cholesky solve with the lower triangle of the Fortran-ordered P from `_assemble`, factorised in place (no copy).""" + return cho_solve(cho_factor(P, lower=True, overwrite_a=True, check_finite=False), B, check_finite=False) + + +def mom_capacitance_gds(metals: list, eps_r: float = 11.45, max_cells: int = 8000, h_min: float | None = None, grade: float = 2.0, + cells_per_gap: float = 3.0, offset: tuple = (0.0, 0.0), mesh: str = "v2"): + """Thin-film MoM on the exact GDS polygons (ground to the chip edge), adaptive quadtree mesh (see `mom_mesh`). + + metals: shapely geometries, one per conductor (index 0 = ground). `offset` (v2 mesh only) shifts the quadtree origin + by that fraction of the coarsest cell. Returns (C fF in the same order, n_cells, h_min).""" + c, h, o, h_min = mom_mesh(metals, max_cells, h_min, grade, cells_per_gap, mesh, offset) + try: + Q = mom_solve(c, h, o, len(metals), eps_r) # v3: exact near field if the 3x3 system is not positive definite + except np.linalg.LinAlgError: + if mesh != "v3": + raise + # cell cap coarser than the finger pitch: cut-panel boxes of different conductors overlap; finest cells as whole + # squares owned by the metal covering >= 50 % (as the v2 mesh), exact near field + print("v3: still not positive definite, majority finest cells", flush=True) + c, h, o = anchored_cells(metals, h_min, grade, majority=True) + Q = _mom_solve_exact_near(c, h, o, len(metals), eps_r) + C = np.stack([Q[o == a].sum(0) for a in range(len(metals))]) + return 0.5 * (C + C.T), len(c), h_min + + +def mom_capacitance_gds_avg(metals: list, n_offsets: int = 4, **kw): + """MoM averaged over quadtree origins (offsets on a diagonal grid of the coarsest cell): removes the part of the + discretisation error that jumps with mesh alignment as the geometry is swept.""" + offs = [(i / n_offsets, ((i * 3) % n_offsets) / n_offsets) for i in range(n_offsets)] + runs = [mom_capacitance_gds(metals, offset=o, mesh="v2", **kw) for o in offs] + return np.mean([r[0] for r in runs], 0), int(np.mean([r[1] for r in runs])), runs[0][2] + + +def _both(f, g): + """(f(), g()), a LinAlgError in place of a result; concurrently (g on a helper thread) when more than one thread is + allowed: the gap/6 and gap/3 solves of v3-rich are independent.""" + def call(fn): + try: + return fn() + except np.linalg.LinAlgError as e: + return e + if _nthreads() < 2: + return call(f), call(g) + with ThreadPoolExecutor(1, thread_name_prefix="tlsq-rich") as ex: + fut = ex.submit(call, g) + a = call(f) + return a, fut.result() + + +def mom_capacitance_gds_rich(metals: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, max_cells: int = 8000, + max_cells_fine: int = 16000, grade: float = 2.0): + """v3 MoM with Richardson extrapolation: solves at gap/cells_per_gap and at half that cell size on the same + conductor-anchored lattice and extrapolates the first-order discretisation error to zero cell size. If the cell + cap forces both meshes to the same resolution, returns the finer solve. If the coarse system is not positive + definite (sliver edge panels badly resolved by the 3x3 near-field rule; ~0.2 % of designs), returns the other + solve alone (fine if the coarse one fails, coarse if the fine one fails). The two solves run concurrently when more + than one thread is allowed. Returns (C, total cells, h of the fine mesh).""" + rf, rc = _both(partial(mom_capacitance_gds, metals, eps_r, max_cells_fine, None, grade, 2 * cells_per_gap, mesh="v3"), + partial(mom_capacitance_gds, metals, eps_r, max_cells, None, grade, cells_per_gap, mesh="v3")) + if isinstance(rf, np.linalg.LinAlgError): + print("v3-rich: fine mesh not positive definite, coarse solve only", flush=True) + if isinstance(rc, np.linalg.LinAlgError): + raise rc + return rc + Cf, nf, hf = rf + if isinstance(rc, np.linalg.LinAlgError): + print("v3-rich: coarse mesh not positive definite, fine solve only", flush=True) + return Cf, nf, hf + Cc, nc, hc = rc + r = hc / hf + C = Cf if r < 1.01 else Cf + (Cf - Cc) / (r - 1) + return C, nc + nf, hf + + +# ---------------------------------------------------------------- flagship prior: strip-merged mesh, H-matrix solve, Richardson +# Resolution-controlled (panels per gap, no small cap), the same conductor-anchored panels as v3 merged along straight +# edges, the exact rectangle potential for near pairs, and for large systems an H-matrix (ACA far field) with +# preconditioned CG instead of the dense Cholesky: O(n log n) time and memory. + +DENSE_MAX = int(os.environ.get("TLSQ_MOM_DENSE_MAX", 12000)) # panels up to which the dense Cholesky is used (faster below this size) +HMAT = dict(leaf=128, eta=2.0, eps=1e-9, tol=1e-12, maxit=1000) # ACA block tolerance (relative Frobenius) and PCG residual + + +def _segments(metals): + segs, verts = [], [] + for g in metals: + for p in getattr(g, "geoms", [g]): + for ring in [p.exterior, *p.interiors]: + xy = np.asarray(ring.coords) + verts.append(xy[:-1]) + segs.append(np.stack([xy[:-1], xy[1:]], 1)) + S = np.concatenate(segs) + return shapely.linestrings(S), S, np.concatenate(verts) + + +def strip_merge(c, wh, o, metals, h_f, lmax_mult: float = 16.0, grade: float = 1.0): + """Merge runs of equal-width panels along the direction of their nearest polygon edge (where the charge density is + translation-invariant) into panels of length <= lmax_mult * h_f and <= grade * distance to the nearest vertex; + the size across the edge is kept. Returns merged (centres, sizes, owners).""" + lines, S, verts = _segments(metals) + near = shapely.STRtree(lines).nearest(shapely.points(c)) + d = S[near, 1] - S[near, 0] + horiz = np.abs(d[:, 0]) >= np.abs(d[:, 1]) + dv, _ = cKDTree(verts).query(c, workers=-1) + allow = np.minimum(lmax_mult * h_f, grade * dv) + out_c, out_wh, out_o = [], [], [] + for axis, mask in ((0, horiz), (1, ~horiz)): + if not mask.any(): + continue + idx = np.nonzero(mask)[0] + other = 1 - axis + key = np.stack([o[idx], np.round(c[idx, other], 4), np.round(wh[idx, other], 4)], 1) + order = np.lexsort([c[idx, axis], key[:, 2], key[:, 1], key[:, 0]]) + idx, key = idx[order], key[order] + same = np.all(key[1:] == key[:-1], 1) + lo, hi = c[idx, axis] - wh[idx, axis] / 2, c[idx, axis] + wh[idx, axis] / 2 + adjacent = same & (np.abs(hi[:-1] - lo[1:]) < 1e-6) + start = 0 + while start < len(idx): + end, length, cap = start, wh[idx[start], axis], allow[idx[start]] + while end + 1 < len(idx) and adjacent[end] and length + wh[idx[end + 1], axis] <= min(cap, allow[idx[end + 1]]): + end += 1 + length += wh[idx[end], axis] + cap = min(cap, allow[idx[end]]) + cc, ww = np.zeros(2), np.zeros(2) + cc[axis], cc[other] = 0.5 * (lo[start] + hi[end]), c[idx[start], other] + ww[axis], ww[other] = hi[end] - lo[start], wh[idx[start], other] + out_c.append(cc) + out_wh.append(ww) + out_o.append(o[idx[start]]) + start = end + 1 + return np.array(out_c), np.array(out_wh), np.array(out_o) + + +def mesh_flagship(metals: list, h: float, max_cells: int, grade: float = 2.0, lmax_mult: float = 16.0, merge_grade: float = 1.0, + majority: bool = False): + """Strip-merged v3 mesh at finest panel h, doubled (same lattice) until the merged mesh has at most max_cells panels. + Returns (centres, sizes, owners, h, raw panel count).""" + while True: + raw = anchored_cells(metals, h, grade, majority=majority, limit=8 * max_cells) + if raw is not None: + c, wh, o = strip_merge(*raw, metals, h, lmax_mult, merge_grade) + if len(c) <= max_cells: + return c, wh, o, h, len(raw[0]) + h *= 2.0 + + +class _Kernel: + """Entries of P / (4 pi eps0 eps_eff) in a permuted panel order: 1 / d for far pairs, the exact rectangle potential + for near pairs (d < 1.5 max side) and rect_self on the diagonal; near and diagonal corrections to 1 / d are held in + a CSR matrix so that any block is 1 / d + N[I, J] (the same numbers as `_assemble` with `rect_potential`).""" + + def __init__(self, c, wh, eps_r, perm): + from scipy.sparse import csr_matrix + + self.x, self.y = c[perm, 0].copy(), c[perm, 1].copy() + self.k = 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2 + self.eps_r = eps_r + self.img = _image_correction(np.zeros(1), eps_r) is not None # finite-substrate image term (exact series in blocks / rows) + n = len(c) + ii, jj = _near_pairs(c, wh.max(1)) + d = np.sqrt(((c[ii] - c[jj]) ** 2).sum(1)) + near = 0.5 * (rect_potential(c[ii], c[jj], wh[jj]) + rect_potential(c[jj], c[ii], wh[ii])) - 1.0 / d + inv = np.empty(n, np.int64) + inv[perm] = np.arange(n) + rows = inv[np.concatenate([ii, jj, np.arange(n)])] + cols = inv[np.concatenate([jj, ii, np.arange(n)])] + vals = np.concatenate([near, near, rect_self(wh[:, 0], wh[:, 1]) - 1.0]) + self.N = csr_matrix((vals, (rows, cols)), shape=(n, n)) + + def block(self, a0, a1, b0, b1): + d = np.sqrt((self.x[a0:a1, None] - self.x[None, b0:b1]) ** 2 + (self.y[a0:a1, None] - self.y[None, b0:b1]) ** 2) + corr = _image_correction(d, self.eps_r, exact=True) + if a0 == b0: + d[np.arange(a1 - a0), np.arange(a1 - a0)] = 1.0 + A = 1.0 / d + if corr is not None: + A += corr + Nb = self.N[a0:a1, b0:b1] + if Nb.nnz: + A += Nb.toarray() + return A / self.k + + def row(self, i, b0, b1): + d = np.sqrt((self.x[i] - self.x[b0:b1]) ** 2 + (self.y[i] - self.y[b0:b1]) ** 2) + r = 1.0 / d + if self.img: + r += _image_correction(d, self.eps_r, exact=True) + Nr = self.N[i, b0:b1] + if Nr.nnz: + r += Nr.toarray()[0] + return r / self.k + + +def _cluster_tree(c, leaf: int): + """Recursive bisection of the panel centres along the longer side of their bounding box at the median: a permutation + making every cluster a contiguous range, and nodes (a, b, lo, hi, left, right).""" + perm, nodes = np.arange(len(c)), [] + + def rec(a, b): + idx = perm[a:b] + lo, hi = c[idx].min(0), c[idx].max(0) + k = len(nodes) + nodes.append([a, b, lo, hi, -1, -1]) + if b - a > leaf: + ax = int(np.argmax(hi - lo)) + perm[a:b] = idx[np.argsort(c[idx, ax], kind="stable")] + m = a + (b - a) // 2 + nodes[k][4], nodes[k][5] = rec(a, m), rec(m, b) + return k + + rec(0, len(c)) + return perm, nodes + + +def _aca(K, a0, a1, b0, b1, eps, max_rank): + """Partial-pivoting adaptive cross approximation of the block (a0:a1, b0:b1) to relative Frobenius accuracy eps: + (U, V) with block ~ U V^T, or None when the rank would exceed max_rank.""" + m, n = a1 - a0, b1 - b0 + U, V, used_r, used_c = [], [], np.zeros(m, bool), np.zeros(n, bool) + i, norm2 = 0, 0.0 + for _ in range(min(m, n, max_rank)): + r = K.row(a0 + i, b0, b1) + for u, v in zip(U, V): + r -= u[i] * v + rm = np.where(used_c, 0.0, np.abs(r)) + j = int(np.argmax(rm)) + if rm[j] == 0.0: + break + v = r / r[j] + u = K.row(b0 + j, a0, a1) # column j of the block = row j of the symmetric kernel + for uu, vv in zip(U, V): + u -= vv[j] * uu + used_r[i], used_c[j] = True, True + nu, nv = float(u @ u), float(v @ v) + norm2 += nu * nv + 2 * sum(float(u @ uu) * float(v @ vv) for uu, vv in zip(U, V)) + U.append(u) + V.append(v) + if nu * nv <= eps**2 * norm2: + break + um = np.where(used_r, 0.0, np.abs(u)) + i = int(np.argmax(um)) + if um[i] == 0.0: + break + else: + return None + return np.stack(U, 1), np.stack(V, 1) + + +class _HMatrix: + """Hierarchical matrix of the panel system: dense blocks for leaf pairs that are not well separated, ACA low-rank + blocks for admissible pairs (min diameter <= eta x distance); only the upper block triangle is stored (symmetric).""" + + def __init__(self, c, wh, eps_r, leaf=128, eta=2.0, eps=1e-9): + self.n = len(c) + self.perm, nodes = _cluster_tree(c, leaf) + self.K = _Kernel(c, wh, eps_r, self.perm) + self.eps = eps + plan = [] + + def leafq(k): + return nodes[k][4] < 0 + + def rec(s, t): + a0, a1, lo_s, hi_s, sl, sr = nodes[s] + b0, b1, lo_t, hi_t, tl, tr = nodes[t] + if s == t: + if leafq(s): + plan.append(("d", a0, a1, a0, a1)) + else: + rec(sl, sl), rec(sr, sr), rec(sl, sr) + return + gap = np.maximum(0.0, np.maximum(lo_s - hi_t, lo_t - hi_s)) + diam = min(np.sqrt(((hi_s - lo_s) ** 2).sum()), np.sqrt(((hi_t - lo_t) ** 2).sum())) + if diam <= eta * np.sqrt((gap**2).sum()): + plan.append(("l", a0, a1, b0, b1)) + elif leafq(s) and leafq(t): + plan.append(("d", a0, a1, b0, b1)) + elif leafq(s): + rec(s, tl), rec(s, tr) + elif leafq(t): + rec(sl, t), rec(sr, t) + else: + for u in (sl, sr): + for v in (tl, tr): + rec(u, v) + + rec(0, 0) + self.dense, self.low = [], [] + + def build(chunk): + out = [] + for kind, a0, a1, b0, b1 in chunk: + if kind == "l": + r = _aca(self.K, a0, a1, b0, b1, eps, max(2, min(a1 - a0, b1 - b0) // 2)) + if r is not None: + out.append(("l", a0, a1, b0, b1, r)) + continue + out.append(("d", a0, a1, b0, b1, self.K.block(a0, a1, b0, b1))) + return out + + for res in _run([partial(build, plan[a:b]) for a, b in _spans(len(plan), 64)]): + for kind, a0, a1, b0, b1, M in res: + (self.low if kind == "l" else self.dense).append((a0, a1, b0, b1, M)) + self.pre = [(a0, a1, cho_factor(D, lower=True)) for a0, a1, b0, _, D in self.dense if a0 == b0] # block Jacobi + self.n_threads = max(1, _nthreads()) + + + def nbytes(self): + return sum(D.nbytes for *_, D in self.dense) + sum(U.nbytes + V.nbytes for *_, (U, V) in self.low) + + def matvec(self, X): + def part(dense, low): + Y = np.zeros_like(X) + for a0, a1, b0, b1, D in dense: + Y[a0:a1] += D @ X[b0:b1] + if a0 != b0: + Y[b0:b1] += D.T @ X[a0:a1] + for a0, a1, b0, b1, (U, V) in low: + Y[a0:a1] += U @ (V.T @ X[b0:b1]) + Y[b0:b1] += V @ (U.T @ X[a0:a1]) + return Y + + T = self.n_threads + if T < 2: + return part(self.dense, self.low) + return sum(_run([partial(part, self.dense[k::T], self.low[k::T]) for k in range(T)])) + + def precondition(self, R): + Z = np.empty_like(R) + for a0, a1, cf in self.pre: + Z[a0:a1] = cho_solve(cf, R[a0:a1], check_finite=False) + return Z + + def pcg(self, B, tol, maxit): + """Conjugate gradients on every right-hand side column at once (independent columns), block-Jacobi preconditioned, + until every column's relative residual is below tol. B and the result are in the permuted order.""" + X, R = np.zeros_like(B), B.copy() + Z = self.precondition(R) + P, rz = Z.copy(), (R * Z).sum(0) + bn = np.sqrt((B * B).sum(0)) + for it in range(maxit): + AP = self.matvec(P) + alpha = rz / (P * AP).sum(0) + X += alpha * P + R -= alpha * AP + res = (np.sqrt((R * R).sum(0)) / bn).max() + if res < tol: + return X, it + 1, res + Z = self.precondition(R) + rz_new = (R * Z).sum(0) + P = Z + (rz_new / rz) * P + rz = rz_new + raise np.linalg.LinAlgError(f"H-matrix PCG did not converge in {maxit} iterations (residual {res:.1e})") + + +def mom_solve_fast(c, wh, o, n_metals: int, eps_r: float = 11.45, dense_max: int | None = None): + """Panel charges Q (n, n_metals) for unit excitation of every conductor, exact near field: dense Cholesky for + n <= dense_max panels (`_mom_solve_exact_near`), otherwise the H-matrix / PCG solve of the same system.""" + n = len(c) + if n <= (DENSE_MAX if dense_max is None else dense_max): + return _mom_solve_exact_near(c, wh, o, n_metals, eps_r) + H = _HMatrix(c, wh, eps_r, HMAT["leaf"], HMAT["eta"], HMAT["eps"]) + B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float)[H.perm] + Xp, _, _ = H.pcg(B, HMAT["tol"], HMAT["maxit"]) + Q = np.empty_like(Xp) + Q[H.perm] = Xp + return Q + + +def _cap_flagship(metals, eps_r, h, max_cells, grade, lmax_mult, merge_grade): + c, wh, o, h, n_raw = mesh_flagship(metals, h, max_cells, grade, lmax_mult, merge_grade) + try: + Q = mom_solve_fast(c, wh, o, len(metals), eps_r) + except np.linalg.LinAlgError: # cut panels of different conductors overlap (lattice coarser than the finger pitch) + print("flagship: system not positive definite, majority finest cells", flush=True) + c, wh, o, h, n_raw = mesh_flagship(metals, h, max_cells, grade, lmax_mult, merge_grade, majority=True) + Q = mom_solve_fast(c, wh, o, len(metals), eps_r) + C = np.stack([Q[o == a].sum(0) for a in range(len(metals))]) + return 0.5 * (C + C.T), len(c), h, n_raw + + +def mom_capacitance_gds_flagship(metals: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, max_cells: int = 250000, + grade: float = 2.0, rich: bool = True, lmax_mult: float = 16.0, merge_grade: float = 1.0): + """Flagship prior: strip-merged conductor-anchored mesh at h_f = max(gap / (2 cells_per_gap), size / 8192) and, with + rich=True, Richardson extrapolation with the mesh at 2 h_f (same lattice), both solved with `mom_solve_fast`. The + resolution is set by cells_per_gap (the fine mesh has 2 cells_per_gap panels across the smallest gap; the coarse + one cells_per_gap); max_cells is only a safety cap on the merged panel count (h doubles until it fits). The two solves + run concurrently when more than one thread is allowed. Returns (C, total panels, h of the fine mesh, info dict).""" + bbox = shapely.union_all(metals).bounds + size = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) + gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) + hf = max(gap / (2 * cells_per_gap), size / 8192) + if not rich: + C, n, h, n_raw = _cap_flagship(metals, eps_r, 2 * hf, max_cells, grade, lmax_mult, merge_grade) + return C, n, h, {"h_target_um": 2 * hf, "min_gap_um": gap, "cap_hit": h > 2 * hf * 1.0001, "raw_cells": n_raw, "extrapolated": False} + rf, rc = _both(partial(_cap_flagship, metals, eps_r, hf, max_cells, grade, lmax_mult, merge_grade), + partial(_cap_flagship, metals, eps_r, 2 * hf, max_cells, grade, lmax_mult, merge_grade)) + for r in (rf, rc): + if isinstance(r, np.linalg.LinAlgError): + raise r + (Cf, nf, h_f, raw_f), (Cc, nc, h_c, raw_c) = rf, rc + r = h_c / h_f + C = Cf if r < 1.01 else Cf + (Cf - Cc) / (r - 1) + info = {"h_target_um": hf, "min_gap_um": gap, "cap_hit": h_f > hf * 1.0001, "raw_cells": raw_f, "coarse_cells": nc, + "extrapolated": bool(r >= 1.01)} + return C, nf + nc, h_f, info diff --git a/src/squadds/ml/capacitance/_core/_tlsq/geometry.py b/src/squadds/ml/capacitance/_core/_tlsq/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..357d691247147e8087420fecf6bc55ab9463d367 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/geometry.py @@ -0,0 +1,256 @@ +"""GDS conductor geometry: exact polygon metrics, separation spectra and spectral shape descriptors. + +Only metal layers are used: (1,0) ground and (1,10) signal conductors. Port stubs (2,0)/(3,0) are ignored. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +import gdstk +import numpy as np +import shapely +from scipy import sparse +from scipy.sparse.linalg import eigsh +from scipy.spatial import cKDTree +from shapely.geometry import MultiPolygon, Polygon + +GROUND_LAYER = (1, 0) +SIGNAL_LAYER = (1, 10) +BOUNDARY_STEP_UM = 0.25 +SEP_BINS_UM = np.geomspace(0.5, 2000.0, 41) +N_FOURIER = 16 +MIC_TOL = [0.01] # inscribed-circle tolerance (um); 0.1 for the approximate token variants (PRIOR_SCHEME.md 14.3.1) +RASTER_PX = 512 +N_EIG = 16 +K_BINS = 48 + + +@dataclass +class Conductors: + N: Polygon + S: Polygon + G: Polygon | MultiPolygon + pocket: Polygon | MultiPolygon # etched region inside the chip (contains N and S) + gap: Polygon | MultiPolygon # pocket minus signal metal (dielectric surface) + chip: Polygon + pads: list = field(default_factory=list) # extra 0 V bodies (merged into G) + + def metals(self) -> dict: + return {"N": self.N, "S": self.S, "G": self.G} + + +def _valid(geom): + g = shapely.make_valid(geom) + polys = [p for p in getattr(g, "geoms", [g]) if isinstance(p, (Polygon, MultiPolygon))] + return shapely.union_all(polys) + + +def load_conductors(gds_path) -> Conductors: + lib = gdstk.read_gds(str(gds_path)) + cell = lib.top_level()[0] + to_um = lib.unit / 1e-6 + sig = [p for p in cell.polygons if (p.layer, p.datatype) == SIGNAL_LAYER] + gnd = [p for p in cell.polygons if (p.layer, p.datatype) == GROUND_LAYER] + if len(sig) < 2 or len(gnd) != 1: + raise ValueError(f"expected >=2 signal + 1 ground polygons, got {len(sig)} + {len(gnd)}") + polys = [_valid(Polygon(p.points * to_um)) for p in sig] + if len(polys) == 2: + N, S = polys + pads = [] + else: + # multi-terminal (exp12): GDS order is not the net order. S = star at the origin; N = body fed by the + # single port stub; the remaining pads are held at 0 V in the solve and are merged into ground. + port = shapely.union_all([Polygon(p.points * to_um) for p in cell.polygons if (p.layer, p.datatype) != SIGNAL_LAYER and p.layer != GROUND_LAYER[0]]) + s = next((i for i, g in enumerate(polys) if g.contains(shapely.Point(0, 0))), int(np.argmax([g.area for g in polys]))) + n = min((i for i in range(len(polys)) if i != s), key=lambda i: polys[i].distance(port)) + N, S = polys[n], polys[s] + pads = [g for i, g in enumerate(polys) if i not in (n, s)] + G0 = _valid(Polygon(gnd[0].points * to_um)) + if abs(G0.area - gnd[0].area() * to_um**2) > 1e-6 * G0.area: + raise ValueError("ground polygon area changed during repair") + chip = shapely.box(*G0.bounds) + pocket = chip.difference(G0) + G = shapely.union_all([G0, *pads]) if pads else G0 + gap = pocket.difference(N).difference(S) + for g in pads: + gap = gap.difference(g) + return Conductors(N, S, G, pocket, gap, chip, pads) + + +def sample_boundary(geom, step: float = BOUNDARY_STEP_UM) -> np.ndarray: + rings = [] + for poly in getattr(geom, "geoms", [geom]): + rings += [poly.exterior, *poly.interiors] + pts = [] + for r in rings: + n = max(int(np.ceil(r.length / step)), 4) + pts.append(shapely.get_coordinates(shapely.line_interpolate_point(r, np.linspace(0, r.length, n, endpoint=False)))) + return np.concatenate(pts) + + +def boundaries(c: Conductors) -> dict[str, np.ndarray]: + # ground edge = boundary of the etched pocket + g = [sample_boundary(c.pocket)] + [sample_boundary(p) for p in c.pads] + return {"N": sample_boundary(c.N), "S": sample_boundary(c.S), "G": np.concatenate(g)} + + +def shape_metrics(poly) -> dict: + hull = poly.convex_hull + x0, y0, x1, y1 = poly.bounds + cx, cy = poly.centroid.x, poly.centroid.y + ixx, iyy, ixy = _second_moments(poly, cx, cy) + evals = np.linalg.eigvalsh([[ixx, ixy], [ixy, iyy]]) + return { + "area": poly.area, + "perimeter": poly.length, + "convex_area": hull.area, + "solidity": poly.area / hull.area, + "compactness": 4 * np.pi * poly.area / poly.length**2, + "bbox_w": x1 - x0, + "bbox_h": y1 - y0, + "cx": cx, + "cy": cy, + "I_major": evals[1], + "I_minor": evals[0], + "elongation": np.sqrt(evals[1] / max(evals[0], 1e-30)), + "inscribed_radius": shapely.maximum_inscribed_circle(poly, MIC_TOL[0]).length if isinstance(poly, Polygon) else np.nan, + "n_vertices": int(shapely.get_num_coordinates(poly)), + "n_holes": int(sum(len(p.interiors) for p in getattr(poly, "geoms", [poly]))), + } + + +def _second_moments(geom, cx, cy) -> tuple[float, float, float]: + ixx = iyy = ixy = 0.0 + for poly in getattr(geom, "geoms", [geom]): + for k, ring in enumerate([poly.exterior, *poly.interiors]): + xy = np.asarray(ring.coords) - (cx, cy) + x, y = xy[:-1, 0], xy[:-1, 1] + xn, yn = xy[1:, 0], xy[1:, 1] + a = x * yn - xn * y + sgn = 1.0 if ring.is_ccw == (k == 0) else -1.0 + ixx += sgn * np.sum(a * (y**2 + y * yn + yn**2)) / 12 + iyy += sgn * np.sum(a * (x**2 + x * xn + xn**2)) / 12 + ixy += sgn * np.sum(a * (x * yn + 2 * x * y + 2 * xn * yn + xn * y)) / 24 + return abs(ixx), abs(iyy), ixy + + +def fourier_descriptors(poly, n_samples: int = 512) -> np.ndarray: + """|c_k|/|c_1| for k=-N..N of the outer contour (translation/rotation/scale invariant).""" + ring = max(getattr(poly, "geoms", [poly]), key=lambda p: p.area).exterior + if not ring.is_ccw: + ring = shapely.reverse(ring) + pts = shapely.get_coordinates(shapely.line_interpolate_point(ring, np.linspace(0, 1, n_samples, endpoint=False), normalized=True)) + c = np.fft.fft(pts[:, 0] + 1j * pts[:, 1]) / n_samples + k = np.r_[np.arange(-N_FOURIER, 0), np.arange(0, N_FOURIER + 1)] + mags = np.abs(c[k]) + mags[k == 0] = 0.0 + return mags / mags[k == 1][0] + + +def separation_spectrum(a_pts: np.ndarray, b_pts: np.ndarray) -> tuple[np.ndarray, dict]: + d, _ = cKDTree(b_pts).query(a_pts) + hist, _ = np.histogram(d, bins=SEP_BINS_UM, weights=np.full(len(d), BOUNDARY_STEP_UM)) + dmin = float(d.min()) + s = {"dmin": dmin, "P_inv": float(np.sum(BOUNDARY_STEP_UM / np.maximum(d, 0.05)))} + for f in (1.05, 1.5, 2.0, 3.0): + s[f"L_{f:g}dmin"] = float(np.sum(d <= f * dmin) * BOUNDARY_STEP_UM) + for d0 in (5.0, 10.0, 20.0): + s[f"L_le{d0:g}um"] = float(np.sum(d <= d0) * BOUNDARY_STEP_UM) + return hist, s + + +def window(c: Conductors) -> tuple[float, float, float]: + """Square raster window around the pocket and signal metal: (x0, y0, side) in µm.""" + x0, y0, x1, y1 = shapely.union(c.N, c.S).buffer(0).bounds + gx0, gy0, gx1, gy1 = c.pocket.bounds + cx, cy = (gx0 + gx1) / 2, (gy0 + gy1) / 2 + side = 1.05 * max(gx1 - gx0, gy1 - gy0, x1 - x0, y1 - y0) + return cx - side / 2, cy - side / 2, side + + +def raster(c: Conductors, npx: int = RASTER_PX) -> tuple[dict[str, np.ndarray], float, tuple[float, float]]: + wx0, wy0, side = window(c) + cx, cy = wx0 + side / 2, wy0 + side / 2 + px = side / npx + xs = cx - side / 2 + (np.arange(npx) + 0.5) * px + ys = cy - side / 2 + (np.arange(npx) + 0.5) * px + X, Y = np.meshgrid(xs, ys) + masks = {} + for k, g in c.metals().items(): + shapely.prepare(g) + masks[k] = shapely.contains_xy(g, X, Y) + return masks, px, (cx - side / 2, cy - side / 2) + + +def radial_power_spectrum(img: np.ndarray, px: float) -> tuple[np.ndarray, np.ndarray]: + n = img.shape[0] + F = np.fft.fftshift(np.fft.fft2(img - img.mean())) + P = np.abs(F) ** 2 / img.size + k = np.fft.fftshift(np.fft.fftfreq(n, d=px)) + KX, KY = np.meshgrid(k, k) + kr = np.hypot(KX, KY).ravel() + edges = np.geomspace(1.0 / (n * px), 0.5 / px, K_BINS + 1) + idx = np.digitize(kr, edges) - 1 + ok = (idx >= 0) & (idx < K_BINS) + s = np.bincount(idx[ok], weights=P.ravel()[ok], minlength=K_BINS) + cnt = np.bincount(idx[ok], minlength=K_BINS) + return np.sqrt(edges[1:] * edges[:-1]), np.where(cnt > 0, s / np.maximum(cnt, 1), np.nan) + + +def dirichlet_eigenvalues(mask: np.ndarray, px: float, k: int = N_EIG) -> np.ndarray: + """Lowest Dirichlet Laplacian eigenvalues of a pixel mask (Shape-DNA), in um^-2.""" + idx = -np.ones(mask.shape, dtype=np.int64) + ii, jj = np.nonzero(mask) + n = len(ii) + if n < 4 * k: + return np.full(k, np.nan) + idx[ii, jj] = np.arange(n) + rows, cols = [np.arange(n)], [np.arange(n)] + vals = [np.full(n, 4.0)] + for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)): + ni, nj = ii + di, jj + dj + inside = (ni >= 0) & (ni < mask.shape[0]) & (nj >= 0) & (nj < mask.shape[1]) + nb = np.full(n, -1) + nb[inside] = idx[ni[inside], nj[inside]] + ok = nb >= 0 + rows.append(np.arange(n)[ok]) + cols.append(nb[ok]) + vals.append(-np.ones(ok.sum())) + L = sparse.csc_matrix((np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n)) + ev = eigsh(L, k=k, sigma=0, which="LM", return_eigenvectors=False) + return np.sort(ev) / px**2 + + +def geometry_record(gds_path) -> tuple[dict, dict]: + return geometry_record_conductors(load_conductors(gds_path)) + + +def geometry_record_conductors(c: Conductors) -> tuple[dict, dict]: + """Descriptors of a (N, S, G) conductor triple; for multi-conductor queries N/S are the queried pair, G the rest.""" + scalars, arrays = {}, {} + for name, g in (("N", c.N), ("S", c.S), ("pocket", c.pocket)): + for k, v in shape_metrics(g).items(): + scalars[f"{name}_{k}"] = float(v) + arrays[f"fourier_{name}"] = fourier_descriptors(g) + scalars["gap_area"] = c.gap.area + scalars["chip_w"], scalars["chip_h"] = c.chip.bounds[2] - c.chip.bounds[0], c.chip.bounds[3] - c.chip.bounds[1] + scalars["G_area"] = c.G.area + + b = boundaries(c) + for a, t in (("N", "S"), ("S", "N"), ("N", "G"), ("G", "N"), ("S", "G"), ("G", "S")): + hist, s = separation_spectrum(b[a], b[t]) + arrays[f"sep_{a}{t}"] = hist + scalars.update({f"sep_{a}{t}_{k}": v for k, v in s.items()}) + + masks, px, origin = raster(c) + scalars["raster_px_um"] = px + metal = (masks["N"] | masks["S"] | masks["G"]).astype(np.float64) + k, P = radial_power_spectrum(metal, px) + arrays["psd_k"], arrays["psd_metal"] = k, P + arrays["psd_NS"] = radial_power_spectrum(masks["N"].astype(float) - masks["S"].astype(float), px)[1] + for name in ("N", "S"): + arrays[f"eig_{name}"] = dirichlet_eigenvalues(masks[name], px) + scalars[f"{name}_raster_area_err"] = float(masks[name].sum() * px**2 / getattr(c, name).area - 1) + arrays["sep_bins_um"] = SEP_BINS_UM + return scalars, arrays diff --git a/src/squadds/ml/capacitance/_core/_tlsq/uge/__init__.py b/src/squadds/ml/capacitance/_core/_tlsq/uge/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b6689b8e89b04c8f16ebc3e1102af4190fb8d841 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/uge/__init__.py @@ -0,0 +1,5 @@ +"""Universal GDS Embedding framework: GDS -> scene -> scene graph (+ physics-proxy plugins) -> universal vector / GNN. + +The recipe is dataset-agnostic; what a user adapts is (1) the layer map / net naming of their GDS, (2) the physics proxy +plugin that fits their observable (capacitance, resonance frequency, kappa, ...), and (3) the target adapter. +""" diff --git a/src/squadds/ml/capacitance/_core/_tlsq/uge/blocks.py b/src/squadds/ml/capacitance/_core/_tlsq/uge/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..d67c8090c9650257091cbdb06d589c06bdaa8bb4 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/uge/blocks.py @@ -0,0 +1,526 @@ +"""Physics-agnostic geometry blocks: node (per conductor), edge (per conductor pair) and global features, all in +physical units (log µm, ratios) so that nothing is fitted to a dataset.""" + +from __future__ import annotations + +import hashlib +import os +import pickle +from collections.abc import Mapping +from pathlib import Path + +import numpy as np +import shapely +from scipy.special import ellipk +from scipy.spatial import cKDTree + +from .. import geometry as _geometry +from ..embed.proxy import _nthreads +from ..geometry import fourier_descriptors, sample_boundary, shape_metrics +from .scene import Scene + +GRAN_R_UM = np.geomspace(0.25, 100.0, 16) +SEP_EDGES_UM = np.geomspace(0.5, 2000.0, 11) +MOMENTS = (0.5, 1.0, 2.0) +STEP_UM = 0.25 + + +def _log(x): + return float(np.log(max(float(x), 1e-9))) + + +def region(scene: Scene, i: int): + """The shape that carries conductor i's edge: the etched pocket for the ground net, the metal otherwise.""" + return scene.pocket if scene.conductors[i].role == "ground" else scene.conductors[i].geom + + +def granulometry(g) -> np.ndarray: + a0 = g.area + return np.array([g.buffer(-r, quad_segs=4).area / a0 if a0 > 0 else 0.0 for r in GRAN_R_UM]) + + +def node_features(scene: Scene, i: int) -> dict: + g = region(scene, i) + m = shape_metrics(g) + f = {"role_ground": float(scene.conductors[i].role == "ground"), + "log_area": _log(m["area"]), "log_perimeter": _log(m["perimeter"]), "compactness": m["compactness"], + "solidity": m["solidity"], "log_min_halfwidth": _log(m["inscribed_radius"]), + "log_aspect": abs(_log(m["bbox_w"]) - _log(m["bbox_h"])), "log_elongation": _log(m["elongation"]), + "log_Imajor_over_A2": _log(m["I_major"] / max(m["area"], 1e-9) ** 2), "n_holes": float(m["n_holes"]), + "log_width": _log(2 * m["area"] / m["perimeter"])} + for j, v in enumerate(fourier_descriptors(g)): + f[f"fourier_{j:02d}"] = float(np.log1p(50 * v)) + for j, v in enumerate(granulometry(g)): + f[f"gran_{j:02d}"] = float(v) + return f + + +def _kratio(m): + m = np.clip(m, 1e-12, 1 - 1e-12) + return ellipk(1 - m) / ellipk(m) + + +TOKEN_VARIANTS = {"exact": None, "td16": dict(d_far=100.0, k=16), "td64": dict(d_far=100.0, k=64), "tc600": dict(crop=600.0)} +TOKEN_VARIANT: dict = {"name": "exact"} # PRIOR_SCHEME.md 14.3; "exact" = the published tokens + + +def set_token_variant(name: str) -> None: + from ..geometry import MIC_TOL + + assert name in TOKEN_VARIANTS, name + TOKEN_VARIANT["name"] = name + MIC_TOL[0] = 0.01 if name == "exact" else 0.1 + + +def _block_distances(pts: np.ndarray, tree) -> tuple: + """Distances from the samples of a to b (k-d tree) for the active token variant, with weights (multiples of the + sample step): the samples are grouped into consecutive blocks of k; a block whose first sample is farther than d_far + from b is represented by that sample with weight = block size, the other blocks sample by sample. crop: blocks whose + first sample is farther than the crop distance are dropped (their representatives kept if every block is dropped).""" + v = TOKEN_VARIANTS[TOKEN_VARIANT["name"]] + k = v.get("k", 64) + r = v.get("crop", v.get("d_far")) + rep = np.arange(0, len(pts), k) + d_rep, _ = tree.query(pts[rep], workers=_nthreads()) + size = np.diff(np.r_[rep, len(pts)]) + far = d_rep > r + near_pts = np.repeat(~far, size) + d_near, _ = tree.query(pts[near_pts], workers=_nthreads()) + if "crop" in v: + if not near_pts.any(): + return d_rep, size.astype(float) + return d_near, np.ones(len(d_near)) + return np.r_[d_rep[far], d_near], np.r_[size[far].astype(float), np.ones(len(d_near))] + + +def edge_features(scene: Scene, i: int, j: int, bpts: dict, widths: dict) -> dict: + """Symmetric pair features: separation spectrum (both directions averaged), minimum gap, coupling moments and the + coplanar-strip conformal-map coupling (Gevorgian modulus; the ground net is treated as infinitely wide).""" + f = {"is_ground_pair": float("ground" in (scene.conductors[i].role, scene.conductors[j].role))} + hist = np.zeros(len(SEP_EDGES_UM) - 1) + mom = np.zeros(len(MOMENTS)) + cps = 0.0 + dmin = np.inf + for a, b in ((i, j), (j, i)): + if TOKEN_VARIANT["name"] != "exact": # approximate tokens (PRIOR_SCHEME.md 14.3) + d, wq = _block_distances(bpts[a], cKDTree(bpts[b])) + dmin = min(dmin, d.min()) + hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=STEP_UM * wq)[0] + dd = np.maximum(d, 0.05) + mom += 0.5 * np.array([np.sum(STEP_UM * wq * dd ** (-p)) for p in MOMENTS]) + w1, w2 = widths[a], widths[b] + if np.isinf(w1) or np.isinf(w2): + wf = w2 if np.isinf(w1) else w1 + mm = dd / (dd + wf) + else: + mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) + cps += 0.5 * np.sum(STEP_UM * wq * _kratio(mm)) + continue + d, _ = cKDTree(bpts[b]).query(bpts[a], workers=_nthreads()) + dmin = min(dmin, d.min()) + hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0] + dd = np.maximum(d, 0.05) + mom += 0.5 * np.array([np.sum(STEP_UM * dd ** (-p)) for p in MOMENTS]) + w1, w2 = widths[a], widths[b] + if np.isinf(w1) or np.isinf(w2): + wf = w2 if np.isinf(w1) else w1 + mm = dd / (dd + wf) + else: + mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) + cps += 0.5 * np.sum(STEP_UM * _kratio(mm)) + f["log_dmin"] = _log(dmin) + for k, v in enumerate(hist): + f[f"sep_{k:02d}"] = float(np.log1p(v)) + for p, v in zip(MOMENTS, mom): + f[f"mom_{p:g}"] = _log(v) + f["log_cps"] = _log(cps) + f["_cps"] = cps # raw, used for shielding shares + return f + + +TREE_LEAFSIZE = 32 # nearest distances do not depend on the leaf size (cKDTree's own distance arithmetic); 32 is fastest +NN_KERNEL: dict = {"on": os.environ.get("TLSQ_NN_KERNEL", "1") == "1"} # numba exact NN (nnk.py), probe-verified + + +def _tree(P: np.ndarray): + """Nearest-sample structure of one conductor: the numba kernel when its probe reproduces cKDTree here, else cKDTree.""" + if NN_KERNEL["on"]: + try: + from . import nnk + except ImportError: + nnk = None + if nnk is not None and nnk.available(): + return nnk.Tree(P) + return cKDTree(P, leafsize=TREE_LEAFSIZE) + + +def _dist(tree, X: np.ndarray) -> np.ndarray: + return tree.query(X)[0] if isinstance(tree, cKDTree) else tree.dist(X) + + +_EDGES_HI = np.r_[SEP_EDGES_UM[:-1], np.nextafter(SEP_EDGES_UM[-1], np.inf)] # np.histogram: last bin closed +_CHUNK = 1 << 20 # distances per task (rows x samples) + + +def _dir_stats(X: np.ndarray, trees: list, bs: list, w1: float, widths: dict) -> tuple: + """edge_features' per-direction statistics of the samples X of one conductor against each conductor in bs (all signal, + or the ground alone): minimum distance, histogram counts, the three moment sums and the conformal sum. The same + element-wise operations and pairwise row sums as edge_features (bit-identical).""" + nb = len(bs) + D = np.empty((nb, len(X))) + for r, b in enumerate(bs): + D[r] = _dist(trees[b], X) + dmin = D.min(1) + k = np.searchsorted(_EDGES_HI, D, side="right") + k += (12 * np.arange(nb))[:, None] + cnt = np.bincount(k.ravel(), minlength=12 * nb).reshape(nb, 12)[:, 1:11] + del k + dd = np.maximum(D, 0.05, out=D) + mom = np.stack([np.sum(STEP_UM * dd ** (-p), axis=1) for p in MOMENTS], 1) + w2 = np.array([widths[b] for b in bs])[:, None] + if np.isinf(w1): + mm = dd / (dd + w2) + elif np.isinf(w2).any(): + mm = dd / (dd + w1) + else: + mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) + cps = np.sum(STEP_UM * _kratio(mm), axis=1) + return dmin, cnt, mom, cps + + +# "bitwise" (default; training / reproduction): every feature bit-identical to the published code. "numex" (numerically exact; +# inference): node features and signal-signal directions computed once per class of translated copies (same shape to 1e-6 +# um, same offset) and shared; values differ from bitwise in the last bits only (agents/embedspeed/RESULTS.md). +EMBED_MODE: dict = {"mode": os.environ.get("TLSQ_EMBED_MODE", "bitwise")} +FAR_DECIMATION: dict = {"k": 0, "d_far": 100.0} +# Edge storage: False (default; training) = a dict per pair; True (inference) = EdgeTable, one float64 array per key. +EDGE_TABLE: dict = {"on": os.environ.get("TLSQ_EDGE_TABLE", "0") == "1"} + + +class EdgeTable(Mapping): + """Read-only complete-graph edges: pairs i < j in combinations order, one float64 column per key (same values as the + dict per pair; `npcols` are returned as numpy float64, the others as Python floats). table[(i, j)] builds that pair's + dict on request; matrix(keys) gives the (P, len(keys)) array without building any dict.""" + + def __init__(self, n: int, cols: dict, npcols=()): + self.n, self.cols, self.npcols = n, cols, frozenset(npcols) + + def _r(self, p) -> int: + i, j = int(p[0]), int(p[1]) + if not 0 <= i < j < self.n: + raise KeyError(p) + return i * (2 * self.n - i - 1) // 2 + j - i - 1 + + def __getitem__(self, p) -> dict: + r = self._r(p) + return {k: (v[r] if k in self.npcols else float(v[r])) for k, v in self.cols.items()} + + def __iter__(self): + return ((i, j) for i in range(self.n) for j in range(i + 1, self.n)) + + def __len__(self) -> int: + return self.n * (self.n - 1) // 2 + + def matrix(self, keys, dtype=np.float32) -> np.ndarray: + if not len(self): + return np.zeros((0, len(keys)), dtype) + return np.stack([self.cols[k] for k in keys], 1).astype(dtype) + + def with_cols(self, new: dict, drop=(), npcols=()) -> "EdgeTable": + cols = {k: v for k, v in self.cols.items() if k not in drop} + return EdgeTable(self.n, {**cols, **new}, (self.npcols | frozenset(npcols)) - frozenset(drop)) + + +def edge_matrix(edges, keys, n: int, dtype=np.float32) -> np.ndarray: + """(P, len(keys)) array of the edge features (pairs i < j): the table's columns, or the per-pair dicts as before.""" + if isinstance(edges, EdgeTable): + return edges.matrix(keys, dtype) + pairs = [(i, j) for i in range(n) for j in range(i + 1, n)] + 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 + + +def _dir_stats_far(X: np.ndarray, trees: list, bs: list, w1: float, widths: dict) -> tuple: + """Approximate _dir_stats (block decimation of PRIOR_SCHEME.md 14.3.1): blocks of k consecutive samples of a whose first + sample is farther than d_far from b are represented by that sample with weight k (the last block by its size). Distances + per row (far representatives, then the near samples), statistics for the whole chunk at once (weighted sums).""" + k, r = FAR_DECIMATION["k"], FAR_DECIMATION["d_far"] + rep = np.arange(0, len(X), k) + size = np.diff(np.r_[rep, len(X)]) + nb = len(bs) + Xr = X[rep] + ds, ws, rows = [], [], [] + for row, b in enumerate(bs): + d_rep = _dist(trees[b], Xr) + far = d_rep > r + if far.all(): + d, wq = d_rep, size.astype(float) + else: + near = np.repeat(~far, size) + d = np.r_[d_rep[far], _dist(trees[b], X[near])] + wq = np.r_[size[far].astype(float), np.ones(int(near.sum()))] + ds.append(d) + ws.append(wq) + rows.append(np.full(len(d), row)) + d, wq, rid = np.concatenate(ds), np.concatenate(ws), np.concatenate(rows) + starts = np.r_[0, np.cumsum([len(x) for x in ds])[:-1]] + dmin = np.minimum.reduceat(d, starts) + kb = np.searchsorted(_EDGES_HI, d, side="right") + cnt = np.rint(np.bincount(rid * 12 + kb, weights=wq, minlength=12 * nb)).astype(np.int64).reshape(nb, 12)[:, 1:11] + dd = np.maximum(d, 0.05) + mom = np.stack([np.bincount(rid, weights=STEP_UM * wq * dd ** (-p), minlength=nb) for p in MOMENTS], 1) + w2 = np.array([widths[b] for b in bs])[rid] + if np.isinf(w1): + mm = dd / (dd + w2) + elif np.isinf(w2).any(): + mm = dd / (dd + w1) + else: + mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) + cps = np.bincount(rid, weights=STEP_UM * wq * _kratio(mm), minlength=nb) + return dmin, cnt, mom, cps + + +def _pmap(fn, items: list, threads: int) -> list: + if threads < 2 or len(items) < 2: + return [fn(x) for x in items] + from concurrent.futures import ThreadPoolExecutor + + with ThreadPoolExecutor(threads, thread_name_prefix="tlsq-edges") as ex: + return list(ex.map(fn, items)) + + +# Optional persistent cache (exact): per-body node features and per-direction pair statistics, keyed by the body's region +# (WKB) and role, under a key of this code, the parameters and the machine / library versions (a value is reused only where +# this machine would recompute it bit for bit). Off unless TLSQ_EMBED_CACHE (or EMBED_CACHE["dir"]) names a directory. +EMBED_CACHE: dict = {"dir": os.environ.get("TLSQ_EMBED_CACHE") or None} + + +def _code_key() -> str: + import platform + + import scipy + + h = hashlib.sha256() + for f in (__file__, _geometry.__file__): + h.update(Path(f).read_bytes()) + h.update(repr((platform.machine(), platform.system(), np.__version__, scipy.__version__, shapely.__version__, STEP_UM, + SEP_EDGES_UM.tolist(), MOMENTS, TREE_LEAFSIZE, TOKEN_VARIANT["name"], EMBED_MODE["mode"], + NN_KERNEL["on"])).encode()) + return h.hexdigest()[:24] + + +def body_keys(scene: Scene) -> list: + return [hashlib.sha256(c.role.encode() + shapely.to_wkb(region(scene, i))).hexdigest()[:32] + for i, c in enumerate(scene.conductors)] + + +class _Cache: + def __init__(self, root): + self.d = Path(root) / _code_key() + for sub in ("dir", "node"): + (self.d / sub).mkdir(parents=True, exist_ok=True) + + def _put(self, path: Path, write): + tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + with open(tmp, "wb") as fh: + write(fh) + os.replace(tmp, path) + + def nodes(self, keys: list) -> dict: + out = {} + for i, k in enumerate(keys): + p = self.d / "node" / f"{k}.pkl" + if p.exists(): + out[i] = pickle.loads(p.read_bytes()) + return out + + def put_node(self, key: str, f: dict): + self._put(self.d / "node" / f"{key}.pkl", lambda fh: pickle.dump(f, fh, protocol=5)) + + def rows(self, ka: str): + p = self.d / "dir" / f"{ka}.npz" + if not p.exists(): + return None + z = np.load(p) + return {str(k): r for r, k in enumerate(z["keys"])}, z["dmin"], z["cnt"], z["mom"], z["cps"] + + def put_rows(self, ka: str, keys: list, dmin, cnt, mom, cps): + old = self.rows(ka) + if old is not None: + idx, *arr = old + ks = set(keys) + extra = [r for k, r in idx.items() if k not in ks] + keys = list(keys) + [k for k, r in idx.items() if k not in ks] + dmin, cnt, mom, cps = (np.concatenate([x, y[extra]]) for x, y in zip((dmin, cnt, mom, cps), arr)) + self._put(self.d / "dir" / f"{ka}.npz", + lambda fh: np.savez(fh, keys=np.array(keys), dmin=dmin, cnt=cnt, mom=mom, cps=cps)) + + + def trim(self): + """Size bound (TLSQ_EMBED_CACHE_MB): the least recently written entries are removed down to 80 % of the bound.""" + mb = os.environ.get("TLSQ_EMBED_CACHE_MB") + if not mb: + return + lim = float(mb) * 2**20 + files = [e for sub in ("dir", "node") for e in os.scandir(self.d / sub) if e.is_file()] + tot = sum(e.stat().st_size for e in files) + if tot <= lim: + return + for e in sorted(files, key=lambda e: e.stat().st_mtime): + if tot <= 0.8 * lim: + break + try: + tot -= e.stat().st_size + os.remove(e.path) + except OSError: + pass + + +def _cache(): + return _Cache(EMBED_CACHE["dir"]) if EMBED_CACHE["dir"] else None + + +def shape_classes(scene: Scene, bpts: dict | None = None) -> tuple: + """Translation classes of the signal bodies (numex mode): class id per conductor (-1 = ground, its own class) from the + coordinates relative to the bounding-box corner rounded to 1e-6 um and the ring structure, and, with bpts, from the + boundary samples relative to that corner rounded to 1e-9 um (a translated copy can get one sample more or fewer when a + ring length is a multiple of the step); integer origins (1e-6 um).""" + ids, cid, org = {}, np.full(scene.n, -1), np.zeros((scene.n, 2), np.int64) + for i, c in enumerate(scene.conductors): + if c.role == "ground": + continue + g = region(scene, i) + o = np.array(g.bounds[:2]) + rings = [len(r.coords) for q in getattr(g, "geoms", [g]) for r in (q.exterior, *q.interiors)] + h = hashlib.sha1(repr((c.role, g.geom_type, rings)).encode() + (np.round(shapely.get_coordinates(g) - o, 6) + 0.0).tobytes()) + if bpts is not None: + h.update((np.round(bpts[i] - o, 9) + 0.0).tobytes()) + cid[i] = ids.setdefault(h.hexdigest(), len(ids)) + org[i] = np.rint(o * 1e6).astype(np.int64) + return cid, org + + +def node_features_all(scene: Scene, keys: list | None = None) -> list: + """[node_features(scene, i) for every conductor], threads over the conductors, reusing the persistent cache (numex: + once per translation class).""" + c = _cache() + keys = keys if keys is not None or c is None else body_keys(scene) + hit = c.nodes(keys) if c else {} + miss = [i for i in range(scene.n) if i not in hit] + rep = {} + if EMBED_MODE["mode"] == "numex": + cid = shape_classes(scene)[0] + first = {} + rep = {i: first.setdefault(cid[i], i) for i in miss if cid[i] >= 0} + rep = {i: r for i, r in rep.items() if r != i} + 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()))) + new.update({i: dict(new[r]) for i, r in rep.items()}) + if c: + for i, f in new.items(): + c.put_node(keys[i], f) + c.trim() + return [hit[i] if i in hit else new[i] for i in range(scene.n)] + + +def edge_features_all(scene: Scene, bpts: dict, widths: dict, keys: list | None = None) -> dict: + """{(i, j): edge_features(scene, i, j, bpts, widths)} for every pair i < j, bit-identical, batched: one k-d tree per + conductor, every direction a -> b as rows of one distance array per (a, chunk of b), threads over the chunks (the + queries and ufuncs release the GIL); directions found in the persistent cache are not recomputed.""" + n = scene.n + pairs = [(i, j) for i in range(n) for j in range(i + 1, n)] + if TOKEN_VARIANT["name"] != "exact" or n < 2: + return {(i, j): edge_features(scene, i, j, bpts, widths) for i, j in pairs} + th = _nthreads() + DM, CP = np.empty((n, n)), np.empty((n, n)) + CN, MO = np.empty((n, n, 10), np.int64), np.empty((n, n, len(MOMENTS))) + c = _cache() if not FAR_DECIMATION["k"] else None + if c and keys is None: + keys = body_keys(scene) + todo = {a: [b for b in range(n) if b != a] for a in range(n)} + if c: + for a in range(n): + got = c.rows(keys[a]) + if got is None: + continue + idx, dm, cn, mo, cp = got + have = [b for b in todo[a] if keys[b] in idx] + r = [idx[keys[b]] for b in have] + DM[a, have], CN[a, have], MO[a, have], CP[a, have] = dm[r], cn[r], mo[r], cp[r] + todo[a] = [b for b in todo[a] if keys[b] not in idx] + share = None + if EMBED_MODE["mode"] == "numex": + cid, org = shape_classes(scene, bpts) + A, B = np.nonzero((cid[:, None] >= 0) & (cid[None, :] >= 0) & ~np.eye(n, dtype=bool)) + K = np.c_[cid[A], cid[B], org[B] - org[A]] + _, first, inv = np.unique(K, axis=0, return_index=True, return_inverse=True) + R = first[inv.ravel()] + share = (A, B, A[R], B[R]) + drop = np.zeros((n, n), bool) + drop[A[R != np.arange(len(A))], B[R != np.arange(len(A))]] = True + todo = {a: [b for b in bs if not drop[a, b]] for a, bs in todo.items()} + tasks = [] + for a, bs in todo.items(): + sig = [b for b in bs if not np.isinf(widths[b])] + tasks += [(a, [b]) for b in bs if np.isinf(widths[b])] + step = max(1, _CHUNK // len(bpts[a])) + tasks += [(a, sig[k:k + step]) for k in range(0, len(sig), step)] + tasks.sort(key=lambda t: -len(t[1]) * len(bpts[t[0]])) + need = sorted({b for _, bs in tasks for b in bs}) + trees = dict(zip(need, _pmap(lambda i: _tree(bpts[i]), need, th))) + + def run(t): + a, bs = t + f = _dir_stats_far if FAR_DECIMATION["k"] else _dir_stats + DM[a, bs], CN[a, bs], MO[a, bs], CP[a, bs] = f(bpts[a], trees, bs, widths[a], widths) + + _pmap(run, tasks, th) + if share is not None: + A, B, RA, RB = share + DM[A, B], CN[A, B], MO[A, B], CP[A, B] = DM[RA, RB], CN[RA, RB], MO[RA, RB], CP[RA, RB] + if c: + for a in {t[0] for t in tasks}: + bs = [b for b in range(n) if b != a] + c.put_rows(keys[a], [keys[b] for b in bs], DM[a, bs], CN[a, bs], MO[a, bs], CP[a, bs]) + c.trim() + return _assemble(scene, DM, CN, MO, CP) + + +def _assemble(scene: Scene, DM, CN, MO, CP) -> dict: + """Pair dicts from the per-direction statistics, in edge_features' operation order and key order.""" + n = scene.n + I, J = np.triu_indices(n, 1) + dmin = np.minimum(DM[I, J], DM[J, I]) + hist = 0.5 * (STEP_UM * CN[I, J]) + 0.5 * (STEP_UM * CN[J, I]) + mom = 0.5 * MO[I, J] + 0.5 * MO[J, I] + cps = 0.5 * CP[I, J] + 0.5 * CP[J, I] + gnd = np.array([c.role == "ground" for c in scene.conductors]) + cols = {"is_ground_pair": (gnd[I] | gnd[J]).astype(float), "log_dmin": np.log(np.maximum(dmin, 1e-9))} + sep = np.log1p(hist) + for k in range(sep.shape[1]): + cols[f"sep_{k:02d}"] = sep[:, k] + lm = np.log(np.maximum(mom, 1e-9)) + for k, p in enumerate(MOMENTS): + cols[f"mom_{p:g}"] = lm[:, k] + cols["log_cps"] = np.log(np.maximum(cps, 1e-9)) + if EDGE_TABLE["on"]: + return EdgeTable(n, {**cols, "_cps": cps}, ("_cps",)) + keys = list(cols) + rows = zip(*[cols[k].tolist() for k in keys], list(cps)) + return {(i, j): {**dict(zip(keys, r[:-1])), "_cps": r[-1]} for i, j, r in zip(I.tolist(), J.tolist(), rows)} + + +def global_features(scene: Scene) -> dict: + st = scene.stack + n_sig = sum(c.role == "signal" for c in scene.conductors) + return {"n_metal_layers": float(st["n_metal_layers"]), "log_metal_t": _log(st["metal_thickness_um"]), + "log_substrate_t": _log(st["substrate_thickness_um"]), "eps_eff": (st["substrate_eps_r"] + 1) / 2, + "n_signal": float(n_sig), "log_chip_area": _log(scene.chip.area), + "log_pocket_area": _log(scene.pocket.area)} + + +def boundary_points(scene: Scene) -> tuple[dict, dict]: + def one(i): + g = region(scene, i) + return sample_boundary(g, STEP_UM), np.inf if scene.conductors[i].role == "ground" else 2 * g.area / g.length + + out = _pmap(one, list(range(scene.n)), _nthreads()) + return {i: p for i, (p, _) in enumerate(out)}, {i: w for i, (_, w) in enumerate(out)} diff --git a/src/squadds/ml/capacitance/_core/_tlsq/uge/graph.py b/src/squadds/ml/capacitance/_core/_tlsq/uge/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..64dfdecbb33386905c0ad9c623cc4313e4102f69 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/uge/graph.py @@ -0,0 +1,74 @@ +"""Scene graph (nodes = conductors, edges = all conductor pairs) and its permutation-invariant pooled vector.""" + +from __future__ import annotations + +import numpy as np + +from .blocks import EdgeTable, _cache, body_keys, boundary_points, edge_features_all, global_features, node_features_all +from .proxies import Proxy +from .scene import Scene + + +def scene_graph(scene: Scene, proxy: Proxy | None = None) -> dict: + keys = body_keys(scene) if _cache() else None + bpts, widths = boundary_points(scene) + nodes = node_features_all(scene, keys) + edges = edge_features_all(scene, bpts, widths, keys) + # shielding: share of each endpoint's total geometric coupling carried by this edge + table = isinstance(edges, EdgeTable) + if table: + edges = _shares_table(scene.n, edges) + if proxy is not None: + edges = {p: edges[p] for p in edges} + tot = None if table else np.zeros(scene.n) + for (i, j), f in (edges.items() if tot is not None else ()): + tot[i] += f["_cps"] + tot[j] += f["_cps"] + for (i, j), f in (edges.items() if tot is not None else ()): + si, sj = f["_cps"] / max(tot[i], 1e-12), f["_cps"] / max(tot[j], 1e-12) + f["share_mean"], f["share_absdiff"] = 0.5 * (si + sj), abs(si - sj) + g = {"names": scene.names(), "global": global_features(scene), "nodes": nodes, "edges": edges} + if proxy is not None: + px = proxy.compute(scene, edges) + for i, v in px["node"].items(): + nodes[i].update({f"proxy_{k}": x for k, x in v.items()}) + for e, v in px["edge"].items(): + edges[e].update({f"proxy_{k}": x for k, x in v.items()}) + g["global"].update({f"proxy_{k}": x for k, x in px["global"].items()}) + if "matrix" in px: + g["proxy_matrix"] = px["matrix"] + for f in (edges.values() if tot is not None else ()): + f.pop("_cps") + return g + + +def _shares_table(n: int, E: EdgeTable) -> EdgeTable: + """The shares of scene_graph on an EdgeTable: the same additions in the same order (np.add.at is sequential).""" + I, J = np.triu_indices(n, 1) + cps = E.cols["_cps"] + tot = np.zeros(n) + np.add.at(tot, np.c_[I, J].ravel(), np.repeat(cps, 2)) + si, sj = cps / np.maximum(tot[I], 1e-12), cps / np.maximum(tot[J], 1e-12) + return E.with_cols({"share_mean": 0.5 * (si + sj), "share_absdiff": np.abs(si - sj)}, drop=("_cps",), + npcols=("share_mean", "share_absdiff")) + + +def pooled_vector(g: dict) -> dict: + """Fixed-length universal vector for any number of conductors: global block, the ground node, sum/mean/max over + signal nodes, and sum/mean/max over signal-signal and signal-ground edges.""" + out = {f"global.{k}": v for k, v in g["global"].items()} + roles = ["ground" if n["role_ground"] else "signal" for n in g["nodes"]] + keys = [k for k in g["nodes"][0] if k != "role_ground"] + gi = roles.index("ground") + out.update({f"ground.{k}": g["nodes"][gi][k] for k in keys}) + S = np.array([[n[k] for k in keys] for n, r in zip(g["nodes"], roles) if r == "signal"]) + for agg, fn in (("mean", np.mean), ("max", np.max), ("min", np.min)): + out.update({f"signal.{agg}.{k}": v for k, v in zip(keys, fn(S, 0))}) + ekeys = [k for k in next(iter(g["edges"].values())) if k != "is_ground_pair"] + for typ, flag in (("ss", 0.0), ("sg", 1.0)): + E = np.array([[f[k] for k in ekeys] for f in g["edges"].values() if f["is_ground_pair"] == flag]) + if len(E) == 0: + E = np.full((1, len(ekeys)), np.nan) + for agg, fn in (("mean", np.nanmean), ("max", np.nanmax), ("min", np.nanmin)): + out.update({f"edge_{typ}.{agg}.{k}": v for k, v in zip(ekeys, fn(E, 0))}) + return out diff --git a/src/squadds/ml/capacitance/_core/_tlsq/uge/localtok.py b/src/squadds/ml/capacitance/_core/_tlsq/uge/localtok.py new file mode 100644 index 0000000000000000000000000000000000000000..491b700f076d5ef31b33e9cacfd5633a862cabbb --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/uge/localtok.py @@ -0,0 +1,126 @@ +"""Local, window-invariant context tokens (PRIOR_SCHEME.md 14.5 E4; replace the chip / pocket areas): for every signal +conductor and radius R, the fractions of its surrounding annulus (conductor buffered by R, minus the conductor) that are +ground metal, other-conductor metal and etched chip; the rest of the annulus lies outside the chip (no metal). Pair +tokens = mean over the pair's signal ends (a ground pair: its signal end). Identical copy: tlsq_infer/localtok.py.""" + +from __future__ import annotations + +import numpy as np +import shapely + +from ..geometry import sample_boundary +from ..embed.proxy import _nthreads +from .blocks import MOMENTS, SEP_EDGES_UM, STEP_UM, EdgeTable, _dist, _kratio, _pmap, _tree + +RADII_UM = (50.0, 150.0, 400.0) +KEYS = [f"lt_{k}{int(r)}" for r in RADII_UM for k in ("g", "o", "e")] + + +def node_tokens(scene) -> np.ndarray: + """(n, len(KEYS)) per conductor (ground row = NaN).""" + conds = scene.conductors + n = len(conds) + G = next(c.geom for c in conds if c.role == "ground") + sig = [k for k, c in enumerate(conds) if c.role != "ground"] + tree = shapely.STRtree([conds[k].geom for k in sig]) + out = np.full((n, len(KEYS)), np.nan) + + def one(k): + g = conds[k].geom + vals = [] + for R in RADII_UM: + ring = g.buffer(R, quad_segs=4).difference(g) + A = ring.area + box = ring.bounds + gm = shapely.intersection(shapely.clip_by_rect(G, *box), ring).area + near = [sig[i] for i in tree.query(ring, predicate="intersects") if sig[i] != k] + om = shapely.intersection(shapely.union_all([conds[i].geom for i in near]), ring).area if near else 0.0 + inchip = shapely.intersection(scene.chip, ring).area + vals += [gm / A, om / A, max(inchip - gm - om, 0.0) / A] + return vals + + for k, vals in zip(sig, _pmap(one, sig, _nthreads())): # threads: shapely releases the GIL + out[k] = vals + return out + + +LG_R_UM = 100.0 +TOK = ["log_dmin"] + [f"sep_{k:02d}" for k in range(10)] + ["mom_0.5", "mom_1", "mom_2", "log_cps"] +LG_KEYS = [f"lg_{k}" for k in TOK] + + +def ground_tokens(scene) -> np.ndarray: + """(n, len(LG_KEYS)) per signal conductor: the ground-pair tokens of blocks.edge_features (separation spectrum, minimum + gap, coupling moments, coplanar-strip coupling) from the ground-edge samples within LG_R_UM of the conductor only + (fixed radius: independent of the ground window).""" + conds = scene.conductors + out = np.full((len(conds), len(LG_KEYS)), np.nan) + + def one(k): + g = conds[k].geom + b = g.bounds + 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) + pj = sample_boundary(g, STEP_UM) + pg = sample_boundary(P, STEP_UM) if not P.is_empty else np.zeros((0, 2)) + if len(pg): + pg = pg[_dist(_tree(pj), pg) < LG_R_UM] # drops the clip-box edges (>= LG_R_UM away) and the far ground + if not len(pg): + return None + wj = 2 * g.area / g.length + hist = np.zeros(len(SEP_EDGES_UM) - 1) + mom = np.zeros(len(MOMENTS)) + cps, dmin = 0.0, np.inf + for a_, b_ in ((pj, pg), (pg, pj)): + d = _dist(_tree(b_), a_) + dmin = min(dmin, d.min()) + hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0] + dd = np.maximum(d, 0.05) + mom += 0.5 * np.array([np.sum(STEP_UM * dd ** (-p)) for p in MOMENTS]) + cps += 0.5 * np.sum(STEP_UM * _kratio(dd / (dd + wj))) + 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))] + + sig = [k for k, c in enumerate(conds) if c.role != "ground"] + for k, v in zip(sig, _pmap(one, sig, _nthreads())): # threads: shapely and the k-d tree queries release the GIL + if v is not None: + out[k] = v + return out + + +def add_tokens(scene, row: dict) -> dict: + """Row (scene graph dict) with the KEYS added to every edge (shallow copy).""" + return add_from_tokens(row, node_tokens(scene), ground_tokens(scene), [c.role != "ground" for c in scene.conductors]) + + +def add_from_tokens(row: dict, T: np.ndarray, Lg: np.ndarray, sig) -> dict: + """Edges + KEYS (mean over the signal ends) + LG_KEYS (ground pairs: the fixed-radius tokens of the signal end; other + pairs: their own tokens, unchanged).""" + sig = np.asarray(sig) + if isinstance(row["edges"], EdgeTable): + return {**row, "edges": _add_table(row["edges"], T, Lg, sig)} + edges = {} + for (i, j), f in row["edges"].items(): + ends = [e for e in (i, j) if sig[e]] + new = {k: float(x) for k, x in zip(KEYS, T[ends].mean(0))} + if len(ends) == 1 and np.all(np.isfinite(Lg[ends[0]])): + new.update({k: float(x) for k, x in zip(LG_KEYS, Lg[ends[0]])}) + else: + new.update({f"lg_{k}": float(f[k]) for k in TOK}) + edges[(i, j)] = {**f, **new} + return {**row, "edges": edges} + + +def _add_table(E: EdgeTable, T: np.ndarray, Lg: np.ndarray, sig: np.ndarray) -> EdgeTable: + """add_from_tokens on an EdgeTable, per column with the same arithmetic: the mean over two signal ends is (a + b) / 2 + (numpy's mean of two rows), over one end the row itself.""" + I, J = np.triu_indices(E.n, 1) + sI, sJ = sig[I], sig[J] + both, oi, oj = sI & sJ, sI & ~sJ, ~sI & sJ + M = np.full((len(I), len(KEYS)), np.nan) + M[both] = (T[I[both]] + T[J[both]]) / 2 + M[oi], M[oj] = T[I[oi]], T[J[oj]] + end = np.where(oi, I, J) + use = (oi | oj) & np.isfinite(Lg[end]).all(1) + new = {k: M[:, c] for c, k in enumerate(KEYS)} + for c, k in enumerate(TOK): + new[f"lg_{k}"] = np.where(use, Lg[end][:, c], E.cols[k]) + return E.with_cols(new) diff --git a/src/squadds/ml/capacitance/_core/_tlsq/uge/nnk.py b/src/squadds/ml/capacitance/_core/_tlsq/uge/nnk.py new file mode 100644 index 0000000000000000000000000000000000000000..f93bb2ced67785f6090250296f73dd674bfc3f38 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/uge/nnk.py @@ -0,0 +1,341 @@ +"""Exact nearest-sample distances (agents/embedspeed, CONSULT_HPC 3a): a 2-D k-d tree in numba whose squared distance is +the platform's cKDTree arithmetic (probed at first use against scipy: fma(dy, dy, dx * dx) on the arm64 wheels, plain +dx * dx + dy * dy elsewhere), queried in boundary order with a warm-start bound from the previous sample (triangle +inequality, inflated), so the minimum over samples, and its sqrt, are the same bits as cKDTree.query. If no variant +reproduces cKDTree on the probe, `available()` is False and callers keep cKDTree. +""" +from __future__ import annotations + +import os +import threading + +import numba as nb +import numpy as np +from llvmlite import ir +from numba import types +from numba.extending import intrinsic + +LEAF = 32 +WARM = 4 # boundary-order neighbours of the previous query's nearest sample evaluated first (an exact upper bound) +_STATE: dict = {} + + +@intrinsic +def _fma(typingctx, a, b, c): + sig = types.float64(types.float64, types.float64, types.float64) + + def codegen(context, builder, signature, args): + d = ir.DoubleType() + fn = builder.module.declare_intrinsic("llvm.fma", [d], ir.FunctionType(d, [d, d, d])) + return builder.call(fn, args) + + return sig, codegen + + +@nb.njit(cache=True) +def _build(P, leaf): + """Balanced k-d tree over P (m, 2): permutation, node boxes and ranges; node k has children 2k+1, 2k+2.""" + m = P.shape[0] + nn = 1 + while (m + leaf - 1) // leaf > (nn + 1) // 2: + nn = 2 * nn + 1 + perm = np.arange(m) + lo = np.zeros(nn, np.int64) + hi = np.zeros(nn, np.int64) + box = np.empty((nn, 4)) + lo[0], hi[0] = 0, m + for k in range(nn): + a, b = lo[k], hi[k] + if b > a: + x0 = x1 = P[perm[a], 0] + y0 = y1 = P[perm[a], 1] + for t in range(a + 1, b): + x, y = P[perm[t], 0], P[perm[t], 1] + x0, x1, y0, y1 = min(x0, x), max(x1, x), min(y0, y), max(y1, y) + box[k, 0], box[k, 1], box[k, 2], box[k, 3] = x0, y0, x1, y1 + else: + box[k, 0] = box[k, 1] = np.inf + box[k, 2] = box[k, 3] = -np.inf + c = 2 * k + 1 + if c < nn: + mid = (a + b) // 2 + if b - a > 1: + d = 0 if box[k, 2] - box[k, 0] >= box[k, 3] - box[k, 1] else 1 + sub = perm[a:b].copy() + order = np.argsort(P[sub, d], kind="mergesort") + perm[a:b] = sub[order] + lo[c], hi[c] = a, mid + lo[c + 1], hi[c + 1] = mid, b + return perm, lo, hi, box + + +@nb.njit(cache=True, inline="always") +def _mind2(box, k, x, y): + dx = max(box[k, 0] - x, 0.0, x - box[k, 2]) + dy = max(box[k, 1] - y, 0.0, y - box[k, 3]) + return dx * dx + dy * dy + + +@nb.njit(nogil=True, cache=True, inline="always") +def _sqd(x, y, P, j, use_fma): + dx, dy = x - P[j, 0], y - P[j, 1] + return _fma(dy, dy, dx * dx) if use_fma else dx * dx + dy * dy + + +@nb.njit(nogil=True, cache=True) +def _kd(x, y, best, jb, P, perm, lo, hi, box, use_fma, stack): + """Exact k-d search below the bound best (a squared distance already attained by sample jb, or inf).""" + nn = lo.shape[0] + stack[0] = 0 + sp = 1 + while sp: + sp -= 1 + k = stack[sp] + if lo[k] >= hi[k] or _mind2(box, k, x, y) * (1.0 - 1e-12) > best: + continue + c = 2 * k + 1 + if c >= nn: + for t in range(lo[k], hi[k]): + j = perm[t] + s = _sqd(x, y, P, j, use_fma) + if s < best: + best, jb = s, j + continue + d1, d2 = _mind2(box, c, x, y), _mind2(box, c + 1, x, y) + if d1 <= d2: + stack[sp] = c + 1 + stack[sp + 1] = c + else: + stack[sp] = c + stack[sp + 1] = c + 1 + sp += 2 + return best, jb + + +@nb.njit(nogil=True, cache=True) +def _scan(x, y, best, jb, P, et, ej, a, b, t0, t1, use_fma): + """min over the edge-list entries a..b with t in [t0, t1] (t sorted).""" + lo_, hi_ = a, b + while lo_ < hi_: + mid = (lo_ + hi_) // 2 + if et[mid] < t0: + lo_ = mid + 1 + else: + hi_ = mid + for i in range(lo_, b): + if et[i] > t1: + break + s = _sqd(x, y, P, ej[i], use_fma) + if s < best: + best, jb = s, ej[i] + return best, jb + + +@nb.njit(nogil=True, cache=True) +def _nearest_t(x, y, P, et, ej, a, b, tf, use_fma): + """An attained upper bound: the better of the two list entries around t = tf.""" + lo_, hi_ = a, b + while lo_ < hi_: + mid = (lo_ + hi_) // 2 + if et[mid] < tf: + lo_ = mid + 1 + else: + hi_ = mid + best, jb = np.inf, -1 + for i in (lo_ - 1, lo_): + if a <= i < b: + s = _sqd(x, y, P, ej[i], use_fma) + if s < best: + best, jb = s, ej[i] + return best, jb + + +@nb.njit(nogil=True, cache=True) +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): + """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 + 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 + 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 + list (samples within delta of it). Otherwise, and whenever rho > delta, the k-d search (warm-started) decides.""" + m = X.shape[0] + mp = P.shape[0] + out = np.empty(m) + stack = np.empty(128, np.int64) + jp = -1 + e = 0 + for q in range(m): + x, y = X[q, 0], X[q, 1] + best = np.inf + jb = -1 + done = False + if H >= 3: + reg = -1 + vtx = -1 + for _ in range(H + 2): + t = (x - hx[e]) * ux[e] + (y - hy[e]) * uy[e] + if t < 0.0: + ep = e - 1 if e > 0 else H - 1 + if (x - hx[ep]) * ux[ep] + (y - hy[ep]) * uy[ep] > L[ep]: + vtx = e + break + e = ep + continue + if t > L[e]: + en = e + 1 if e + 1 < H else 0 + if (x - hx[en]) * ux[en] + (y - hy[en]) * uy[en] < 0.0: + vtx = en + break + e = en + continue + if (x - hx[e]) * nx[e] + (y - hy[e]) * ny[e] > 0.0: + reg = e + break + if vtx >= 0: + fx, fy = hx[vtx], hy[vtx] + dh2 = (x - fx) * (x - fx) + (y - fy) * (y - fy) + best = _sqd(x, y, P, hv[vtx], use_fma) + jb = hv[vtx] + rho2 = best - dh2 + 1e-9 * best + 1e-4 + 4.0 * eps * (np.sqrt(best) + 1.0) + if rho2 <= delta * delta: + r = np.sqrt(max(rho2, 0.0)) + ep = vtx - 1 if vtx > 0 else H - 1 + best, jb = _scan(x, y, best, jb, P, et, ej, eoff[vtx], eoff[vtx + 1], -r, r, use_fma) + best, jb = _scan(x, y, best, jb, P, et, ej, eoff[ep], eoff[ep + 1], L[ep] - r, L[ep] + r, use_fma) + done = True + elif reg >= 0: + tf = (x - hx[reg]) * ux[reg] + (y - hy[reg]) * uy[reg] + pp = (x - hx[reg]) * nx[reg] + (y - hy[reg]) * ny[reg] + dh2 = pp * pp + best, jb = _nearest_t(x, y, P, et, ej, eoff[reg], eoff[reg + 1], tf, use_fma) + if jb >= 0: + rho2 = best - dh2 + 1e-9 * best + 1e-4 + 4.0 * eps * (np.sqrt(best) + 1.0) + if rho2 <= delta * delta: + r = np.sqrt(max(rho2, 0.0)) + best, jb = _scan(x, y, best, jb, P, et, ej, eoff[reg], eoff[reg + 1], tf - r, tf + r, use_fma) + done = True + if not done: + if jp >= 0: + for j in range(max(0, jp - warm), min(mp, jp + warm + 1)): + s = _sqd(x, y, P, j, use_fma) + if s < best: + best, jb = s, j + best, jb = _kd(x, y, best, jb, P, perm, lo, hi, box, use_fma, stack) + out[q] = np.sqrt(best) + jp = jb + return out + + +@nb.njit(cache=True) +def _hull_lists(P, hv, delta): + H = hv.shape[0] + hx, hy = np.empty(H), np.empty(H) + ux, uy, L, nx, ny = np.empty(H), np.empty(H), np.empty(H), np.empty(H), np.empty(H) + for i in range(H): + hx[i], hy[i] = P[hv[i], 0], P[hv[i], 1] + for i in range(H): + k = i + 1 if i + 1 < H else 0 + dx, dy = hx[k] - hx[i], hy[k] - hy[i] + L[i] = np.sqrt(dx * dx + dy * dy) + ux[i], uy[i] = dx / L[i], dy / L[i] + nx[i], ny[i] = uy[i], -ux[i] # outward for a counter-clockwise hull + m = P.shape[0] + eps = 0.0 + cnt = np.zeros(H + 1, np.int64) + db = delta + 0.01 + for i in range(H): + for j in range(m): + ax, ay = P[j, 0] - hx[i], P[j, 1] - hy[i] + pp = ax * nx[i] + ay * ny[i] + if pp > eps: + eps = pp + t = ax * ux[i] + ay * uy[i] + if -db <= t <= L[i] + db and abs(pp) <= db: + cnt[i + 1] += 1 + eoff = np.cumsum(cnt) + et, ej = np.empty(eoff[H]), np.empty(eoff[H], np.int64) + for i in range(H): + k = eoff[i] + for j in range(m): + ax, ay = P[j, 0] - hx[i], P[j, 1] - hy[i] + pp = ax * nx[i] + ay * ny[i] + t = ax * ux[i] + ay * uy[i] + if -db <= t <= L[i] + db and abs(pp) <= db: + et[k], ej[k] = t, j + k += 1 + o = np.argsort(et[eoff[i]:eoff[i + 1]], kind="mergesort") + et[eoff[i]:eoff[i + 1]] = et[eoff[i]:eoff[i + 1]][o] + ej[eoff[i]:eoff[i + 1]] = ej[eoff[i]:eoff[i + 1]][o] + return hx, hy, ux, uy, L, nx, ny, eoff, et, ej, eps + + +DELTA = 1.0 +HULL_MAX = 200_000 # targets with more samples (the ground) use the k-d search only +_EMPTY = (np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), + np.zeros(1, np.int64), np.zeros(0), np.zeros(0, np.int64), 0.0) + + +class Tree: + """Drop-in for cKDTree(P).query(X)[0] (distances only).""" + + def __init__(self, P: np.ndarray, hull: bool | None = None): + self.P = np.ascontiguousarray(P, dtype=np.float64) + self.perm, self.lo, self.hi, self.box = _build(self.P, LEAF) + self.hv, self.H = np.zeros(0, np.int64), 0 + self.hl = _EMPTY + if (HULL["on"] if hull is None else hull) and 3 <= len(self.P) <= HULL_MAX: + try: + from scipy.spatial import ConvexHull + hv = ConvexHull(self.P).vertices.astype(np.int64) + except Exception: # noqa: BLE001 (degenerate: collinear samples) + hv = None + if hv is not None and len(hv) >= 3: + self.hv, self.H = hv, len(hv) + self.hl = _hull_lists(self.P, hv, DELTA) + + def dist(self, X: np.ndarray) -> np.ndarray: + return _query(np.ascontiguousarray(X, dtype=np.float64), self.P, self.perm, self.lo, self.hi, self.box, _STATE["fma"], + WARM, self.H, self.hv, *self.hl, DELTA) + + +HULL: dict = {"on": os.environ.get("TLSQ_NN_HULL", "1") == "1"} # far-field hull path (exact; off: k-d search only) + + +def probe(n_targets: int = 40, seed: int = 0) -> dict: + """Which arithmetic reproduces this platform's cKDTree bit for bit (random and boundary-like targets, near and far).""" + from scipy.spatial import cKDTree + + rng = np.random.default_rng(seed) + res = {} + for name in ("fma", "plain"): + bad = tot = 0 + for t in range(n_targets): + m = int(rng.integers(5, 3000)) + if t % 2: + th = np.sort(rng.uniform(0, 2 * np.pi, m)) + P = np.c_[np.cos(th) * rng.uniform(10, 300), np.sin(th) * rng.uniform(10, 300)] + rng.uniform(-5000, 5000, 2) + else: + P = rng.uniform(-300, 300, (m, 2)) + rng.uniform(-5000, 5000, 2) + X = np.cumsum(rng.normal(0, rng.choice([0.25, 30.0]), (2000, 2)), 0) + P.mean(0) + rng.uniform(-3000, 3000, 2) + tr = Tree(P, hull=False) + d = _query(np.ascontiguousarray(X), tr.P, tr.perm, tr.lo, tr.hi, tr.box, name == "fma", WARM, 0, tr.hv, *tr.hl, DELTA) + ref = cKDTree(P).query(X)[0] + bad += int((d != ref).sum()) + tot += len(X) + res[name] = dict(mismatches=bad, queries=tot) + return res + + +_LOCK = threading.Lock() + + +def available() -> bool: + with _LOCK: + return _available() + + +def _available() -> bool: + if "ok" not in _STATE: + r = probe() + ok = [k for k in ("fma", "plain") if r[k]["mismatches"] == 0] + _STATE.update(probe=r, ok=bool(ok), arith=ok[0] if ok else None) + _STATE["fma"] = bool(ok) and ok[0] == "fma" + return _STATE["ok"] diff --git a/src/squadds/ml/capacitance/_core/_tlsq/uge/proxies.py b/src/squadds/ml/capacitance/_core/_tlsq/uge/proxies.py new file mode 100644 index 0000000000000000000000000000000000000000..257da3ed0b735f127e702b3c1f0cdf776366d45b --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/uge/proxies.py @@ -0,0 +1,102 @@ +"""Physics-proxy plugins. A proxy maps a Scene to extra node / edge / global quantities that are cheap to compute and +physically aligned with the target. Swap the proxy to move the recipe to another observable (e.g. a resonator dataset +would plug in a quasi-TEM transmission-line proxy for f0 and kappa); the rest of the pipeline is unchanged.""" + +from __future__ import annotations + +import numpy as np + +from ..embed.proxy import mom_capacitance_gds, mom_capacitance_gds_avg, mom_capacitance_gds_flagship, mom_capacitance_gds_rich +from .scene import Scene + +EPS0 = 8.8541878128e-3 # fF/µm + + +class Proxy: + name = "none" + + def compute(self, scene: Scene, edges: dict) -> dict: + """Return {"node": {i: {...}}, "edge": {(i, j): {...}}, "global": {...}}; `edges` holds the geometry edge features.""" + return {"node": {}, "edge": {}, "global": {}} + + +class NoProxy(Proxy): + name = "none" + + +class ConformalCoupling(Proxy): + """Solver-free: per-pair coplanar-strip conformal-map coupling (already a geometry edge feature) turned into a + capacitance estimate C_ij ~ eps0 eps_eff * sum L K(k')/K(k), and node totals.""" + + name = "conformal" + + def compute(self, scene, edges): + e_eff = (scene.stack["substrate_eps_r"] + 1) / 2 + out = {"node": {i: {"log_Cself": -np.inf} for i in range(scene.n)}, "edge": {}, "global": {}} + tot = np.zeros(scene.n) + for (i, j), f in edges.items(): + c = EPS0 * e_eff * f["_cps"] + out["edge"][(i, j)] = {"log_C": float(np.log(max(c, 1e-9)))} + tot[i] += c + tot[j] += c + for i in range(scene.n): + out["node"][i] = {"log_Cself": float(np.log(max(tot[i], 1e-9)))} + return out + + +class CapacitanceMoM(Proxy): + """Thin-film method of moments on the exact polygons (quadtree mesh, whole ground plane): full Maxwell matrix.""" + + name = "mom" + + def __init__(self, max_cells: int = 8000, cells_per_gap: float = 3.0, n_offsets: int = 1, mesh: str = "v2", + substrate: str = "slab_open"): + self.max_cells, self.cells_per_gap, self.n_offsets, self.mesh = max_cells, cells_per_gap, n_offsets, mesh + self.substrate = substrate # MoM Green's function (embed.proxy.SUBSTRATE; PRIOR_SCHEME.md 14.6) + + def compute(self, scene, edges): + from ..embed.proxy import substrate + + with substrate(self.substrate, scene.stack.get("substrate_thickness_um")): + return self._compute(scene, edges) + + def _compute(self, scene, edges): + metals, kw = [c.geom for c in scene.conductors], dict(eps_r=scene.stack["substrate_eps_r"], max_cells=self.max_cells, + cells_per_gap=self.cells_per_gap) + if self.mesh == "v3-rich": # conductor-anchored mesh, Richardson-extrapolated (gap/3 and gap/6) + C, n, hm = mom_capacitance_gds_rich(metals, kw["eps_r"], self.cells_per_gap, self.max_cells, 2 * self.max_cells) + elif self.mesh in ("lite", "formula"): # flagship-fast cheap priors (PRIOR_SCHEME.md Part III): micro-MoM at a panel budget / closed form + from ..embed.fastprior import formula_prior, micro_mom + + if self.mesh == "lite": + C, _, info = micro_mom(metals[0], metals[1:], kw["eps_r"], budget=self.max_cells, cells_per_gap=self.cells_per_gap) + n, hm = int(sum(info["panels"])), float(min(info["h_um"])) + mg = float(info["min_gap_um"]) # the mesh's smallest conductor gap (h = gap / ppg off the floor) + else: + C, info = formula_prior(metals[0], metals[1:], kw["eps_r"]) + n, hm = 0, float(info["min_gap_um"]) + elif self.mesh == "flagship": # strip-merged, resolution-controlled Richardson pair, H-matrix solve (PRIOR_SCHEME.md Part II) + C, n, hm, _ = mom_capacitance_gds_flagship(metals, kw["eps_r"], self.cells_per_gap, self.max_cells) + else: + if self.mesh != "v2": + kw["mesh"] = self.mesh + try: + C, n, hm = mom_capacitance_gds_avg(metals, self.n_offsets, **kw) if self.n_offsets > 1 else mom_capacitance_gds(metals, **kw) + except np.linalg.LinAlgError: + if self.mesh != "v3": + raise + # v3 single solve: sliver edge panels can make the gap/3 system indefinite (~0.2 % of designs); use gap/6 + kw.update(cells_per_gap=2 * self.cells_per_gap, max_cells=2 * self.max_cells) + C, n, hm = mom_capacitance_gds(metals, **kw) + out = {"node": {i: {"log_Cself": float(np.log(max(C[i, i], 1e-9)))} for i in range(scene.n)}, "edge": {}, + "global": {"cells": float(n), "h_min_um": float(hm)}, "matrix": C} + if self.mesh != "lite": # every variant records the layout's smallest conductor gap (review W1); lite: the mesh's own + from ..embed.fastprior import gap_of + mg = float(info["min_gap_um"]) if self.mesh == "formula" else float(gap_of(metals)) + out["global"]["min_gap_um"] = mg + for (i, j) in edges: + out["edge"][(i, j)] = {"log_C": float(np.log(max(-C[i, j], 1e-9)))} + return out + + +PROXIES = {p.name: p for p in (NoProxy, ConformalCoupling, CapacitanceMoM)} diff --git a/src/squadds/ml/capacitance/_core/_tlsq/uge/scene.py b/src/squadds/ml/capacitance/_core/_tlsq/uge/scene.py new file mode 100644 index 0000000000000000000000000000000000000000..fd065001f444949153aed2c227c3eda7c321d02f --- /dev/null +++ b/src/squadds/ml/capacitance/_core/_tlsq/uge/scene.py @@ -0,0 +1,90 @@ +"""Scene: the metal of a layout as a list of conductors (one ground net + any number of signal bodies), plus the stack.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Callable + +import gdstk +import numpy as np +import shapely +from shapely.geometry import Polygon + +DEFAULT_LAYERS = {"ground": [(1, 0)], "signal": [(1, 10)]} +DEFAULT_STACK = {"n_metal_layers": 1, "metal_thickness_um": 0.25, "substrate_thickness_um": 350.0, "substrate_eps_r": 11.45} + + +@dataclass +class Conductor: + name: str + role: str # "ground" | "signal" + geom: object # shapely (Multi)Polygon, µm + + +@dataclass +class Scene: + conductors: list[Conductor] # index 0 is the ground net + chip: Polygon + pocket: object # chip minus ground metal: the etched region (its edge is the ground's active edge) + stack: dict = field(default_factory=lambda: dict(DEFAULT_STACK)) + markers: dict = field(default_factory=dict) # non-metal helper shapes by (layer, datatype), e.g. port stubs; naming only + + @property + def n(self) -> int: + return len(self.conductors) + + def names(self) -> list[str]: + return [c.name for c in self.conductors] + + +def _valid(g): + g = shapely.make_valid(g) + parts = [p for p in getattr(g, "geoms", [g]) if p.geom_type in ("Polygon", "MultiPolygon")] + return shapely.union_all(parts) + + +def scene_from_gds(path, layers: dict = DEFAULT_LAYERS, stack: dict | None = None, + namer: Callable[[list, object], list[str]] | None = None) -> Scene: + """Read only metal layers. Each signal polygon is one conductor; all ground polygons form one net. + `namer(signal_geoms, markers)` returns a name per signal body (dataset convention); default S0, S1, ...""" + lib = gdstk.read_gds(str(path)) + cell = lib.top_level()[0] + u = lib.unit / 1e-6 + lay = {k: {tuple(x) for x in v} for k, v in layers.items()} + sig, gnd, other = [], [], {} + for p in cell.polygons: + key = (p.layer, p.datatype) + g = Polygon(p.points * u) + if key in lay["signal"]: + sig.append(g) + elif key in lay["ground"]: + gnd.append(g) + else: + other.setdefault(key, []).append(g) + G = _valid(shapely.union_all([_valid(g) for g in gnd])) + S = [_valid(g) for g in sig] + chip = shapely.box(*G.bounds) + markers = {k: shapely.union_all(v) for k, v in other.items()} + names = namer(S, markers) if namer else [f"S{i}" for i in range(len(S))] + conds = [Conductor("G", "ground", G)] + [Conductor(n, "signal", g) for n, g in zip(names, S)] + return Scene(conds, chip, chip.difference(G), {**DEFAULT_STACK, **(stack or {})}, markers) + + +def tlsq_namer(signals: list, markers: dict, n_slots: int = 5) -> list[str]: + """This dataset's convention: N = body fed by the north port stub (2,0); S = body fed by the south stub (3,0) if + present, else the body containing the origin (star, inner pad); remaining bodies P1, P2, ... ordered by angle.""" + north, south = markers.get((2, 0)), markers.get((3, 0)) + n = min(range(len(signals)), key=lambda i: signals[i].distance(north)) + rest = [i for i in range(len(signals)) if i != n] + if south is not None: + s = min(rest, key=lambda i: signals[i].distance(south)) + else: + s = next((i for i in rest if signals[i].contains(shapely.Point(0, 0))), max(rest, key=lambda i: signals[i].area)) + names = [""] * len(signals) + names[s], names[n] = "S", "N" + a0 = np.degrees(np.arctan2(signals[n].centroid.y, signals[n].centroid.x)) + for i in rest: + if i != s: + a = np.degrees(np.arctan2(signals[i].centroid.y, signals[i].centroid.x)) + names[i] = f"P{int(round(((a - a0) % 360) / (360 / n_slots))) % n_slots}" + return names diff --git a/src/squadds/ml/capacitance/_core/api.py b/src/squadds/ml/capacitance/_core/api.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8c2d653ae0fa9f4ae898d178c8ae02cc3e9688 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/api.py @@ -0,0 +1,531 @@ +"""Registry-driven GNN prediction for the Space (deploy/registry.yaml: gnn_hub, gnn_models). + +predict_gnn(prepared, name) runs the frozen Predictor (geomgnn.infer, FINALIZATION_V1 checkpoints) on the scene built from a +tlsq_infer PreparedLayout. The steps after the scene are those of infer.Predictor.from_gds, statement for statement; +deploy/tests/test_gnn_space.py checks the result against the frozen stage's from_gds on the raw TRAIN GDS files. +Entries with `learned_prior` (the fast tier) replace the two field solves by the learned prior surrogate +(geomgnn.learned_prior = scripts/learnedprior/lp_bench.py Learned.from_gds); the networks are the same frozen weights. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import json +import os +import threading +import time +import warnings +from pathlib import Path + +import numpy as np +import shapely + +from . import __version__ +from . import infer as I +from ._tlsq.embed import fastprior, proxy +from ._tlsq.uge.graph import scene_graph +from ._tlsq.uge.scene import DEFAULT_STACK, Conductor, Scene +from ._tlsq.uge import blocks as _blocks + +# Inference default: the numerically exact embedding (translated copies shared; last-bit differences only, agents/embedspeed); +# TLSQ_EMBED_MODE=bitwise restores the bit-identical training features. +_blocks.EMBED_MODE["mode"] = os.environ.get("TLSQ_EMBED_MODE", "numex") +_blocks.EDGE_TABLE["on"] = os.environ.get("TLSQ_EDGE_TABLE", "1") == "1" # array edge table (bitwise values; dicts on request) + +lt = I.lt +EPS_TRAIN, T_TRAIN_UM = 11.45, 350.0 +# Other substrate stacks (agents/v4stack, author decision 2026-11-03): the physics prior is solved at the requested (eps_r, thickness) +# and the frozen networks correct it; the geometric embedding and the global inputs stay at the training stack (Si 11.45, 350 um). +# Tested on the 15 held-out DoE designs: Si at 10-1000 um, and eps_r 3.8-24 at 350 um. Learned-prior entries (the Fast tier) cannot +# solve a prior: off the stack they keep the (1 + eps_r) / (1 + 11.45) rescaling of their training-stack prediction, with a warning. +TESTED_THICKNESS_UM = (10.0, 1000.0) +TESTED_EPS_R = (3.8, 24.0) +CALIBRATED_ROUTE = "calibrated: physics prior solved at the requested stack, networks and embedding at the training stack" +CALIBRATED_CAVEAT = ( + "calibrated substrate route: the physics prior is solved at your stack; the networks were trained on Si (eps_r 11.45), 350 um " + "only and correct it unchanged. A bounded-error route, not training-stack accuracy: on 15 held-out DoE designs (paper model) " + "the mutual entries were 0.21-1.02 % (MAE 0.07-0.33 fF, RMSE 0.09-0.45 fF) on every tested stack, against 0.23 % (0.080 / " + "0.111 fF) on the training stack; self terms 0.96-1.22 % (MAE 0.48-0.79, RMSE 0.52-0.86 fF) at 10-50 um Si and 0.89 % " + "(0.92 / 1.07 fF) at 1000 um, against 0.24 % (0.18 / 0.22 fF)") +FAST_ROUTE = "fast: eps-rescaled training-stack prediction; thickness not modelled" +FAST_WARNING = ("Fast does not solve the prior at your stack: it rescales its 350 um silicon answer by (1 + eps_r) / (1 + 11.45) and " + "ignores thickness. Measured off the stack: 6.4 % median error (MAE 1.7 fF, RMSE 2.4 fF), 13 % (3.4 / 4.7 fF) across Si " + "thickness 10-1000 um; use the flagship (Accurate) model for other substrates (prior solved at your eps_r and thickness: 0.48 % " + "(0.13 / 0.18 fF) on the same solves).") + + +def on_training_stack(eps_r: float, thickness_um: float) -> bool: + return abs(float(eps_r) - EPS_TRAIN) <= 1e-9 and abs(float(thickness_um) - T_TRAIN_UM) <= 1e-9 + + +def tested_stack(eps_r: float, thickness_um: float) -> bool: + """The (eps_r, thickness) combinations the calibrated route was scored on: Si (11.45) at 10-1000 um, or eps_r 3.8-24 at 350 um.""" + e, t = float(eps_r), float(thickness_um) + si = abs(e - EPS_TRAIN) <= 1e-9 and TESTED_THICKNESS_UM[0] <= t <= TESTED_THICKNESS_UM[1] + return si or (abs(t - T_TRAIN_UM) <= 1e-9 and TESTED_EPS_R[0] <= e <= TESTED_EPS_R[1]) + + +def substrate_route(eps_r: float, thickness_um: float, solves_prior: bool = True) -> tuple[dict, list]: + """(substrate record, warnings) of a request. solves_prior=False: a learned-prior entry (the Fast tier), eps-rescaled off the stack.""" + e, t = float(eps_r), float(thickness_um) + if not (np.isfinite(e) and e >= 1.0): + raise ValueError(f"substrate eps_r must be a finite number >= 1 (got {eps_r!r})") + if not (np.isfinite(t) and t > 0): + raise ValueError(f"substrate thickness must be a finite number > 0 um (got {thickness_um!r})") + train = {"eps_r": EPS_TRAIN, "thickness_um": T_TRAIN_UM} + rec = {"eps_r": e, "thickness_um": t, "training_stack": train, "embedding_stack": dict(train), "tested": True} + if on_training_stack(e, t): + rec.update(route="training stack", prior_solved_at=dict(train) if solves_prior else None, eps_rescale_factor=1.0) + return rec, [] + if not solves_prior: + rec.update(route=FAST_ROUTE, prior_solved_at=None, eps_rescale_factor=(1.0 + e) / (1.0 + EPS_TRAIN), tested=False, + caveat="eps rescaling of the training-stack prediction, thickness not modelled; on 285 off-stack Q3D solves of 15 " + "held-out designs 6.36 % (MAE 1.74 fF, RMSE 2.39 fF): 13.1 % (3.43 / 4.67 fF) across Si thickness 10-1000 um, " + "1.44 % (0.51 / 0.73 fF) across eps_r 3.8-24 at 350 um, against 1.29 % (0.48 / 0.71 fF) on the training stack") + return rec, [FAST_WARNING] + rec.update(route=CALIBRATED_ROUTE, prior_solved_at={"eps_r": e, "thickness_um": t}, eps_rescale_factor=None, + tested=tested_stack(e, t), caveat=CALIBRATED_CAVEAT) + w = [] + if not rec["tested"]: + w.append(f"substrate eps_r {e:g}, {t:g} um is outside the tested range of the calibrated route (Si eps_r 11.45 at " + f"{TESTED_THICKNESS_UM[0]:g}-{TESTED_THICKNESS_UM[1]:g} um, or eps_r {TESTED_EPS_R[0]:g}-{TESTED_EPS_R[1]:g} at " + f"{T_TRAIN_UM:g} um): untested, its error is unknown") + return rec, w + + + +def substrate_line(res: dict) -> str: + """One Markdown line of a result's substrate route for the Space reports.""" + sub = res.get("substrate_route") or {} + head = f"**Substrate** {res.get('substrate')} (eps_r {res['eps_r']:g}), {res['thickness_um']:g} µm: " + r = sub.get("route", "training stack") + if r == "training stack": + return head + "the training stack" + if r == FAST_ROUTE: + return head + f"{r} (factor (1+eps_r)/(1+11.45) = {sub['eps_rescale_factor']:.4f}). {FAST_WARNING}" + return head + r + ("" if sub.get("tested") else " (UNTESTED combination)") + f". {sub.get('caveat', '')}" + +PRIOR_IMPLS = ("frozen", "cpu_fast") +_HMAT0 = dict(proxy.HMAT) +_STATE = {"prior_impl": "frozen", "patches": [], "mode": None, "stack": None} +_CACHE: dict = {} + + +def gnn_names(reg) -> list[str]: + return [k for k, v in (reg.data.get("gnn_models") or {}).items() if v.get("status", "available") == "available"] + + +def set_prior_impl(impl: str) -> None: + """frozen: the solver as frozen. cpu_fast: scripts/geomfast/fastmom.py (vectorised H-matrix kernel) with ACA eps 1e-6 and + PCG tol 1e-8 (agents/geomfast/FASTPRIOR_STATUS.md); process-wide.""" + if impl not in PRIOR_IMPLS: + raise ValueError(f"prior_impl {impl!r} not in {PRIOR_IMPLS}") + if impl == _STATE["prior_impl"]: + return + from . import fastmom + if impl == "cpu_fast": + fastmom.install() + proxy.HMAT.update(eps=1e-6, tol=1e-8) + else: + fastmom.uninstall() + proxy.HMAT.clear() + proxy.HMAT.update(_HMAT0) + _STATE["prior_impl"] = impl + + +VALUE_PRESERVING = ("rejtail_fv",) # bit-identical priors +VALUE_CHANGING = ("priorv2m_sf", "priorv2m", "priorv2") # change the prior: need prior.value_changing_approved in the registry entry +# priorv2.installed() arguments of each value-changing patch: v2m_sf = the corrected prior with substrate far field (default since +# 2026-10-20); v2m = the corrected prior with the half-space far field (before 2026-10-20; reproduction); v2 = version 2 (no margin +# widening), the prior of the paper's "retrained, version 2" ablation (paper Space only) +V2_KWARGS = {"priorv2m_sf": dict(policy="fc", dip=True, margin=True), "priorv2m": dict(policy="fc", dip=True, margin=True), + "priorv2": dict(policy="fc", dip=True, margin=False)} +# far-pair form on top of the v2 pieces: geomgnn.farfield = scripts/farfield/farfield.py verbatim, arm b of agents/farfield (slab dipole +# for signal far pairs in different ground pockets, half-space dipole inside a pocket); adopted by the user 2026-10-20 +FAR_ARM = {"priorv2m_sf": "b"} +# TLSQ_FAR_FIELD=halfspace: serve priorv2m wherever priorv2m_sf is listed (the previous corrected prior, process-wide; reproduction) +FAR_FIELD_ENV = "TLSQ_FAR_FIELD" +PRIOR_PATCHES = VALUE_PRESERVING + VALUE_CHANGING + + +def resolve_patches(patches) -> list: + """The registry patches with the TLSQ_FAR_FIELD override applied ('halfspace': priorv2m_sf -> priorv2m).""" + v = os.environ.get(FAR_FIELD_ENV, "").strip().lower() + if v not in ("", "substrate", "halfspace"): + raise ValueError(f"{FAR_FIELD_ENV}={v!r}: use 'substrate' (default) or 'halfspace'") + return sorted("priorv2m" if (p == "priorv2m_sf" and v == "halfspace") else p for p in (patches or [])) + + +SPEED_MODES = ("exact", "exact_compiled", "certified") # geomgnn.fastprior_pkg modes (agents/fastprior_pkg/RESULTS.md) + + +def speed_mode(pr: dict): + """Solver mode of the prior: TLSQ_GNN_PRIOR_MODE (opt-in override, e.g. 'certified' or 'frozen') else registry prior.mode; + None / 'frozen' = the vendor solver as frozen (no fastprior_pkg).""" + m = os.environ.get("TLSQ_GNN_PRIOR_MODE") or pr.get("mode") + if m in (None, "", "frozen"): + return None + if m not in SPEED_MODES: + raise ValueError(f"prior mode {m!r} not in {SPEED_MODES} (or 'frozen')") + return m + + +def _v2m_value_patch(F, P, FL, patch="priorv2m"): + """fastprior_pkg value hook: prior v2m (geomgnn.priorv2 installed(policy='fc', dip=True, margin=True)) on top of the + solver components (patch="priorv2": version 2, margin=False); returns the undo callable.""" + from . import priorv2 + assert priorv2.F is F and priorv2.P is P, "priorv2 and fastprior_pkg must patch the same vendor modules" + return _install_v2(priorv2, F, P, patch) + + +def _install_v2(priorv2, F, P, patch): + """priorv2.installed(**V2_KWARGS[patch]) and, for priorv2m_sf, the far-pair arm on top (geomgnn.farfield); returns the undo.""" + ctx = priorv2.installed(**V2_KWARGS[patch]) + ctx.__enter__() + undo_far = None + if patch in FAR_ARM: + from . import farfield + try: + undo_far = farfield.install(FAR_ARM[patch], F, P, priorv2) + except BaseException: + ctx.__exit__(None, None, None) + raise + + def undo(): + if undo_far is not None: + undo_far() + ctx.__exit__(None, None, None) + return undo + + +def _teardown() -> None: + from . import rejtail_fv + if _STATE.get("mode"): + from . import fastprior_pkg + fastprior_pkg.uninstall() # also undoes its value patch + elif set(V2_KWARGS) & set(_STATE["patches"]): + _STATE.pop("v2undo")() + rejtail_fv.uninstall() + _STATE.update(patches=[], mode=None, stack=None) + + +def set_prior_stack(pr: dict, threads: int = 2) -> None: + """Process-wide prior stack of a registry prior: patches (rejtail_fv | priorv2m) and the solver mode (fastprior_pkg). + rejtail_fv: geomgnn.rejtail_fv (value-preserving rejection-tail fix; fastprior_pkg's fv replaces it, so not with a mode). + priorv2m: prior v2m (agents/priorv2/FINALIZATION_V2.json): priorv2.installed(policy='fc', dip=True, margin=True), as + fastprior_pkg's value_patch when a mode is set; it replaces _window_solve itself, so never with rejtail_fv. + mode: fastprior_pkg.install(mode, cpus=threads, target='geomgnn', value_patch=v2m) + warmup() (numba compile).""" + patches = resolve_patches(pr.get("patches")) + mode = speed_mode(pr) + bad = set(patches) - set(PRIOR_PATCHES) + if bad: + raise ValueError(f"unknown prior patches {bad}; known: {PRIOR_PATCHES}") + v2 = [p for p in patches if p in V2_KWARGS] + if v2 and "rejtail_fv" in patches: + raise ValueError("priorv2m already contains the rejection-tail handling; do not combine it with rejtail_fv") + if len(v2) > 1: + raise ValueError(f"one prior version per stack, got {v2}") + if mode and "rejtail_fv" in patches: + raise ValueError("fastprior_pkg contains fv; list rejtail_fv only without a prior mode") + unapproved = [p for p in patches if p in VALUE_CHANGING and not pr.get("value_changing_approved")] + if unapproved: + raise ValueError(f"value-changing prior patches {unapproved} need prior.value_changing_approved in the registry") + key = (tuple(patches), mode, int(threads)) + if key == _STATE.get("stack"): + return + _teardown() + if mode: + from . import fastprior_pkg as fp + fp.install(mode=mode, cpus=int(threads), workers=os.environ.get("TLSQ_PRIOR_WORKERS"), target="geomgnn", blas_threads=int(threads), + value_patch=(lambda F, P, FL: _v2m_value_patch(F, P, FL, v2[0])) if v2 else None, warm=False) + if mode in ("exact_compiled", "certified"): + _STATE["warmup_s"] = fp.warmup() + else: + from . import priorv2, rejtail_fv + if "rejtail_fv" in patches: + rejtail_fv.install() + if v2: + _STATE["v2undo"] = _install_v2(priorv2, fastprior, proxy, v2[0]) + _STATE.update(patches=patches, mode=mode, stack=key, pr=dict(pr)) + if mode: + from . import winpool + winpool.install() # macOS: the prior's windows on spawned workers (numerically exact; TLSQ_WINDOW_PROCS=0 turns it off) + + +def _sha(p) -> str: + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +def surrogate_file(reg, name: str, model_dir=None) -> Path | None: + """The learned prior checkpoint of an entry (bundle copy named in info.json "surrogate", else the registry path).""" + lp = reg["gnn_models"][name].get("learned_prior") + if not lp: + return None + md = os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir + if md and (Path(md) / name / "info.json").exists(): + info = json.loads((Path(md) / name / "info.json").read_text()) + if info.get("surrogate"): + return Path(md) / name / info["surrogate"] + return reg.root / lp["checkpoint"]["path"] + + +def checkpoint_files(reg, name: str, model_dir=None) -> list[Path]: + """Bundle copies (//info.json) or the registry's source paths; SHA256 checked against the registry.""" + m = reg["gnn_models"][name] + md = os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir + if md and (Path(md) / name / "info.json").exists(): + info = json.loads((Path(md) / name / "info.json").read_text()) + files = [Path(md) / name / f for f in info["files"]] + else: + files = [reg.root / c["path"] for c in m["checkpoints"]] + return files + + +def available(name: str, reg, model_dir=None) -> bool: + s = surrogate_file(reg, name, model_dir) + return all(f.exists() for f in checkpoint_files(reg, name, model_dir)) and (s is None or s.exists()) + + +def load(name: str, reg, model_dir=None, threads: int | None = None) -> I.Predictor: + m = reg["gnn_models"][name] + threads = int(threads or os.environ.get("TLSQ_NUM_THREADS") or 2) + key = (str(reg.path), name, str(os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir), threads) + if key in _CACHE: + _apply_prior(m, threads) + return _CACHE[key] + files = checkpoint_files(reg, name, model_dir) + for f, c in zip(files, m["checkpoints"], strict=True): + if _sha(f) != c["sha256"]: + raise RuntimeError(f"{name}: {f.name} SHA256 differs from the registry (frozen checkpoint {c['sha256'][:12]})") + P = I.Predictor(files, threads=threads) + if P.arm != m["arm"]: + raise RuntimeError(f"{name}: checkpoints are arm {P.arm!r}, registry says {m['arm']!r}") + pr = m.get("prior") + lpr = m.get("learned_prior") + phys = P.models[0][0].get("schema", {}).get("physics", {}) + P.surrogate = None + if P.direct: + if pr or lpr: + raise RuntimeError(f"{name}: direct arm has no prior, registry lists one") + elif lpr: + if pr or P.fast or [float(x) for x in lpr["ppg"]] != [1.5, 3.0]: + raise RuntimeError(f"{name}: a learned prior replaces the 1.5 / 3 ppg field solves of a full_gnn arm only ({P.arm}, {lpr})") + sf = surrogate_file(reg, name, model_dir) + if _sha(sf) != lpr["checkpoint"]["sha256"]: + raise RuntimeError(f"{name}: {sf.name} SHA256 differs from the registry (learned prior {lpr['checkpoint']['sha256'][:12]})") + from . import learned_prior + model, prep, _ = learned_prior.load(sf) + prep.floor_ff = lpr.get("floor_ff") + P.surrogate = (model, prep) + else: + if not pr or abs(float(pr["alpha"]) - float(phys.get("alpha"))) > 0 or (pr["method"] == "local_gap") != (phys.get("prior_method") == "local_gap") \ + or [float(x) for x in pr["ppg"]] != ([0.75, 1.5] if P.fast else [1.5, 3.0]): + raise RuntimeError(f"{name}: registry prior {pr} does not match the checkpoint physics {phys}") + _apply_prior(m, threads) + _CACHE[key] = P + return P + + +def _apply_prior(m: dict, threads: int = 2) -> None: + """Process-wide prior settings of a gnn_models entry (on every load: entries may differ, the patches are global).""" + pr = m.get("prior") + if pr: + set_prior_impl(pr.get("prior_impl", "frozen")) + set_prior_stack(pr, threads) + + +STARTUP: dict = {} # preload record (reported by /models) +_TLS = threading.local() + + +def _thread_limits(threads: int) -> None: + """numba and OpenMP thread counts are per thread: apply fastprior_pkg's limits once in every thread that predicts (the + preload runs in the main thread, requests in the server's worker threads).""" + if not _STATE.get("mode") or getattr(_TLS, "key", None) == (_STATE["stack"], threads): + return + from . import fastprior_pkg + fastprior_pkg._set_threads(int(threads)) + _TLS.key = (_STATE["stack"], threads) + + +def preload(name: str, reg, example=None) -> dict: + """Server start: load the default model (SHA check, prior stack, numba warmup) and, if given, predict one small example so + the first user request runs at normal speed. Synchronous (about 20-30 s on the 2-vCPU Space), before the queue opens. The + learned-prior entries (no prior stack) are loaded and run on the example too.""" + t0 = time.perf_counter() + load(name, reg) + STARTUP.update(model=name, load_and_warmup_s=time.perf_counter() - t0, numba_warmup_s=_STATE.get("warmup_s"), mode=_STATE.get("mode")) + also = [k for k in gnn_names(reg) if k != name and reg["gnn_models"][k].get("learned_prior") and available(k, reg)] + if example is not None and Path(example).exists(): + from .layout import prepare + t = time.perf_counter() + predict_gnn(prepare(str(example)), name, reg) + STARTUP["example_s"] = time.perf_counter() - t + for k in also: + t = time.perf_counter() + predict_gnn(prepare(str(example)), k, reg) + STARTUP.setdefault("also_s", {})[k] = time.perf_counter() - t + else: + for k in also: + load(k, reg) + STARTUP["total_s"] = time.perf_counter() - t0 + print("preload " + json.dumps({k: (round(v, 2) if isinstance(v, float) else v) for k, v in STARTUP.items()}), flush=True) + return dict(STARTUP) + + +def scene_from_prepared(lay) -> Scene: + """The Scene scene_from_gds builds (ground = net 0, signal bodies in file order, chip = ground bounding box, training stack), + from the prepared ground and conductor bodies.""" + G = lay.ground + chip = shapely.box(*G.bounds) + conds = [Conductor("G", "ground", G)] + [Conductor(n, "signal", g) for n, g in zip(lay.names, lay.conductors)] + return Scene(conds, chip, chip.difference(G), dict(DEFAULT_STACK), {}) + + +def predict_scene(P: I.Predictor, sc: Scene, alpha=None, local_gap=None, stack=None) -> dict: + """infer.Predictor.from_gds after the scene (same statements). stack: (eps_r, thickness_um) the prior is solved at (default the + scene's, i.e. the training stack); the embedding always uses the scene's stack.""" + eps_r, t_um = stack or (sc.stack["substrate_eps_r"], sc.stack["substrate_thickness_um"]) + physics = P.models[0][0].get("schema", {}).get("physics", {}) + if alpha is None: + alpha = physics.get("alpha") + if local_gap is None: + local_gap = physics.get("prior_method") == "local_gap" + proxy.NUM_THREADS = P.threads + if set(V2_KWARGS) & set(_STATE["patches"]): + from . import priorv2 + priorv2.clear() # its per-window traces would otherwise grow for the life of the server + start = time.perf_counter() + t1 = time.perf_counter() + from . import overlap as OV + 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 + row = None if fut else lt.add_tokens(sc, scene_graph(sc)) # overlap: the embedding runs in the worker during the priors + t2 = time.perf_counter() + priors = {} + if getattr(P, "surrogate", None) is not None: + from . import learned_prior + priors = learned_prior.priors(*P.surrogate, row) + elif not P.direct: + old = fastprior.ALPHA_GAP_SHARE + try: + if alpha is not None: + fastprior.ALPHA_GAP_SHARE = alpha + from . import levelpar + lvls = [.75, 1.5] if P.fast else [1.5, 3.] + if local_gap and levelpar.enabled(sc, lvls, P.threads): # the levels concurrently (spawned workers, same stack and statements) + priors.update(levelpar.solve(sc, lvls, P.threads, alpha, (eps_r, t_um))[0]) + lvls = [] + for p in lvls: + if local_gap: + from ._tlsq.embed.fastprior_loc import micro_mom_loc + with proxy.substrate("slab_open", t_um), _quiet_mixed_cast(): + mat, _, _ = micro_mom_loc(sc.conductors[0].geom, [c.geom for c in sc.conductors[1:]], eps_r=eps_r, ppg=p) + priors[p] = -mat + else: + if stack is not None and not on_training_stack(eps_r, t_um): + raise ValueError("the off-stack prior needs the local-gap prior method") + priors[p] = -I.CapacitanceMoM(max_cells=10**9, mesh="lite", cells_per_gap=p, + substrate="slab_open").compute(sc, list(row["edges"]))["matrix"] + finally: + fastprior.ALPHA_GAP_SHARE = old + t3 = time.perf_counter() + extra = {} + if fut is not None: + row, embed_s = fut.result() + extra = dict(overlap=True, geometry_worker=embed_s, geometry_wait_after_prior=time.perf_counter() - t3) + t3 = time.perf_counter() + C = P.from_features(row, priors) + t4 = time.perf_counter() + return dict(C=C, names=row["names"], timing=dict(scene=t1 - start, geometry=t2 - t1, prior=t3 - t2, network_and_pack=t4 - t3, + total=t4 - start, **extra)) + + +@contextlib.contextmanager +def _quiet_mixed_cast(): + """fastprior_pkg's mixed Cholesky casts the system to float32 first; on some windows the cast overflows and numpy warns + 'invalid value / overflow encountered in cast' before the package falls back to the float64 solve (expected; the result is checked + by iterative refinement). Silence exactly that warning, from that module, during the prior call only.""" + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message="(invalid value|overflow) encountered in cast", category=RuntimeWarning, + module=r"squadds\.ml\.capacitance\._core\.fastprior_pkg") + yield + + +def physical_checks(C: np.ndarray) -> dict: + n = len(C) + off = C[~np.eye(n, dtype=bool)] + sig = C[1:, 1:] + return {"symmetric_max_abs": float(np.max(np.abs(C - C.T))), "offdiag_all_negative": bool(np.all(off < 0)), + "signal_block_min_eig": float(np.linalg.eigvalsh(sig).min()) if n > 1 else None} + + +def physical_banner(res: dict) -> list[str]: + """Report lines that put a failed physical check first.""" + w = next((w for w in res.get("warnings") or [] if w.startswith("physical check failed")), None) + return [f"> **Not a physical matrix.** {w}", ""] if w else [] + + +def physical_warning(chk: dict, C: np.ndarray) -> str | None: + """Readable warning when the checks of physical_checks fail (None when the matrix passes).""" + bad = [] + if not chk["symmetric_max_abs"] <= 1e-6 * max(1.0, float(np.abs(C).max())): + bad.append(f"not symmetric (max |C - C^T| {chk['symmetric_max_abs']:.3g} fF)") + if not chk["offdiag_all_negative"]: + bad.append(f"{int(np.sum(C[~np.eye(len(C), dtype=bool)] >= 0))} off-diagonal entries are not negative") + if chk["signal_block_min_eig"] is not None and not chk["signal_block_min_eig"] > 0: + bad.append(f"the signal block is not positive definite (smallest eigenvalue {chk['signal_block_min_eig']:.4g} fF)") + if not bad: + return None + return ("physical check failed: " + "; ".join(bad) + ". This matrix is not physical: do not use it. A model that solves the physics " + "(flagship / Accurate, or the paper's model) is the safer choice, especially outside the trained component families.") + + +def predict_gnn(prepared, name: str, reg, substrate="Si (cryogenic, training)", thickness_um: float = 350.0, model_dir=None, + threads: int | None = None) -> dict: + """Full N x N Maxwell matrix (fF; ground row/column 0, self terms learned) of a prepared layout with a gnn_models entry.""" + m = reg["gnn_models"][name] + eps, t_um = reg.eps_of(substrate), float(thickness_um) + sub, sub_w = substrate_route(eps, t_um, solves_prior=not m.get("learned_prior")) + stack = None if on_training_stack(eps, t_um) else (eps, t_um) + t = time.perf_counter() + P = load(name, reg, model_dir, threads) + _thread_limits(P.threads) + load_s = time.perf_counter() - t + sc = scene_from_prepared(prepared) + try: + r = predict_scene(P, sc, stack=stack if sub["eps_rescale_factor"] is None else None) + except AssertionError as e: + raise ValueError(f"{name}: the prior or the features of this layout are not finite (no matrix returned): {e}") from e + C = np.asarray(r["C"], float) + if stack is not None and sub["eps_rescale_factor"] is not None: + C = C * sub["eps_rescale_factor"] + chk = physical_checks(C) + labels = ["G"] + list(prepared.names) + pr = m.get("prior") + lpr = m.get("learned_prior") + warnings = [w for w in prepared.warnings if "beyond the validated range" not in w] + if m.get("warning"): + warnings.insert(0, m["warning"]) + pw = physical_warning(chk, C) + if pw: + warnings.insert(0, pw) + warnings += sub_w + tm = r["timing"] + return {"names": labels, "matrix_fF": C.tolist(), "units": "fF", + "convention": "Maxwell matrix: diagonal = self (learned), off-diagonal = -mutual; row/column 0 = ground", + "self_capacitance": "predicted by the network (learned positive row-sum closure; trained). The ground self term is " + "trained at low weight and depends on the chip boundary: indicative only", + "model": name, "model_title": m.get("title"), "recipe": "GNN", "arm": m["arm"], "role": m.get("role"), + "ensemble": m.get("ensemble"), "weights_sha256": [c["sha256"] for c in m["checkpoints"]], + "prior": ({**pr, "prior_impl": _STATE["prior_impl"], "patches": _STATE.get("patches", []), "mode": _STATE.get("mode") or "frozen", + "numba_warmup_s": _STATE.get("warmup_s")} if pr else None), + "learned_prior": ({"name": lpr["name"], "sha256": lpr["checkpoint"]["sha256"], "ppg": lpr["ppg"]} if lpr else None), + "package_version": f"geomgnn {__version__}", + "registry_version": reg["version"], + "substrate": substrate if not isinstance(substrate, (int, float)) else f"custom eps={eps:g}", "eps_r": eps, "thickness_um": t_um, + "substrate_route": sub, "training_stack": {"eps_r": EPS_TRAIN, "thickness_um": T_TRAIN_UM}, + "timing_s": {"load_s": load_s, "geometry_s": tm["geometry"], "prior_s": tm["prior"], "network_s": tm["network_and_pack"], + "total_s": tm["total"], "threads": P.threads}, + "accuracy": m.get("accuracy") or {}, "checks": chk, "trust": None, "expected_error": {}, "warnings": warnings, + "stored": False} diff --git a/src/squadds/ml/capacitance/_core/farfield.py b/src/squadds/ml/capacitance/_core/farfield.py new file mode 100644 index 0000000000000000000000000000000000000000..09c356fd375c0472b41f34c0263b8521e9d7c6e3 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/farfield.py @@ -0,0 +1,73 @@ +"""farfield arms (agents/farfield/PROTOCOL.md sec. 2): the far-pair dipole form, installed on top of an installed v2m +prior (priorv2.installed(policy='fc', dip=True, margin=True)). install(arm, F, P, PV) patches the bound vendor modules +F (fastprior) / P (proxy) through PV (the priorv2 module patching them) and returns the undo callable. + a: half-space dipole for every far pair (v2m as deployed; values bit-identical, only timed) + b: slab dipole for signal-signal pairs of micro_mom's cross-pocket call; same-pocket and ground far pairs half-space + c: slab dipole for every far pair +Slab factor (1 + eps_r R(d)) / (1 + eps_r), R = PV.slab_R at the substrate thickness of P.SUBSTRATE, d = centroid +distance: PV.dipole_far_slab's expression, applied per pair.""" +import time + +import numpy as np +import shapely + +STATS = dict(cross_calls=0, cross_pairs=0, same_calls=0, same_pairs=0, slab_pairs=0, fill_s=0.0) +MODES = {'a': ('half', 'half'), 'b': ('slab_sig', 'half'), 'c': ('slab_all', 'slab_all')} + + +def reset(): + for k in STATS: + STATS[k] = 0.0 if k == 'fill_s' else 0 + + +def _dip(mode, frozen, P, PV, tag): + def dip(G, conds, pairs, eps_r=11.45, gap=None): + t = time.perf_counter() + v = frozen(G, conds, pairs, eps_r, gap) + pairs = np.asarray(pairs, int).reshape(-1, 2) + if mode != 'half': + cen = shapely.get_coordinates(shapely.centroid(np.array([G] + list(conds), dtype=object))) + d = np.hypot(*(cen[pairs[:, 0]] - cen[pairs[:, 1]]).T) + s = v * (1 + eps_r * PV.slab_R(d, float(P.SUBSTRATE["t_um"]), eps_r)) / (1 + eps_r) + use = np.ones(len(pairs), bool) if mode == 'slab_all' else (pairs > 0).all(1) + v = np.where(use, s, v) + STATS['slab_pairs'] += int(use.sum()) + STATS[f'{tag}_calls'] += 1 + STATS[f'{tag}_pairs'] += len(pairs) + STATS['fill_s'] += time.perf_counter() - t + return v + return dip + + +def install(arm, F, P, PV): + assert F.formula_prior is PV.formula_as_dipole and F._window_solve is not None, 'v2m fill must be installed first' + frozen = PV._FROZEN['dipole_far'] + assert F.dipole_far is frozen, 'dipole_far must be the vendor function under v2m' + saved = (F.dipole_far, F.formula_prior) + cross, same = (_dip(m, frozen, P, PV, t) for m, t in zip(MODES[arm], ('cross', 'same'))) + + def formula(G, conds, eps_r=11.45, step_um=None, R_gaps=None, pairs=None, gap=None, screen_um=None, workers=1, max_core=8): + F.dipole_far = same + try: + return PV.formula_as_dipole(G, conds, eps_r, step_um, R_gaps, pairs, gap, screen_um, workers, max_core) + finally: + F.dipole_far = cross + + F.dipole_far, F.formula_prior = cross, formula + + def undo(): + F.dipole_far, F.formula_prior = saved + return undo + + +def install_sentinel(F): + """G4: any far-fill call raises.""" + saved = (F.dipole_far, F.formula_prior) + + def boom(*a, **k): + raise RuntimeError('far fill called') + F.dipole_far = F.formula_prior = boom + + def undo(): + F.dipole_far, F.formula_prior = saved + return undo diff --git a/src/squadds/ml/capacitance/_core/fastmom.py b/src/squadds/ml/capacitance/_core/fastmom.py new file mode 100644 index 0000000000000000000000000000000000000000..6500ae97672071def8cd0ccf599369d544f30636 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/fastmom.py @@ -0,0 +1,147 @@ +"""Vectorised drop-in replacements for the H-matrix kernel of tlsq.embed.proxy (same mathematics, no per-row scipy +sparse slicing, no Python loop over image charges or ACA ranks). install() patches the loaded module in place.""" +import numpy as np + +from ._tlsq.embed import proxy as P + +_orig = {} + + +def _images(eps_r): + P._image_correction(np.zeros(1), eps_r) + key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) + w, D = P._IMG_CACHE[key][2:] + return np.asarray(w, float), np.asarray(D, float) ** 2 + + +def _kernel_init(self, c, wh, eps_r, perm): + _orig["Kernel.__init__"](self, c, wh, eps_r, perm) + N = self.N.tocsr() + N.sort_indices() + self.indptr, self.indices, self.data = N.indptr, N.indices, N.data + self.w, self.D2 = _images(eps_r) if self.img else (None, None) + + +def _corr(self, d): + return np.sqrt((d * d)[..., None] + self.D2) ** -1 @ self.w + + +def _row(self, i, b0, b1): + d = np.sqrt((self.x[i] - self.x[b0:b1]) ** 2 + (self.y[i] - self.y[b0:b1]) ** 2) + r = 1.0 / d + if self.img: + r += _corr(self, d) + s, e = self.indptr[i], self.indptr[i + 1] + if e > s: + ix = self.indices[s:e] + lo, hi = np.searchsorted(ix, (b0, b1)) + if hi > lo: + r[ix[lo:hi] - b0] += self.data[s + lo:s + hi] + return r / self.k + + +def _block(self, a0, a1, b0, b1): + d = np.sqrt((self.x[a0:a1, None] - self.x[None, b0:b1]) ** 2 + (self.y[a0:a1, None] - self.y[None, b0:b1]) ** 2) + corr = _corr(self, d) if self.img else None + if a0 == b0: + d[np.arange(a1 - a0), np.arange(a1 - a0)] = 1.0 + A = 1.0 / d + if corr is not None: + A += corr + s, e = self.indptr[a0], self.indptr[a1] + if e > s: + ix = self.indices[s:e] + rr = np.repeat(np.arange(a1 - a0), np.diff(self.indptr[a0:a1 + 1])) + m = (ix >= b0) & (ix < b1) + np.add.at(A, (rr[m], ix[m] - b0), self.data[s:e][m]) + return A / self.k + + +def _aca(K, a0, a1, b0, b1, eps, max_rank): + m, n = a1 - a0, b1 - b0 + R = min(m, n, max_rank) + U, V = np.empty((m, R)), np.empty((n, R)) + used_r, used_c = np.zeros(m, bool), np.zeros(n, bool) + i, norm2, k = 0, 0.0, 0 + for _ in range(R): + r = K.row(a0 + i, b0, b1) + if k: + r -= V[:, :k] @ U[i, :k] + rm = np.where(used_c, 0.0, np.abs(r)) + j = int(np.argmax(rm)) + if rm[j] == 0.0: + break + v = r / r[j] + u = K.row(b0 + j, a0, a1) + if k: + u -= U[:, :k] @ V[j, :k] + used_r[i], used_c[j] = True, True + nu, nv = float(u @ u), float(v @ v) + norm2 += nu * nv + (2 * float((U[:, :k].T @ u) @ (V[:, :k].T @ v)) if k else 0.0) + U[:, k], V[:, k] = u, v + k += 1 + if nu * nv <= eps**2 * norm2: + break + um = np.where(used_r, 0.0, np.abs(u)) + i = int(np.argmax(um)) + if um[i] == 0.0: + break + else: + return None + return U[:, :k].copy(), V[:, :k].copy() + + +def _image_correction(d, eps_r, exact=False): + if exact or P.SUBSTRATE["model"] == "halfspace": + return _orig["image"](d, eps_r, exact) + _orig["image"](np.zeros(1), eps_r) + key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) + du, T = P._IMG_CACHE[key][:2] + u = np.asarray(d, float) / du + j = np.minimum(u.astype(np.int64), len(T) - 2) + f = u - j + t0 = T[j] + return t0 + f * (T[j + 1] - t0) + + +REFINE = dict(steps=6, tol=1e-13) + + +def _chol_solve(A, B): + from scipy.linalg import cho_factor, cho_solve + from scipy.linalg.blas import dsymm + + try: + cf = cho_factor(A.astype(np.float32, order="F"), lower=True, overwrite_a=True, check_finite=False) + except np.linalg.LinAlgError: + return _orig["chol_solve"](A, B) + B = np.asfortranarray(B, dtype=float) + X = cho_solve(cf, B.astype(np.float32), check_finite=False).astype(float) + bn = np.linalg.norm(B, axis=0) + for _ in range(REFINE["steps"]): + R = B - dsymm(1.0, A, X, side=0, lower=1) + if (np.linalg.norm(R, axis=0) <= REFINE["tol"] * bn).all(): + return X + X += cho_solve(cf, R.astype(np.float32), check_finite=False) + return _orig["chol_solve"](A, B) + + +def install(dense_max=None, mixed=False): + if not _orig: + _orig["Kernel.__init__"] = P._Kernel.__init__ + _orig.update(row=P._Kernel.row, block=P._Kernel.block, aca=P._aca, dense_max=P.DENSE_MAX, image=P._image_correction, + chol_solve=P._chol_solve) + P._Kernel.__init__, P._Kernel.row, P._Kernel.block, P._aca = _kernel_init, _row, _block, _aca + P._image_correction = _image_correction + P._chol_solve = _chol_solve if mixed else _orig["chol_solve"] + if dense_max is not None: + P.DENSE_MAX = dense_max + + +def uninstall(): + if _orig: + P._Kernel.__init__, P._Kernel.row, P._Kernel.block, P._aca = (_orig["Kernel.__init__"], _orig["row"], _orig["block"], + _orig["aca"]) + P._image_correction, P._chol_solve = _orig["image"], _orig["chol_solve"] + P.DENSE_MAX = _orig["dense_max"] + _orig.clear() diff --git a/src/squadds/ml/capacitance/_core/fastprior_pkg.py b/src/squadds/ml/capacitance/_core/fastprior_pkg.py new file mode 100644 index 0000000000000000000000000000000000000000..08b0ab64b541c08ec977fd2c07cda233accd1955 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/fastprior_pkg.py @@ -0,0 +1,1291 @@ +"""fastprior_pkg: switchable speed components for the FROZEN physical prior of the P2d GNN (micro_mom_loc at ppg 1.5 +and 3, alpha 0.49685219816506904), installed by monkeypatching the loaded frozen vendor modules (never edited). + + import fastprior_pkg as fp + fp.install(mode="exact") # fv + parallel + hmat_vec (+ gpu if CUDA) (+ mixed if gated) + fp.install(mode="exact_compiled") # exact + numba H-matrix operator (closer to the dense solve; VAL-tested, A5) + fp.install(mode="certified") # exact + compiled + Rayleigh-Ritz solves with an error estimate (fp.certificates()) + fp.install(components=["fv", "compiled"]) # explicit set + fp.uninstall() + +Components (protocol and gates: agents/fastprior_pkg/PROTOCOL.md; sources cited per section, code reused verbatim +where possible, only module bindings changed): + fv value-preserving rejection-tail fix of the windowed solve (rejtail; bit-identical) + parallel forked window workers (the vendor's micro_mom(workers=k)); threads per worker limited (bit-identical) + hmat_vec the frozen H-matrix PCG (> 12,000 panels) with a vectorised kernel, frozen tolerances (<= 1e-6) + compiled numba H-matrix operator for the H-matrix PCG path: closer to the exact dense solve than the frozen + H-matrix, but up to 1.4e-5 from it (fails strict parity; opt-in, used by certified) + gpu dense assembly + Cholesky on CUDA (only when torch.cuda is available) + mixed float32 Cholesky + float64 iterative refinement (only if gated, see MIXED_GATED) + ritz Rayleigh-Ritz window / local solves (template start, tau 1e-3, dense <= 3,000 panels), certified +Parallel windows fork (the vendor's pool); on macOS they are always off (Accelerate is not fork-safe) and the prior +runs serially. Environment: TLSQ_PRIOR_CPUS (CPUs; default cgroup / affinity aware), TLSQ_PRIOR_WORKERS (window workers; default = +CPUs), TLSQ_PRIOR_MODE (default mode of install() without arguments). +Value hook: install(..., value_patch=fn) with fn(F, P, FL) -> undo callable (e.g. a prior-v2 patch once it passes).""" +from __future__ import annotations + +import contextlib +import inspect +import json +import os +import sys +import tempfile +import time + +import numpy as np +from scipy.linalg import cho_factor, cho_solve, eigh + +FROZEN_DENSE_MAX = 12000 # the frozen proxy.DENSE_MAX: decides which attempts the frozen code could not solve (fv) +RITZ_CAL = 1.825367354114339 # varritz S0 calibration of the block-Jacobi estimate (s0_choice.json) +MIXED_GATED = True # PROTOCOL.md G3 passed on Discovery x86 (A5): prior <= 4.4e-10, final matrix <= 4.5e-7 +COMPONENTS = ("fv", "parallel", "hmat_vec", "compiled", "gpu", "mixed", "ritz") +CFG = dict(device="cuda", gpu_min=2000, gpu_dense_max=60000, rows=4096, ritz_tau=1e-3, ritz_maxit=12, ritz_dense_n=3000, + ritz_start="tmpl", refine_steps=6, refine_tol=1e-13) +STATE = dict(mode=None, components=(), cpus=1, workers=1, gpu=False, value_patch=None, target=None, parallel_off=None) +F = P = FL = None # bound vendor modules: fastprior, proxy, fastprior_loc +_ORIG: dict = {} +_UNDO: list = [] +_PARENT = [0] +_CHILD = [False] +_TP: list = [] +STATS = dict(compiled_calls=0) # per-process counters +LOG: list = [] # Ritz / exact solve records of the running prior call (certified mode) +CERTS: list = [] # one certificate per micro_mom_loc call (certified mode) +_CERT_FILE = [None] + + +# ------------------------------------------------------------------------------------------------ binding / CPUs + + +def bind(target="auto"): + """Bind the frozen vendor modules: 'stage' (tlsq.embed of the geomfast stage), 'geomgnn' (the GNN Space bundle, + geomgnn._tlsq.embed), or a tuple (fastprior, proxy, fastprior_loc). 'auto': whichever is loaded, else stage.""" + global F, P, FL + if isinstance(target, tuple): + F, P, FL = target + STATE["target"] = "modules" + return F, P, FL + if target == "auto": + target = "geomgnn" if "squadds.ml.capacitance._core._tlsq.embed.fastprior" in sys.modules else "stage" + if target == "stage" and "tlsq.embed.fastprior" not in sys.modules: + try: + import tlsq.embed.fastprior # noqa: F401 + except ImportError: + target = "geomgnn" + if target == "geomgnn": + from squadds.ml.capacitance._core._tlsq.embed import fastprior as F_, fastprior_loc as FL_, proxy as P_ + else: + from tlsq.embed import fastprior as F_, fastprior_loc as FL_, proxy as P_ + F, P, FL = F_, P_, FL_ + STATE["target"] = target + return F, P, FL + + +def _cgroup_cpus(): + """CPU quota of this process's cgroup (v2 cpu.max along the cgroup path, or v1 cfs quota / period); None if none.""" + best = None + try: + lines = open("/proc/self/cgroup").read().splitlines() + except OSError: + lines = [] + paths = [] + for ln in lines: + parts = ln.split(":", 2) + if len(parts) == 3 and parts[0] == "0" and parts[1] == "": + rel = parts[2].strip("/") + segs = rel.split("/") if rel else [] + for k in range(len(segs), -1, -1): + paths.append(os.path.join("/sys/fs/cgroup", *segs[:k], "cpu.max")) + paths.append("/sys/fs/cgroup/cpu.max") + for p in paths: + try: + q, per = open(p).read().split()[:2] + except (OSError, ValueError): + continue + if q != "max" and float(per) > 0: + v = float(q) / float(per) + best = v if best is None else min(best, v) + for d in ("/sys/fs/cgroup/cpu", "/sys/fs/cgroup/cpu,cpuacct"): + try: + q = int(open(f"{d}/cpu.cfs_quota_us").read()) + per = int(open(f"{d}/cpu.cfs_period_us").read()) + except (OSError, ValueError): + continue + if q > 0 and per > 0: + best = q / per if best is None else min(best, q / per) + return best + + +def detect_cpus() -> int: + """CPUs this process may use: TLSQ_PRIOR_CPUS, else min(cgroup quota, affinity, os.cpu_count()).""" + env = os.environ.get("TLSQ_PRIOR_CPUS") + if env: + return max(1, int(env)) + cands = [os.cpu_count() or 1] + q = _cgroup_cpus() + if q: + cands.append(max(1, int(q))) + if hasattr(os, "sched_getaffinity"): + cands.append(len(os.sched_getaffinity(0))) + return max(1, min(cands)) + + +def _set_threads(n: int) -> None: + """Limit BLAS / OpenMP (threadpoolctl), numba and the vendor's thread pool to n threads in this process.""" + try: + from threadpoolctl import threadpool_limits + _TP[:] = [threadpool_limits(n)] + except Exception: # noqa: BLE001 (no threadpoolctl / Accelerate: env vars at process start decide) + pass + if P is not None: + P.NUM_THREADS = n + try: + import numba + numba.set_num_threads(max(1, min(n, numba.config.NUMBA_NUM_THREADS))) + except Exception: # noqa: BLE001 + pass + + +# ------------------------------------------------------------------------------------------------ fv +# deploy/geomgnn/src/geomgnn/rejtail_fv.py (= scripts/rejtail/rt.py policy fv), keep_last_solved=True (frozen stage), +# with the "doomed" test on the frozen DENSE_MAX (a GPU-raised DENSE_MAX must not change which attempts solve). + + +def _fv_solve(c, wh, o, metals, cols, eps_r): + t = time.perf_counter() + t_asm = 0.0 + if len(c) <= P.DENSE_MAX: + A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) + t_asm = time.perf_counter() - t + Bm = (o[:, None] == cols[None, :]).astype(float) + Q = F._sym_solve(A, Bm) + else: + Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)[:, cols] + return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1), t_asm + + +def fv_window_solve(metals, n_core, h, budget, eps_r, all_rhs, levels=()): + if all_rhs: + return _ORIG["window_solve"](metals, n_core, h, budget, eps_r, all_rhs, levels) + cols = np.arange(1, 1 + n_core) + t_mesh = t_asm = t_sol = 0.0 + hh, cap, refined, majority = h, budget, 0, False + hist = [] + while True: + t = time.perf_counter() + if not refined: + c, wh, o, hh, n_raw = F._lite_mesh(metals, hh, cap, n_core, levels) + elif levels: + c, wh, o, hh, n_raw = F._graded_mesh(metals, n_core, hh, levels, majority) + else: + c, wh, o, hh, n_raw = P.mesh_flagship(metals, hh, cap, majority=majority) + t_mesh += time.perf_counter() - t + if not np.all(np.bincount(o, minlength=len(metals)) > 0): + hist.append(("doomed",) if len(c) > FROZEN_DENSE_MAX else ("mesh", c, wh, o)) + ok = False + else: + t = time.perf_counter() + try: + R, ta = _fv_solve(c, wh, o, metals, cols, eps_r) + t_asm += ta + hist.append(("R", R)) + ok = True + except np.linalg.LinAlgError: + hist.append(("err",)) + ok = False + t_sol += time.perf_counter() - t + if ok or majority: + break + if refined < F.LITE_REFINE: + hh, cap, refined = hh / 2, np.inf, refined + 1 + else: + majority = True + if ok: + R = hist[-1][1] + else: + R = None + t = time.perf_counter() + for e in reversed(hist): + if e[0] == "R": + R = e[1] + break + if e[0] == "mesh": + try: + R = _fv_solve(e[1], e[2], e[3], metals, cols, eps_r)[0] + break + except np.linalg.LinAlgError: + continue + t_sol += time.perf_counter() - t + assert R is not None, "no attempt solved (the frozen code raises here too)" + return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, + "assemble_s": t_asm, "solve_s": t_sol} + + +# ------------------------------------------------------------------------------------------------ parallel windows +# The vendor's micro_mom(workers=k) (ProcessPoolExecutor, fork); windows inherit the layout through fastprior._LITE. + + +def _micro_mom(*args, **kw): + ba = _ORIG["micro_mom_sig"].bind(*args, **kw) + if sys.platform == "darwin": # never fork on macOS, whatever the caller asked for + ba.arguments["workers"] = 1 + if STATE["workers"] > 1 and ba.arguments.get("workers", 1) <= 1: + ba.arguments["workers"] = STATE["workers"] + _PARENT[0] = os.getpid() + return _ORIG["micro_mom"](*ba.args, **ba.kwargs) + + +def _child_setup(): + """First window job in a forked worker: threads per worker = CPUs // workers; CUDA is never used after fork.""" + if _CHILD[0] or os.getpid() == _PARENT[0]: + return + _CHILD[0] = True + nw = max(1, min(STATE["workers"], len(F._LITE.get("cores", [0])))) + _set_threads(max(1, STATE["cpus"] // nw)) + if STATE["gpu"]: + STATE["gpu"] = False + P.DENSE_MAX = FROZEN_DENSE_MAX + + +def _lite_job(k): + _child_setup() + if _CHILD[0] and _CERT_FILE[0]: + i0 = len(LOG) + out = _ORIG["lite_job"](k) + recs = LOG[i0:] + for r in recs: + r["window"] = int(k) + with open(_CERT_FILE[0], "a") as f: + f.write("".join(json.dumps(_jsonable(r)) + "\n" for r in recs)) + return out + i0 = len(LOG) + out = _ORIG["lite_job"](k) + for r in LOG[i0:]: + r["window"] = int(k) + return out + + +def _jsonable(r): + return {k: (v.tolist() if isinstance(v, np.ndarray) else (float(v) if isinstance(v, np.floating) else v)) for k, v in r.items()} + + +# ------------------------------------------------------------------------------------------------ compiled operator +# scripts/varritz/hmat.py and scripts/varritz/fastop.py (numba H-matrix of the far kernel, exact near field, FFT image +# term, block-Jacobi leaf factors on the frozen cluster tree); bodies verbatim, `P` bound late. + +os.environ.setdefault("NUMBA_THREADING_LAYER", "workqueue") # fork-safe; GNU OpenMP aborts in forked window workers +try: + import numba as nb + nb.config.THREADING_LAYER = os.environ["NUMBA_THREADING_LAYER"] +except ImportError: # compiled / ritz unavailable without numba + nb = None + +if nb is not None: + @nb.njit(fastmath=True, cache=True) + def _krow(x, y, i, b0, b1, out): + for j in range(b0, b1): + dx, dy = x[i] - x[j], y[i] - y[j] + r2 = dx * dx + dy * dy + out[j - b0] = 1.0 / np.sqrt(r2) if r2 > 0 else 0.0 + + @nb.njit(fastmath=True, cache=True) + def _aca(x, y, a0, a1, b0, b1, eps, kmax, U, V): + m, n = a1 - a0, b1 - b0 + used_r = np.zeros(m, np.bool_) + used_c = np.zeros(n, np.bool_) + r = np.empty(n) + u = np.empty(m) + norm2 = 0.0 + i = 0 + k = 0 + while k < min(m, n, kmax): + _krow(x, y, a0 + i, b0, b1, r) + for q in range(k): + ui = U[i, q] + for j in range(n): + r[j] -= ui * V[j, q] + used_r[i] = True + jbest, vbest = -1, 0.0 + for j in range(n): + if not used_c[j] and abs(r[j]) > vbest: + vbest, jbest = abs(r[j]), j + if jbest < 0 or vbest == 0.0: + return k + piv = r[jbest] + for j in range(n): + V[j, k] = r[j] / piv + _krow(x, y, b0 + jbest, a0, a1, u) + for q in range(k): + vj = V[jbest, q] + for ii in range(m): + u[ii] -= vj * U[ii, q] + for ii in range(m): + U[ii, k] = u[ii] + used_c[jbest] = True + nu, nv = 0.0, 0.0 + for ii in range(m): + nu += u[ii] * u[ii] + for j in range(n): + nv += V[j, k] * V[j, k] + cross = 0.0 + for q in range(k): + su, sv = 0.0, 0.0 + for ii in range(m): + su += u[ii] * U[ii, q] + for j in range(n): + sv += V[j, k] * V[j, q] + cross += su * sv + norm2 += nu * nv + 2.0 * cross + k += 1 + if nu * nv <= eps * eps * norm2: + return k + ibest, ub = -1, 0.0 + for ii in range(m): + if not used_r[ii] and abs(u[ii]) > ub: + ub, ibest = abs(u[ii]), ii + if ibest < 0: + return k + i = ibest + return -1 if k >= kmax and k < min(m, n) else k + + @nb.njit(parallel=True, cache=True) + def _build(x, y, lows, eps, kmax, Ubuf, Vbuf, uoff, voff, ranks, dense, doff, ddata): + nl = lows.shape[0] + for b in nb.prange(nl): + a0, a1, b0, b1 = lows[b, 0], lows[b, 1], lows[b, 2], lows[b, 3] + m, n = a1 - a0, b1 - b0 + U = Ubuf[uoff[b]:uoff[b] + m * kmax].reshape(m, kmax) + V = Vbuf[voff[b]:voff[b] + n * kmax].reshape(n, kmax) + ranks[b] = _aca(x, y, a0, a1, b0, b1, eps, kmax, U, V) + nd = dense.shape[0] + for b in nb.prange(nd): + a0, a1, b0, b1 = dense[b, 0], dense[b, 1], dense[b, 2], dense[b, 3] + n = b1 - b0 + row = np.empty(n) + for i in range(a0, a1): + _krow(x, y, i, b0, b1, row) + ddata[doff[b] + (i - a0) * n:doff[b] + (i - a0 + 1) * n] = row + + @nb.njit(parallel=True, cache=True) + def _apply(X, lows, kmax, Ubuf, Vbuf, uoff, voff, ranks, dense, doff, ddata, nthr, Y): + n, mc = X.shape + buf = np.zeros((nthr, n, mc)) + nl = lows.shape[0] + nd = dense.shape[0] + tot = nl + nd + for t in nb.prange(nthr): + B = buf[t] + for b in range(t, tot, nthr): + if b < nl: + a0, a1, b0, b1 = lows[b, 0], lows[b, 1], lows[b, 2], lows[b, 3] + m, nn = a1 - a0, b1 - b0 + k = ranks[b] + U = Ubuf[uoff[b]:uoff[b] + m * kmax].reshape(m, kmax)[:, :k] + V = Vbuf[voff[b]:voff[b] + nn * kmax].reshape(nn, kmax)[:, :k] + B[a0:a1] += U @ (V.T @ X[b0:b1]) + B[b0:b1] += V @ (U.T @ X[a0:a1]) + else: + q = b - nl + a0, a1, b0, b1 = dense[q, 0], dense[q, 1], dense[q, 2], dense[q, 3] + D = ddata[doff[q]:doff[q] + (a1 - a0) * (b1 - b0)].reshape(a1 - a0, b1 - b0) + B[a0:a1] += D @ X[b0:b1] + if a0 != b0: + B[b0:b1] += D.T @ X[a0:a1] + for i in nb.prange(n): + for c in range(mc): + s = 0.0 + for t in range(nthr): + s += buf[t, i, c] + Y[i, c] = s + + @nb.njit(parallel=True, fastmath=True, cache=True) + def _far(x, y, Xt, Y, T=64): + m, n = Xt.shape + nt = (n + T - 1) // T + for it in nb.prange(nt): + r = np.empty(n) + for i in range(it * T, min(n, it * T + T)): + xi, yi = x[i], y[i] + for j in range(n): + dx, dy = xi - x[j], yi - y[j] + r[j] = dx * dx + dy * dy + r[i] = 1.0 + for j in range(n): + r[j] = 1.0 / np.sqrt(r[j]) + r[i] = 0.0 + for k in range(m): + s = 0.0 + for j in range(n): + s += r[j] * Xt[k, j] + Y[i, k] = s + + +def _numba(): + if nb is None: + raise ImportError("numba is required for the compiled / ritz components") + return dict(nb=nb, build=_build, apply=_apply, far=_far) + + +class HFar: + """Far kernel sum_{j != i} x_j / d_ij as an H-matrix (frozen block plan: leaf 128, eta 2). (varritz/hmat.py)""" + + def __init__(self, c, leaf=128, eta=2.0, eps=1e-7, kmax=48, nthr=None): + K = _numba() + self.perm, nodes = P._cluster_tree(c, leaf) + self.x, self.y = np.ascontiguousarray(c[self.perm, 0]), np.ascontiguousarray(c[self.perm, 1]) + plan_l, plan_d = [], [] + + def leafq(k): + return nodes[k][4] < 0 + + def rec(s, t): + a0, a1, lo_s, hi_s, sl, sr = nodes[s] + b0, b1, lo_t, hi_t, tl, tr = nodes[t] + if s == t: + if leafq(s): + plan_d.append((a0, a1, a0, a1)) + else: + rec(sl, sl), rec(sr, sr), rec(sl, sr) + return + gap = np.maximum(0.0, np.maximum(lo_s - hi_t, lo_t - hi_s)) + diam = min(np.sqrt(((hi_s - lo_s) ** 2).sum()), np.sqrt(((hi_t - lo_t) ** 2).sum())) + if diam <= eta * np.sqrt((gap**2).sum()): + plan_l.append((a0, a1, b0, b1)) + elif leafq(s) and leafq(t): + plan_d.append((a0, a1, b0, b1)) + elif leafq(s): + rec(s, tl), rec(s, tr) + elif leafq(t): + rec(sl, t), rec(sr, t) + else: + for u in (sl, sr): + for v in (tl, tr): + rec(u, v) + + rec(0, 0) + lows = np.array(plan_l, np.int64).reshape(-1, 4) + dense = np.array(plan_d, np.int64).reshape(-1, 4) + m = lows[:, 1] - lows[:, 0] + nn = lows[:, 3] - lows[:, 2] + uoff = np.r_[0, np.cumsum(m * kmax)][:-1] + voff = np.r_[0, np.cumsum(nn * kmax)][:-1] + Ubuf, Vbuf = np.zeros(int((m * kmax).sum())), np.zeros(int((nn * kmax).sum())) + dsz = (dense[:, 1] - dense[:, 0]) * (dense[:, 3] - dense[:, 2]) + doff = np.r_[0, np.cumsum(dsz)][:-1] + ddata = np.zeros(int(dsz.sum())) + ranks = np.zeros(len(lows), np.int64) + K["build"](self.x, self.y, lows, eps, kmax, Ubuf, Vbuf, uoff, voff, ranks, dense, doff, ddata) + bad = ranks < 0 + if bad.any(): # rank above kmax: these blocks become dense + extra = lows[bad] + lows = lows[~bad] + keep_u, keep_v = uoff[~bad], voff[~bad] + ranks = ranks[~bad] + uoff, voff = keep_u, keep_v + esz = (extra[:, 1] - extra[:, 0]) * (extra[:, 3] - extra[:, 2]) + eoff = np.r_[0, np.cumsum(esz)][:-1] + edata = np.zeros(int(esz.sum())) + K["build"](self.x, self.y, np.zeros((0, 4), np.int64), eps, kmax, Ubuf, Vbuf, uoff[:0], voff[:0], ranks[:0], extra, eoff, edata) + doff = np.r_[doff, eoff + len(ddata)] + ddata = np.r_[ddata, edata] + dense = np.r_[dense, extra] + self.args = (lows, kmax, Ubuf, Vbuf, uoff, voff, ranks, dense, doff, ddata) + self.nthr = nthr or K["nb"].get_num_threads() + self.n_low, self.n_dense, self.mean_rank = len(lows), len(dense), float(ranks.mean()) if len(ranks) else 0.0 + self.n_converted = int(bad.sum()) + + def __call__(self, X): + Xp = np.ascontiguousarray(X[self.perm]) + Yp = np.empty_like(Xp) + _numba()["apply"](Xp, *self.args, self.nthr, Yp) + Y = np.empty_like(Yp) + Y[self.perm] = Yp + return Y + + +def _lagrange(u, q): + i0 = np.floor(u).astype(np.int64) - (q // 2 - 1) + t = u - i0 + w = np.ones((len(u), q)) + for a in range(q): + for b in range(q): + if a != b: + w[:, a] *= (t - b) / (a - b) + return i0, w + + +class ImageConv: + """Smooth finite-substrate image kernel (proxy._image_correction, exact series) by grid convolution. (fastop.py)""" + + def __init__(self, c, eps_r, spacing_frac=1 / 16, q=6): + from scipy.sparse import csr_matrix + P._image_correction(np.zeros(1), eps_r) + key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) + _, _, w, D = P._IMG_CACHE[key] + self.w, self.D = w, D + h = spacing_frac * D.min() + lo = c.min(0) - (q // 2 + 1) * h + u = (c - lo) / h + ix0, wx = _lagrange(u[:, 0], q) + iy0, wy = _lagrange(u[:, 1], q) + nx, ny = int(ix0.max()) + q + 1, int(iy0.max()) + q + 1 + rows = np.repeat(np.arange(len(c)), q * q) + gx = (ix0[:, None, None] + np.arange(q)[None, :, None]) * np.ones((1, 1, q), np.int64) + gy = (iy0[:, None, None] + np.arange(q)[None, None, :]) * np.ones((1, q, 1), np.int64) + vals = (wx[:, :, None] * wy[:, None, :]).ravel() + self.W = csr_matrix((vals, (rows, (gx * ny + gy).ravel())), shape=(len(c), nx * ny)) + self.nx, self.ny = nx, ny + Lx, Ly = 2 * nx, 2 * ny + ax = np.minimum(np.arange(Lx), Lx - np.arange(Lx)) * h + ay = np.minimum(np.arange(Ly), Ly - np.arange(Ly)) * h + rho = np.sqrt(ax[:, None] ** 2 + ay[None, :] ** 2) + Kk = sum(wn / np.sqrt(rho**2 + Dn * Dn) for wn, Dn in zip(w, D)) + self.Kf = np.fft.rfft2(Kk) + self.L = (Lx, Ly) + + def __call__(self, X): + G = (self.W.T @ X).reshape(self.nx, self.ny, -1) + out = np.empty((self.nx * self.ny, X.shape[1])) + for k in range(X.shape[1]): + f = np.fft.irfft2(np.fft.rfft2(G[:, :, k], s=self.L) * self.Kf, s=self.L)[: self.nx, : self.ny] + out[:, k] = f.ravel() + return self.W @ out + + +class FastOp: + """The frozen panel operator, matrix-free; bj(): block-Jacobi on the frozen cluster tree's leaves. (fastop.py)""" + + def __init__(self, c, wh, o, eps_r, M, leaf=128, h_min_n=4000, h_eps=1e-8): + from scipy.sparse import csr_matrix + t = time.perf_counter() + self.H = None + if len(c) >= h_min_n: + self.H = HFar(c, eps=h_eps) + self.t_hmat = time.perf_counter() - t + t = time.perf_counter() + self.c, self.wh, self.o, self.n, self.M = c, wh, o, len(c), M + self.B = (o[:, None] == np.arange(M)[None]).astype(float) + self.k = 4 * np.pi * P.EPS0_FF_PER_UM * (eps_r + 1) / 2 + self.x, self.y = np.ascontiguousarray(c[:, 0]), np.ascontiguousarray(c[:, 1]) + ii, jj = P._near_pairs(c, wh.max(1)) + d = np.sqrt(((c[ii] - c[jj]) ** 2).sum(1)) + near = 0.5 * (P.rect_potential(c[ii], c[jj], wh[jj]) + P.rect_potential(c[jj], c[ii], wh[ii])) - 1.0 / d + dg = P.rect_self(wh[:, 0], wh[:, 1]) + n = self.n + self.N = csr_matrix((np.r_[near, near, dg], (np.r_[ii, jj, np.arange(n)], np.r_[jj, ii, np.arange(n)])), shape=(n, n)) + self.t_near = time.perf_counter() - t + t = time.perf_counter() + self.img = ImageConv(c, eps_r) if P._image_correction(np.zeros(1), eps_r) is not None else None + self.t_img = time.perf_counter() - t + t = time.perf_counter() + perm, nodes = P._cluster_tree(c, leaf) + self.leaves = [] + img0 = P._image_correction + for a0, a1, lo, hi, l, r in nodes: + if l >= 0: + continue + ix = np.sort(perm[a0:a1]) + cc = c[ix] + dd = np.sqrt(((cc[:, None] - cc[None]) ** 2).sum(-1)) + np.fill_diagonal(dd, 1.0) + A = 1.0 / dd + np.fill_diagonal(A, 0.0) + A += self.N[ix][:, ix].toarray() + if self.img is not None: + np.fill_diagonal(dd, 0.0) + A += img0(dd, eps_r, exact=True) + self.leaves.append((ix, cho_factor(A / self.k, lower=True))) + self.t_blocks = time.perf_counter() - t + + def matvec(self, X): + X = np.ascontiguousarray(X, dtype=np.float64) + if self.H is not None: + Y = self.H(X) + else: + Y = np.empty_like(X) + _numba()["far"](self.x, self.y, np.ascontiguousarray(X.T), Y) + Y += self.N @ X + if self.img is not None: + Y += self.img(X) + return Y / self.k + + def bj(self, R): + Z = np.zeros_like(R) + for ix, cf in self.leaves: + Z[ix] = cho_solve(cf, R[ix], check_finite=False) + return Z + + +def compiled_pcg(c, wh, o, n_metals, eps_r): + """Panel charges (n, n_metals) by the frozen block-Jacobi PCG (proxy._HMatrix.pcg: all columns, stop when every + column's relative residual < HMAT tol, LinAlgError after maxit) on the compiled operator. A zero right-hand-side + column (a metal without panels) gives residual 0/0 = NaN forever, so it raises at once instead of after maxit.""" + STATS["compiled_calls"] += 1 + B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float) + bn = np.sqrt((B * B).sum(0)) + if not np.all(bn > 0): + raise np.linalg.LinAlgError("H-matrix PCG: a metal without panels (zero right-hand side; frozen: NaN residual)") + op = FastOp(c, wh, o, eps_r, n_metals, h_eps=P.HMAT["eps"]) + tol, maxit = P.HMAT["tol"], P.HMAT["maxit"] + X, R = np.zeros_like(B), B.copy() + Z = op.bj(R) + Pd, rz = Z.copy(), (R * Z).sum(0) + res = np.inf + for it in range(maxit): + AP = op.matvec(Pd) + al = rz / (Pd * AP).sum(0) + X += al * Pd + R -= al * AP + res = (np.sqrt((R * R).sum(0)) / bn).max() + if res < tol: + return X + if not np.isfinite(res): + break + Z = op.bj(R) + rzn = (R * Z).sum(0) + Pd = Z + (rzn / rz) * Pd + rz = rzn + raise np.linalg.LinAlgError(f"compiled H-matrix PCG did not converge (residual {res:.1e})") + + +def _mom_solve_fast(c, wh, o, n_metals, eps_r=11.45, dense_max=None): + n = len(c) + if n <= (P.DENSE_MAX if dense_max is None else dense_max) or "compiled" not in STATE["components"]: + return _ORIG["mom_solve_fast"](c, wh, o, n_metals, eps_r, dense_max) + return compiled_pcg(c, wh, o, n_metals, eps_r) + + +# ------------------------------------------------------------------------------------------------ hmat_vec (fastmom.py) +# scripts/geomfast/fastmom.py: the frozen H-matrix (same cluster tree, ACA, block-Jacobi PCG, FROZEN tolerances) with a +# vectorised kernel (no per-row scipy sparse slicing, no Python loop over image charges or ACA ranks). Only the H-matrix +# kernel is patched (proxy._image_correction and the dense path are untouched). + + +def _hv_images(eps_r): + P._image_correction(np.zeros(1), eps_r) + key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) + w, D = P._IMG_CACHE[key][2:] + return np.asarray(w, float), np.asarray(D, float) ** 2 + + +def _hv_kernel_init(self, c, wh, eps_r, perm): + _ORIG["Kernel.__init__"](self, c, wh, eps_r, perm) + N = self.N.tocsr() + N.sort_indices() + self.indptr, self.indices, self.data = N.indptr, N.indices, N.data + self.w, self.D2 = _hv_images(eps_r) if self.img else (None, None) + + +def _hv_corr(self, d): + return np.sqrt((d * d)[..., None] + self.D2) ** -1 @ self.w + + +def _hv_row(self, i, b0, b1): + d = np.sqrt((self.x[i] - self.x[b0:b1]) ** 2 + (self.y[i] - self.y[b0:b1]) ** 2) + r = 1.0 / d + if self.img: + r += _hv_corr(self, d) + s, e = self.indptr[i], self.indptr[i + 1] + if e > s: + ix = self.indices[s:e] + lo, hi = np.searchsorted(ix, (b0, b1)) + if hi > lo: + r[ix[lo:hi] - b0] += self.data[s + lo:s + hi] + return r / self.k + + +def _hv_block(self, a0, a1, b0, b1): + d = np.sqrt((self.x[a0:a1, None] - self.x[None, b0:b1]) ** 2 + (self.y[a0:a1, None] - self.y[None, b0:b1]) ** 2) + corr = _hv_corr(self, d) if self.img else None + if a0 == b0: + d[np.arange(a1 - a0), np.arange(a1 - a0)] = 1.0 + A = 1.0 / d + if corr is not None: + A += corr + s, e = self.indptr[a0], self.indptr[a1] + if e > s: + ix = self.indices[s:e] + rr = np.repeat(np.arange(a1 - a0), np.diff(self.indptr[a0:a1 + 1])) + m = (ix >= b0) & (ix < b1) + np.add.at(A, (rr[m], ix[m] - b0), self.data[s:e][m]) + return A / self.k + + +def _hv_aca(K, a0, a1, b0, b1, eps, max_rank): + m, n = a1 - a0, b1 - b0 + R = min(m, n, max_rank) + U, V = np.empty((m, R)), np.empty((n, R)) + used_r, used_c = np.zeros(m, bool), np.zeros(n, bool) + i, norm2, k = 0, 0.0, 0 + for _ in range(R): + r = K.row(a0 + i, b0, b1) + if k: + r -= V[:, :k] @ U[i, :k] + rm = np.where(used_c, 0.0, np.abs(r)) + j = int(np.argmax(rm)) + if rm[j] == 0.0: + break + v = r / r[j] + u = K.row(b0 + j, a0, a1) + if k: + u -= U[:, :k] @ V[j, :k] + used_r[i], used_c[j] = True, True + nu, nv = float(u @ u), float(v @ v) + norm2 += nu * nv + (2 * float((U[:, :k].T @ u) @ (V[:, :k].T @ v)) if k else 0.0) + U[:, k], V[:, k] = u, v + k += 1 + if nu * nv <= eps**2 * norm2: + break + um = np.where(used_r, 0.0, np.abs(u)) + i = int(np.argmax(um)) + if um[i] == 0.0: + break + else: + return None + return U[:, :k].copy(), V[:, :k].copy() + + +def _hv_mom_solve_fast(c, wh, o, n_metals, eps_r=11.45, dense_max=None): + """The frozen mom_solve_fast (vectorised kernel); a zero right-hand-side column raises at once (frozen: after maxit).""" + if len(c) > (P.DENSE_MAX if dense_max is None else dense_max) and not np.all(np.bincount(o, minlength=n_metals) > 0): + raise np.linalg.LinAlgError("H-matrix PCG: a metal without panels (zero right-hand side; frozen: NaN residual)") + return _ORIG["mom_solve_fast"](c, wh, o, n_metals, eps_r, dense_max) + + +# ------------------------------------------------------------------------------------------------ gpu (fastgpu.py) + + +class _Dev: + def __init__(self, t): + self.t = t + + +def _gpu_assemble(c, wh, diag, eps_r, near): + n = len(c) + if not STATE["gpu"] or n < CFG["gpu_min"]: + return _ORIG["assemble"](c, wh, diag, eps_r, near) + import torch + dev = CFG["device"] + k = 4 * np.pi * P.EPS0_FF_PER_UM * (eps_r + 1) / 2 + img = P._image_correction(np.zeros(1), eps_r) is not None + if img: + key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) + du, T = P._IMG_CACHE[key][:2] + T = torch.as_tensor(T, dtype=torch.float64, device=dev) + x = torch.as_tensor(c[:, 0], dtype=torch.float64, device=dev) + y = torch.as_tensor(c[:, 1], dtype=torch.float64, device=dev) + A = torch.empty((n, n), dtype=torch.float64, device=dev) + for r0 in range(0, n, CFG["rows"]): + r1 = min(r0 + CFG["rows"], n) + d = torch.sqrt((x[r0:r1, None] - x[None, :]) ** 2 + (y[r0:r1, None] - y[None, :]) ** 2) + if img: + u = d / du + j = torch.clamp(u.floor().long(), 0, len(T) - 2) + f = u - j + corr = T[j] + f * (T[j + 1] - T[j]) + d[torch.arange(r1 - r0, device=dev), torch.arange(r0, r1, device=dev)] = 1.0 + blk = 1.0 / d + if img: + blk += corr + A[r0:r1] = blk / k + ii, jj = P._near_pairs(c, wh.max(1)) + if len(ii): + v = 0.5 * (near(c[ii], c[jj], wh[jj]) + near(c[jj], c[ii], wh[ii])) / k + if img: + v = v + P._image_correction(np.sqrt(((c[ii] - c[jj]) ** 2).sum(1)), eps_r) / k + vi = torch.as_tensor(v, dtype=torch.float64, device=dev) + ti, tj = torch.as_tensor(ii, device=dev), torch.as_tensor(jj, device=dev) + A[ti, tj] = vi + A[tj, ti] = vi + dg = diag / k if not img else (diag + P._image_correction(np.zeros(1), eps_r)[0]) / k + A[torch.arange(n, device=dev), torch.arange(n, device=dev)] = torch.as_tensor(dg, dtype=torch.float64, device=dev) + return _Dev(A) + + +def _gpu_chol(A, B): + import torch + L, info = torch.linalg.cholesky_ex(A.t) + if int(info) > 0: + raise np.linalg.LinAlgError("not positive definite (device Cholesky)") + Bt = torch.as_tensor(np.ascontiguousarray(B), dtype=torch.float64, device=A.t.device) + X = torch.cholesky_solve(Bt, L).cpu().numpy() + A.t = None # the matrix is not used after a successful solve: release it and the allocator cache (shared GPU) + del L, Bt + torch.cuda.empty_cache() + return X + + +# ------------------------------------------------------------------------------------------------ mixed (fastmom.py) + + +def _mixed_chol(A, B): + from scipy.linalg.blas import dsymm + try: + cf = cho_factor(A.astype(np.float32, order="F"), lower=True, overwrite_a=True, check_finite=False) + except np.linalg.LinAlgError: + return _ORIG["chol_solve"](A, B) + B = np.asfortranarray(B, dtype=float) + X = cho_solve(cf, B.astype(np.float32), check_finite=False).astype(float) + bn = np.linalg.norm(B, axis=0) + for _ in range(CFG["refine_steps"]): + R = B - dsymm(1.0, A, X, side=0, lower=1) + if (np.linalg.norm(R, axis=0) <= CFG["refine_tol"] * bn).all(): + return X + X += cho_solve(cf, R.astype(np.float32), check_finite=False) + return _ORIG["chol_solve"](A, B) + + +def _chol_solve(A, B): + if isinstance(A, _Dev): + return _gpu_chol(A, B) + if "mixed" in STATE["components"]: + return _mixed_chol(A, B) + return _ORIG["chol_solve"](A, B) + + +def _sym_solve(A, B): + if not isinstance(A, _Dev): + return _ORIG["sym_solve"](A, B) + if A.t.shape[0] > FROZEN_DENSE_MAX: + return _gpu_chol(A, B) + try: + return _gpu_chol(A, B) + except np.linalg.LinAlgError: + from scipy.linalg import solve + return solve(A.t.cpu().numpy(), B, lower=True, assume_a="sym", overwrite_a=True, check_finite=False) + + +# ------------------------------------------------------------------------------------------------ ritz (certified) +# scripts/varritz/vr.py (templates, Ritz) and scripts/varritz/ritzprior.py (window / local loops, A5 dense dispatch). + + +def edge_geometry(metals, c, wh, o): + import shapely + n, M = len(c), len(metals) + d, a, g = np.zeros(n), np.zeros(n), np.zeros(n) + D = np.zeros((n, M)) + pts = shapely.points(c) + for k in range(M): + ix = np.nonzero(o == k)[0] + if not len(ix): + continue + bd = metals[k].boundary + shapely.prepare(bd) + ln = shapely.shortest_line(pts[ix], bd) + xy = shapely.get_coordinates(ln).reshape(-1, 2, 2) + v = xy[:, 0] - xy[:, 1] + dk = np.sqrt((v**2).sum(1)) + nv = np.where(dk[:, None] > 0, v / np.maximum(dk, 1e-300)[:, None], 0.7071) + d[ix], a[ix] = dk, np.abs(nv[:, 0]) * wh[ix, 0] + np.abs(nv[:, 1]) * wh[ix, 1] + others = shapely.union_all([metals[j] for j in range(M) if j != k]) + shapely.prepare(others) + g[ix] = shapely.distance(shapely.points(xy[:, 1]), others) + for j in range(M): + shapely.prepare(metals[j]) + D[:, j] = shapely.distance(pts, metals[j]) + return d, a, np.maximum(g, 1e-9), D + + +def templates(d, a, g): + lo, hi = np.maximum(d - a / 2, 0.0), d + a / 2 + w = np.maximum(hi - lo, 1e-12) + s = 2 * (np.sqrt(hi) - np.sqrt(lo)) / w + gg = 2 * (np.arcsinh(np.sqrt(hi / g)) - np.arcsinh(np.sqrt(lo / g))) / w + return {"u": np.ones_like(d), "s": s, "g": gg} + + +def _orth_blocks(V, o, M): + out = [] + for k in range(M): + ix = np.nonzero(o == k)[0] + cols = np.nonzero(np.abs(V[ix]).sum(0) > 0)[0] + if not len(cols): + continue + Vk = V[np.ix_(ix, cols)] + Vk = Vk / np.maximum(np.linalg.norm(Vk, axis=0), 1e-300) + U, s, _ = np.linalg.svd(Vk, full_matrices=False) + keep = s > 1e-10 * s[0] + W = np.zeros((len(o), int(keep.sum()))) + W[ix] = U[:, keep] + out.append(W) + return np.hstack(out) + + +def ritz(V, PV, B): + G = V.T @ PV + G = 0.5 * (G + G.T) + Fm = V.T @ B + try: + Y = cho_solve(cho_factor(G, lower=True), Fm) + except np.linalg.LinAlgError: + lam, U = eigh(G) + keep = lam > 1e-13 * lam.max() + Y = U[:, keep] @ ((U[:, keep].T @ Fm) / lam[keep, None]) + CV = Fm.T @ Y + return 0.5 * (CV + CV.T), Y, B - PV @ Y + + +def start_basis(metals, c, wh, o, kind, op, B): + M = len(metals) + if kind == "pcg": + Z = op.bj(B) + return Z / np.maximum(np.linalg.norm(Z, axis=0), 1e-300) + area = wh[:, 0] * wh[:, 1] + d, a, g, _ = edge_geometry(metals, c, wh, o) + T = templates(d, a, g) + return _orth_blocks(np.hstack([np.where((o == k)[:, None], (T[nm] * area)[:, None], 0.0) + for k in range(M) for nm in "usg"]), o, M) + + +def criterion(CV, est, floor=0.1): + e = np.sqrt(np.maximum(np.diag(est), 0.0)) + return float(np.max(np.outer(e, e) / np.maximum(np.abs(CV), floor))) + + +def ritz_solve(metals, c, wh, o, eps_r, cols): + tau, start, maxit = CFG["ritz_tau"], CFG["ritz_start"], CFG["ritz_maxit"] + t0 = time.perf_counter() + op = FastOp(c, wh, o, eps_r, len(metals)) + B = op.B + V = start_basis(metals, c, wh, o, start, op, B) + PV = op.matvec(V) + for m in range(maxit + 1): + CV, Y, R = ritz(V, PV, B) + est = R.T @ op.bj(R) + rel = criterion(CV, est) + if rel <= tau or m == maxit: + break + Z = op.bj(R) + Z /= np.maximum(np.linalg.norm(Z, axis=0), 1e-300) + V, PV = np.hstack([V, Z]), np.hstack([PV, op.matvec(Z)]) + info = dict(n=len(c), steps=m, converged=rel <= tau, est_rel=rel, est_diag=np.diag(est).tolist(), k=V.shape[1], + t=time.perf_counter() - t0) + return (V @ Y)[:, np.asarray(cols)], info + + +def _frozen_solve(c, wh, o, eps_r, cols, all_rhs, n_metals): + if len(c) <= P.DENSE_MAX: + A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) + Bm = (o[:, None] == cols[None, :]).astype(float) + return P._chol_solve(A, Bm) if all_rhs else F._sym_solve(A, Bm) + return P.mom_solve_fast(c, wh, o, n_metals, eps_r)[:, cols] + + +def _ritz_dense_n(): + return max(CFG["ritz_dense_n"], CFG["gpu_dense_max"] if STATE["gpu"] else 0) + + +def _solve_mesh(metals, c, wh, o, eps_r, cols, all_rhs, kind): + if len(c) <= _ritz_dense_n(): # A5 (and the GPU): exact solve, estimate 0 + Q = _frozen_solve(c, wh, o, eps_r, cols, all_rhs, len(metals)) + LOG.append(dict(kind=kind, ritz=None, exact=True, steps=0, n=len(c), est_rel=0.0, est_diag=[0.0] * len(metals))) + return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) + try: + Q, info = ritz_solve(metals, c, wh, o, eps_r, cols) + rec = dict(kind=kind, ritz=bool(info["converged"]), exact=False, **info) + if not info["converged"]: + raise np.linalg.LinAlgError("ritz not converged") + except np.linalg.LinAlgError: + LOG.append(dict(kind=kind, ritz=False, exact=True, fallback=True, steps=0, n=len(c), est_rel=0.0, est_diag=[0.0] * len(metals))) + Q = _frozen_solve(c, wh, o, eps_r, cols, all_rhs, len(metals)) + return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) + LOG.append(rec) + return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) + + +def _last_good(R, ok, skipped, metals, eps_r, cols, all_rhs): + if R is not None and (ok or not np.isnan(R).any()): + return R + for c, wh, o in reversed(skipped): + try: + Q = _frozen_solve(c, wh, o, eps_r, cols, all_rhs, len(metals)) + LOG.append(dict(kind="last_good", ritz=None, exact=True, steps=0, n=len(c), est_rel=0.0, est_diag=[0.0] * len(metals))) + return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) + except np.linalg.LinAlgError: + continue + raise np.linalg.LinAlgError("no successful solve in the refinement sequence") + + +def _final_unpanelled(metals, c, wh, o, eps_r, cols, all_rhs): + """Final majority mesh still missing a metal: the frozen solve (doomed above the frozen DENSE_MAX: it raises).""" + if len(c) > FROZEN_DENSE_MAX: + raise np.linalg.LinAlgError("final mesh misses a metal above DENSE_MAX (frozen: NaN PCG)") + Q = _frozen_solve(c, wh, o, eps_r, cols, all_rhs, len(metals)) + LOG.append(dict(kind="window", ritz=None, exact=True, steps=0, n=len(c), est_rel=0.0, est_diag=[0.0] * len(metals))) + return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) + + +def ritz_window_solve(metals, n_core, h, budget, eps_r, all_rhs, levels=()): + cols = np.arange(len(metals)) if all_rhs else np.arange(1, 1 + n_core) + t_mesh = t_sol = 0.0 + hh, cap, refined, majority = h, budget, 0, False + skipped, R = [], None + while True: + t = time.perf_counter() + if not refined: + c, wh, o, hh, n_raw = F._lite_mesh(metals, hh, cap, n_core, levels) + elif levels: + c, wh, o, hh, n_raw = F._graded_mesh(metals, n_core, hh, levels, majority) + else: + c, wh, o, hh, n_raw = P.mesh_flagship(metals, hh, cap, majority=majority) + t_mesh += time.perf_counter() - t + t = time.perf_counter() + full = bool(np.all(np.bincount(o, minlength=len(metals)) > 0)) + if not full and not majority: + skipped.append((c, wh, o)) + if refined < F.LITE_REFINE: + hh, cap, refined = hh / 2, np.inf, refined + 1 + else: + majority = True + continue + try: + if not full: + R = _final_unpanelled(metals, c, wh, o, eps_r, cols, all_rhs) + else: + R = _solve_mesh(metals, c, wh, o, eps_r, cols, all_rhs, "window") + off = np.ones(R.shape, bool) + off[np.arange(len(cols)), cols] = False + ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and (not all_rhs or np.all(R[off] < 0))) + except np.linalg.LinAlgError: + ok = False + t_sol += time.perf_counter() - t + if LOG: + LOG[-1].update(accepted=ok, refined=refined) + if ok or majority: + break + if refined < F.LITE_REFINE: + hh, cap, refined = hh / 2, np.inf, refined + 1 + else: + majority = True + R = _last_good(R, ok, skipped, metals, eps_r, cols, all_rhs) + return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, + "assemble_s": 0.0, "solve_s": t_sol} + + +def ritz_loc_solve(metals, H, h_floor, ppg, eps_r): + t_mesh = t_sol = 0.0 + cols = np.arange(len(metals)) + refined, majority = 0, False + skipped, R = [], None + while True: + t = time.perf_counter() + c, wh, o, n_raw = FL.mesh_local(metals, H, h_floor, ppg, majority) + t_mesh += time.perf_counter() - t + t = time.perf_counter() + full = bool(np.all(np.bincount(o, minlength=len(metals)) > 0)) + if not full and not majority: + skipped.append((c, wh, o)) + if refined < F.LITE_REFINE: + H, h_floor, refined = H / 2, h_floor / 2, refined + 1 + else: + majority = True + continue + try: + if not full: + R = _final_unpanelled(metals, c, wh, o, eps_r, cols, True) + else: + R = _solve_mesh(metals, c, wh, o, eps_r, cols, True, "local") + off = ~np.eye(len(metals), dtype=bool) + ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and np.all(R[off] < 0)) + except np.linalg.LinAlgError: + ok = False + t_sol += time.perf_counter() - t + if LOG: + LOG[-1].update(accepted=ok, refined=refined) + if ok or majority: + break + if refined < F.LITE_REFINE: + H, h_floor, refined = H / 2, h_floor / 2, refined + 1 + else: + majority = True + R = _last_good(R, ok, skipped, metals, eps_r, cols, True) + return R, {"H_um": H, "h_floor_um": h_floor, "h_min_um": float(wh.min()), "panels": len(c), "raw": n_raw, + "refined": refined, "majority": majority, "mesh_s": t_mesh, "solve_s": t_sol} + + +def _micro_mom_loc(G, conds, eps_r=11.45, ppg=3.0, *args, **kw): + """micro_mom_loc + a certificate (certified mode). Window records of forked workers come back through a file.""" + LOG.clear() + fd, path = tempfile.mkstemp(prefix="fp_cert_", suffix=".jsonl") + os.close(fd) + _CERT_FILE[0] = path + try: + out = _ORIG["micro_mom_loc"](G, conds, eps_r, ppg, *args, **kw) + with open(path) as f: + LOG.extend(json.loads(ln) for ln in f if ln.strip()) + finally: + _CERT_FILE[0] = None + os.unlink(path) + CERTS.append(_certificate(G, conds, out[0], list(LOG), ppg)) + return out + + +def _certificate(G, conds, C, recs, ppg): + """Calibrated estimate (c = RITZ_CAL) of the prior's solver error: max relative entry error (0.1 fF floor) over the + accepted solves; per-entry fF estimates c sqrt(e_i e_j) for a single-window single-frame layout (input order). + Self entries of Ritz solves are lower bounds of the exact ones.""" + acc = [r for r in recs if r.get("accepted", True) and "est_rel" in r] + cert = dict(ppg=ppg, n_solves=len(recs), n_ritz=sum(bool(r.get("ritz")) for r in recs), + n_exact=sum(bool(r.get("exact")) for r in recs), n_fallback=sum(bool(r.get("fallback")) for r in recs), + max_rel_est=RITZ_CAL * max((r["est_rel"] for r in acc), default=0.0), calibration=RITZ_CAL, + windows=[dict(window=r.get("window"), n=r["n"], ritz=bool(r.get("ritz")), max_rel_est=RITZ_CAL * r["est_rel"]) + for r in acc], entry_est_fF=None) + if len(acc) == 1 and len(conds) <= 8: + frames = F.canonical_frames(G, conds) + e = np.maximum(np.asarray(acc[0]["est_diag"], float), 0.0) + if len(frames) == 1 and len(e) == len(conds) + 1: + inv = np.r_[0, np.argsort(frames[0][2]) + 1] + ei = e[inv] + cert["entry_est_fF"] = (RITZ_CAL * np.sqrt(np.outer(ei, ei))).tolist() + return cert + + +def certificates(clear=True) -> list: + out = list(CERTS) + if clear: + CERTS.clear() + return out + + +# ------------------------------------------------------------------------------------------------ install + + +def _gpu_available() -> bool: + try: + import torch + return bool(torch.cuda.is_available()) + except Exception: # noqa: BLE001 + return False + + +def resolve(mode=None, components=None) -> tuple: + if components is not None: + bad = set(components) - set(COMPONENTS) + if bad: + raise ValueError(f"unknown components {sorted(bad)}; known {COMPONENTS}") + return tuple(c for c in COMPONENTS if c in components) + mode = mode or os.environ.get("TLSQ_PRIOR_MODE", "exact") + if mode not in ("exact", "exact_compiled", "certified", "frozen"): + raise ValueError(f"mode {mode!r}") + if mode == "frozen": + return () + comps = ["fv", "parallel", "hmat_vec"] + if _gpu_available(): + comps.append("gpu") + if MIXED_GATED: + comps.append("mixed") + if mode in ("exact_compiled", "certified"): + comps.append("compiled") + if mode == "certified": + comps.append("ritz") + return tuple(c for c in COMPONENTS if c in comps) + + +def install(mode=None, components=None, workers=None, cpus=None, target="auto", blas_threads="auto", value_patch=None, + warm=True, **cfg): + """Install the components (mode 'exact' / 'certified' / 'frozen', or an explicit component list) on the frozen + vendor modules. workers: window workers (default TLSQ_PRIOR_WORKERS, else CPUs); cpus: default detect_cpus(); + blas_threads='auto': this process's BLAS / numba / pool threads = CPUs (None leaves them alone).""" + uninstall() + bind(target) + CFG.update(cfg) + comps = resolve(mode, components) + STATE["mode"] = mode or ("explicit" if components is not None else os.environ.get("TLSQ_PRIOR_MODE", "exact")) + STATE["components"] = comps + STATE["cpus"] = int(cpus) if cpus else detect_cpus() + w = workers if workers is not None else os.environ.get("TLSQ_PRIOR_WORKERS") + # default (A5): serial windows with all threads; forked windows only for certified (measured faster there) + STATE["workers"] = max(1, int(w)) if w is not None else (STATE["cpus"] if "ritz" in comps else 1) + if "parallel" not in comps: + STATE["workers"] = 1 + if sys.platform == "darwin" and STATE["workers"] > 1: # Accelerate (BLAS) crashes in forked children: never fork on macOS + STATE["workers"] = 1 + STATE["parallel_off"] = "darwin: the vendor's window pool forks and Accelerate is not fork-safe" + STATE["gpu"] = "gpu" in comps + _ORIG.update(window_solve=F._window_solve, loc_solve=FL._solve, micro_mom=F.micro_mom, lite_job=F._lite_job, + micro_mom_loc=FL.micro_mom_loc, mom_solve_fast=P.mom_solve_fast, assemble=P._assemble, + chol_solve=P._chol_solve, sym_solve=F._sym_solve, dense_max=P.DENSE_MAX, num_threads=P.NUM_THREADS) + _ORIG["micro_mom_sig"] = inspect.signature(F.micro_mom) + if blas_threads == "auto": + _set_threads(STATE["cpus"]) + elif blas_threads: + _set_threads(int(blas_threads)) + if "fv" in comps: + F._window_solve = fv_window_solve + F.micro_mom = _micro_mom + F._lite_job = _lite_job + _PARENT[0] = os.getpid() + _CHILD[0] = False + if "hmat_vec" in comps: + _ORIG.update({"Kernel.__init__": P._Kernel.__init__, "Kernel.row": P._Kernel.row, "Kernel.block": P._Kernel.block, "aca": P._aca}) + P._Kernel.__init__, P._Kernel.row, P._Kernel.block, P._aca = _hv_kernel_init, _hv_row, _hv_block, _hv_aca + P.mom_solve_fast = _hv_mom_solve_fast + if "compiled" in comps: + P.mom_solve_fast = _mom_solve_fast + if warm: + warmup() + if "gpu" in comps: + P._assemble = _gpu_assemble + P.DENSE_MAX = CFG["gpu_dense_max"] + if "gpu" in comps or "mixed" in comps: + P._chol_solve = _chol_solve + F._sym_solve = _sym_solve + if "ritz" in comps: + F._window_solve = ritz_window_solve + FL._solve = ritz_loc_solve + FL.micro_mom_loc = _micro_mom_loc + if warm: + warmup() + if value_patch is not None: + _UNDO.append(value_patch(F, P, FL)) + STATE["value_patch"] = getattr(value_patch, "__name__", str(value_patch)) + return dict(STATE) + + +def uninstall() -> None: + for u in reversed(_UNDO): + if callable(u): + u() + _UNDO.clear() + if _ORIG: + F._window_solve, FL._solve, F.micro_mom, F._lite_job = (_ORIG["window_solve"], _ORIG["loc_solve"], _ORIG["micro_mom"], + _ORIG["lite_job"]) + FL.micro_mom_loc, P.mom_solve_fast, P._assemble = _ORIG["micro_mom_loc"], _ORIG["mom_solve_fast"], _ORIG["assemble"] + P._chol_solve, F._sym_solve, P.DENSE_MAX = _ORIG["chol_solve"], _ORIG["sym_solve"], _ORIG["dense_max"] + P.NUM_THREADS = _ORIG["num_threads"] + if "aca" in _ORIG: + P._Kernel.__init__, P._Kernel.row, P._Kernel.block, P._aca = (_ORIG["Kernel.__init__"], _ORIG["Kernel.row"], + _ORIG["Kernel.block"], _ORIG["aca"]) + _ORIG.clear() + for tp in _TP: + try: + tp.restore_original_limits() + except Exception: # noqa: BLE001 + pass + _TP.clear() + STATE.update(mode=None, components=(), workers=1, gpu=False, value_patch=None, parallel_off=None) + + +@contextlib.contextmanager +def installed(**kw): + install(**kw) + try: + yield dict(STATE) + finally: + uninstall() + + +def warmup() -> float: + """Compile / load the numba kernels (first call per process; cached on disk afterwards). Returns seconds.""" + t = time.perf_counter() + rng = np.random.default_rng(0) + c = rng.random((600, 2)) * 100 + H = HFar(c, leaf=64) + H(np.ones((600, 2))) + Y = np.empty((600, 1)) + _numba()["far"](c[:, 0].copy(), c[:, 1].copy(), np.ones((1, 600)), Y) + return time.perf_counter() - t + + +def status() -> dict: + return dict(STATE, cfg=dict(CFG), mixed_gated=MIXED_GATED, frozen_dense_max=FROZEN_DENSE_MAX) diff --git a/src/squadds/ml/capacitance/_core/flagship.py b/src/squadds/ml/capacitance/_core/flagship.py new file mode 100644 index 0000000000000000000000000000000000000000..a233966fd2d4be5e78a9586c1360691c93382f90 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/flagship.py @@ -0,0 +1,43 @@ +"""Flagship Space tiers (deploy/registry.yaml: flagship_hub, flagship_tiers; deploy/GNN_SPACE.md "Flagship Space"). + +The tiers run through the paper Space's code path (geomgnn.paper: scene -> embedding -> priors under the tier's prior stack, or the +learned prior surrogate -> networks), unchanged. `view(reg)` is the registry seen with paper_arms / paper_hub replaced by +flagship_tiers / flagship_hub, so every geomgnn.paper function serves the tiers as arms. +""" + +from __future__ import annotations + +import copy + +from . import paper as PA + + +def view(reg): + if reg.data.get("_flagship_view"): + return reg + v = copy.copy(reg) + v.data = dict(reg.data, paper_arms=reg.data["flagship_tiers"], paper_hub=reg.data["flagship_hub"], _flagship_view=True) + return v + + +def tiers(reg) -> dict: + return view(reg)["paper_arms"] + + +def served(reg) -> list[str]: + v = view(reg) + return [k for k in PA.live(v) if PA.available(k, v)] + + +def predict(prepared, tier, reg, **kw) -> dict: + """Full N x N Maxwell matrix (fF; ground row/column 0) of a prepared layout with a flagship tier (geomgnn.paper.predict).""" + v = view(reg) + res = PA.predict(prepared, tier, v, **kw) + t = v["paper_arms"][tier] + res.pop("paper", None) + res.update(tier=tier, tier_title=t["title"], reference=t.get("reference") or {}, own=t.get("own") or {}, b5=t.get("b5"), b5_physics=t.get("b5_physics")) + return res + + +def preload(reg, example=None) -> dict: + return PA.preload(view(reg), example=example) diff --git a/src/squadds/ml/capacitance/_core/infer.py b/src/squadds/ml/capacitance/_core/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..f919fdd148e0fdb832c4f0bbddc8ad86ebccbd67 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/infer.py @@ -0,0 +1,72 @@ +"""Label-free standalone prediction for geomfast checkpoints. +Only checkpoints, geometry, and optional priors are accepted; never Q3D labels. +""" +import os +os.environ.setdefault('PYTHONDONTWRITEBYTECODE','1') +import sys,importlib.util,time +from pathlib import Path +import numpy as np +import torch +W=Path(__file__).resolve().parent +from ..network import build_model +from ._tlsq.uge.scene import scene_from_gds,tlsq_namer +from ._tlsq.uge.graph import scene_graph +from ._tlsq.uge.blocks import edge_matrix +from ._tlsq.uge.proxies import CapacitanceMoM +from ._tlsq.uge import localtok as lt + +class Predictor: + def __init__(self,paths,threads=2): + torch.set_num_threads(threads);self.models=[];self.threads=threads + for path in paths: + c=torch.load(path,map_location='cpu',weights_only=False) + model=build_model(len(c['scales']['X']['median']),len(c['scales']['E']['median']),len(c['scales']['G']['median']),c['rounds']);model.load_state_dict(c['state']);model.eval();self.models.append((c,model)) + assert len({c['arm'] for c,m in self.models})==1 + self.arm=self.models[0][0]['arm'];self.direct=self.arm=='direct_gnn';self.fast=self.arm=='fast_gnn' + def from_features(self,row,priors=None): + n=len(row['names']);pairs=np.array([(i,j) for i in range(n) for j in range(i+1,n)]);i,j=pairs.T;assert len(row['edges'])==len(pairs),'complete graph required' + outputs=[] + for ck,model in self.models: + 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']) + 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] + E=edge_matrix(row['edges'],ek,n)[None];G=np.array([[row['global'][k] for k in gk]],np.float32) + kinds=E[0,:,ek.index('is_ground_pair')].astype(int) + if self.arm in ['pair_mlp','mesh','lofo_pair']:X=X[:,:,[nk.index('role_ground')]];G=np.zeros((1,1),np.float32) + if self.direct:base=np.array([[ck['direct_intercepts'][str(k)] for k in kinds]],np.float32) + else: + p0,p1=(.75,1.5) if self.fast else (1.5,3.) + lo=np.log(priors[p0][i,j]);hi=np.log(priors[p1][i,j]);assert np.isfinite(lo).all() and np.isfinite(hi).all() + base=(2*hi-lo)[None].astype(np.float32);E=np.concatenate([E,(hi-lo)[None,:,None].astype(np.float32)],-1) + for name,z in [('X',X),('E',E),('G',G)]: + scale=ck['scales'][name];med=np.array(scale['median']);iqr=np.array(scale['iqr']);z[:]=np.clip((np.where(np.isfinite(z),z,med)-med)/iqr,-10,10) + assert np.isfinite(z).all() + closure=ck['closure_intercepts'];bbase=np.array([[closure.get('1',closure.get('True')) if nm!='G' else closure.get('0',closure.get('False')) for nm in row['names']]],np.float32) + T=lambda a:torch.from_numpy(np.asarray(a));M=torch.ones((1,n),dtype=torch.bool);PM=torch.ones((1,len(pairs)),dtype=torch.bool) + with torch.inference_mode():C,_=model(T(X),T(E),T(G),M,PM,T(pairs),T(base),T(bbase),self.direct) + outputs.append(C[0].numpy()) + result=np.mean(outputs,axis=0);assert np.isfinite(result).all();return result + def from_gds(self,path,names=None,alpha=None,local_gap=None): + from ._tlsq.embed import proxy,fastprior + physics=self.models[0][0].get('schema',{}).get('physics',{}) + if alpha is None:alpha=physics.get('alpha') + if local_gap is None:local_gap=physics.get('prior_method')=='local_gap' + proxy.NUM_THREADS=self.threads;start=time.perf_counter() + if names is None:namer=tlsq_namer + else: + def namer(S,m): + sig=[n for n in names if n!='G'];assert len(S)==len(sig),'signal polygons vs supplied file-order names';return sig + sc=scene_from_gds(path,namer=namer);t1=time.perf_counter();row=lt.add_tokens(sc,scene_graph(sc));t2=time.perf_counter();priors={} + if not self.direct: + old=fastprior.ALPHA_GAP_SHARE + try: + if alpha is not None:fastprior.ALPHA_GAP_SHARE=alpha + for p in ([.75,1.5] if self.fast else [1.5,3.]): + if local_gap: + from ._tlsq.embed.fastprior_loc import micro_mom_loc + with proxy.substrate('slab_open',sc.stack['substrate_thickness_um']): + 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) + priors[p]=-mat + else:priors[p]=-CapacitanceMoM(max_cells=10**9,mesh='lite',cells_per_gap=p,substrate='slab_open').compute(sc,list(row['edges']))['matrix'] + finally:fastprior.ALPHA_GAP_SHARE=old + t3=time.perf_counter();C=self.from_features(row,priors);t4=time.perf_counter() + return dict(C=C,names=row['names'],timing=dict(scene=t1-start,geometry=t2-t1,prior=t3-t2,network_and_pack=t4-t3,total=t4-start)) diff --git a/src/squadds/ml/capacitance/_core/layout.py b/src/squadds/ml/capacitance/_core/layout.py new file mode 100644 index 0000000000000000000000000000000000000000..2ebd0a3c6e2a9b4d4a7469a4aa80d6f72ac55ac6 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/layout.py @@ -0,0 +1,514 @@ +"""GDS reading and layout preparation: layers -> ground net + conductor bodies (full ground by default; optional crop window).""" + +from __future__ import annotations + +import tempfile +from dataclasses import dataclass, field +from pathlib import Path + +import gdstk +import numpy as np +import shapely +from shapely.geometry import Polygon + +from ._tlsq.uge.scene import _valid + +GROUND = (1, 0) +CONDUCTOR = (1, 10) +N_VALIDATED_SIGNALS = 7 # largest conductor count (plus ground) seen in training and validation +N_MAX_SIGNALS = 30 # practical cap for the free Space (MoM cost); the networks themselves have no limit +AUTO_GAPS, AUTO_FRAC, AUTO_MIN_UM = 100.0, 0.5, 150.0 # margin="auto" (see deploy/LIMITS.md: crop study) # the networks are dense over at most 8 conductors including ground + +# Figure colours = the paper's (MetBrewer Archambault, Hokusai2, OKeeffe1; paper_v4/ml_paper_2026/figures/scripts/_style.py) +GROUND_COLOR = "#D9D9D9" +CONDUCTOR_COLORS = ("#AB3329", "#F9D14A", "#381A61", "#88A0DC", "#E78429", "#7C4B73", "#ED968C") +LIGHT_GOLD = "#F9D14A" # large conductors only: thin ones skip it +WINDOW_COLOR = "#381A61" +UNMODELLED_COLOR = "#6B200C" +INK = "#111827" + + +def conductor_colors(areas) -> list[str]: + """The paper's per-conductor cycle; a conductor smaller than the median area skips light gold.""" + med = float(np.median(areas)) if len(areas) else 0.0 + out, i = [], 0 + for a in areas: + if CONDUCTOR_COLORS[i % len(CONDUCTOR_COLORS)] == LIGHT_GOLD and a < med: + i += 1 + out.append(CONDUCTOR_COLORS[i % len(CONDUCTOR_COLORS)]) + i += 1 + return out + + +def _luminance(hex_color: str) -> float: + lin = [(c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4) for c in (int(hex_color[j:j + 2], 16) / 255 for j in (1, 3, 5))] + return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2] + + +def text_color(hex_color: str) -> str: + """White or ink, whichever has the higher WCAG contrast on the fill.""" + lum = _luminance(hex_color) + return "white" if 1.05 / (lum + 0.05) >= (lum + 0.05) / (_luminance(INK) + 0.05) else INK + + +class LayoutError(ValueError): + """The layout cannot be turned into a valid capacitance problem (message says why and what to change).""" + + +def _top_cell(lib, cell: str | None): + if cell is not None: + for c in lib.cells: + if c.name == cell: + return c + raise LayoutError(f"cell {cell!r} not in the file (cells: {[c.name for c in lib.cells][:20]})") + tops = lib.top_level() + if not tops: + raise LayoutError("the GDS file has no cells") + if len(tops) == 1: + return tops[0] + # several top cells: take the one with the most (flattened) polygons + return max(tops, key=lambda c: len(c.get_polygons())) + + +def read_polygons(path, cell: str | None = None) -> tuple[dict, float, str]: + """{(layer, datatype): [shapely Polygon in µm, ...]} in file order, with references and paths flattened.""" + try: + lib = gdstk.read_gds(str(path)) + except Exception as e: # noqa: BLE001 + raise LayoutError(f"not a readable GDS file: {e}") from e + top = _top_cell(lib, cell) + u = lib.unit / 1e-6 + # flat cells (the training files): direct polygons in file order, which fixes the conductor order of the paper; + # otherwise everything is flattened (references, repetitions, paths) + polys = list(top.polygons) if not (top.references or top.paths) else top.get_polygons(apply_repetitions=True, include_paths=True) + out: dict = {} + for p in polys: + if len(p.points) < 3: + continue + out.setdefault((p.layer, p.datatype), []).append(Polygon(p.points * u)) + return out, u, top.name + + +def load_gds(path, layer_map: dict | None = None, cell: str | None = None) -> list[dict]: + """Detected (layer, datatype) pairs with polygon count, area (µm²) and bounding box (µm), plus a suggested role + (ground / conductor / ground+conductor / ignore) from `layer_map` ({"ground": [(1, 0)], "conductor": [(1, 10)]} by default; + a single-layer file without them gets "ground+conductor").""" + layer_map = layer_map or {"ground": [GROUND], "conductor": [CONDUCTOR]} + lm = {tuple(k): role for role, ks in layer_map.items() for k in ks} + polys, _, top = read_polygons(path, cell) + if len(polys) == 1 and not set(lm) <= set(polys): + lm = {k: "ground+conductor" for k in polys} # one metal layer: ground detected among its pieces (prepare) + rows = [] + for (l, d), ps in sorted(polys.items()): + b = shapely.union_all(ps).bounds if ps else (np.nan,) * 4 + rows.append({"layer": l, "datatype": d, "n_polygons": len(ps), "area_um2": float(sum(p.area for p in ps)), + "bbox_um": tuple(float(x) for x in b), "role": lm.get((l, d), "ignore"), "cell": top}) + return rows + + +def _components(polys: list) -> list[list[int]]: + """Connected components (touching or overlapping polygons) as lists of polygon indices, ordered by first index.""" + n = len(polys) + parent = list(range(n)) + + def find(a): + while parent[a] != a: + parent[a] = parent[parent[a]] + a = parent[a] + return a + + if n > 1: + tree = shapely.STRtree(polys) + ii, jj = tree.query(polys, predicate="intersects") + for a, b in zip(ii, jj): + ra, rb = find(int(a)), find(int(b)) + if ra != rb: + parent[max(ra, rb)] = min(ra, rb) + groups: dict = {} + for i in range(n): + groups.setdefault(find(i), []).append(i) + return sorted(groups.values(), key=lambda g: g[0]) + + +def _core_bounds(G, bodies: list, warnings: list) -> tuple: + """Bounds of the conductors together with the etched pocket(s) that contain them, so that cropping never cuts into the + ground edge facing the conductors. Open regions (the etch reaches the outer boundary of the metal) and very large + pockets (e.g. a CPW gap running across the chip) fall back to the conductors' own bounds.""" + S = shapely.union_all(bodies) + sb = S.bounds + outer = shapely.box(*shapely.union_all([G, S]).bounds) + etched = outer.difference(G) + parts = [p for p in getattr(etched, "geoms", [etched]) if p.intersects(S)] + if not parts: + return sb + P = shapely.union_all(parts) + pb = P.bounds + ob = outer.bounds + open_ = any(abs(a - b) < 1e-6 for a, b in zip(pb, ob)) + big = (pb[2] - pb[0]) * (pb[3] - pb[1]) > 25 * max((sb[2] - sb[0]) * (sb[3] - sb[1]), 1e-9) + if open_ or big: + if big and not open_: + warnings.append("the etched region around the conductors is large (> 25x their bounding box); window built " + "around the conductors only: check the crop in the preview") + return sb + return (min(sb[0], pb[0]), min(sb[1], pb[1]), max(sb[2], pb[2]), max(sb[3], pb[3])) + + +RECT_FILL, AREA_RATIO_LOW = 0.95, 2.0 # ground detection: near-rectangular outline; top-2 piece areas within this ratio = low confidence + + +def _shell(g): + """The piece with its openings filled (outer boundary only).""" + return shapely.union_all([Polygon(p.exterior) for p in getattr(g, "geoms", [g]) if p.geom_type == "Polygon"]) + + +def detect_ground(geoms: list) -> tuple[list[int], str, str]: + """(ground piece indices, reason, confidence) for metal pieces that share one layer. Ground = the piece whose openings + contain every other piece; else the largest near-rectangular piece touching the layout bounding box; else the largest.""" + n = len(geoms) + areas = [float(g.area) for g in geoms] + shells = [_shell(g) for g in geoms] + enc = [i for i in range(n) if all(shells[i].contains(geoms[j]) for j in range(n) if j != i)] + if len(enc) == 1: + k, why = enc[0], "it encloses every other piece (they sit in its openings)" + else: + B = shapely.union_all(geoms).bounds + tol = 1e-6 * max(B[2] - B[0], B[3] - B[1]) + + def rect_edge(i): + with np.errstate(divide="ignore", invalid="ignore"): # GEOS warns on axis-aligned rectangles; the envelope is still right + fill = shells[i].area / max(shells[i].minimum_rotated_rectangle.area, 1e-30) + return fill >= RECT_FILL and any(abs(a - b) <= tol for a, b in zip(shells[i].bounds, B)) + + cand = [i for i in range(n) if rect_edge(i)] + if cand: + k = max(cand, key=lambda i: areas[i]) + why = "no piece encloses all the others; it is the largest near-rectangular piece on the layout boundary" + else: + k = max(range(n), key=lambda i: areas[i]) + why = "no piece encloses all the others and none is a near-rectangular piece on the layout boundary; it is the largest" + top = sorted(areas, reverse=True) + close = n > 1 and top[0] < AREA_RATIO_LOW * top[1] + conf = "high" if len(enc) == 1 and not close else "low" + if close: + why += f"; the two largest pieces are within {AREA_RATIO_LOW:g}x in area" + return [k], why, conf + + +@dataclass +class PreparedLayout: + ground: object # shapely geometry (µm), cropped + conductors: list # shapely geometries (µm), one per net, file order + names: list[str] + window: tuple | None # (x0, y0, x1, y1) µm, or None when not cropped + min_gap_um: float + source: str = "" + warnings: list[str] = field(default_factory=list) + extra_metal: dict = field(default_factory=dict) # label -> geometry of metal inside the window that is not modelled + info: dict = field(default_factory=dict) + pieces: list = field(default_factory=list) # metal pieces (shapely, µm) when ground and conductors share a layer; piece #k = pieces[k - 1] (conductor Ck) + + @property + def n_conductors(self) -> int: + return len(self.conductors) + + def extent_um(self) -> float: + """Lateral size L of the conductors: diagonal of their joint bounding box (µm).""" + x0, y0, x1, y1 = shapely.union_all(self.conductors).bounds + return float(np.hypot(x1 - x0, y1 - y0)) + + def to_gds(self, path=None) -> bytes: + """Simplified GDS in the training convention: ground on (1, 0), one or more polygons per conductor on (1, 10). + Returns the bytes (and writes them when `path` is given).""" + lib = gdstk.Library(unit=1e-6, precision=1e-9) + cell = lib.new_cell("PREPARED") + + def add(g, layer, dt): + for poly in getattr(g, "geoms", [g]): + if poly.is_empty: + continue + if len(poly.interiors) == 0: + cell.add(gdstk.Polygon(np.asarray(poly.exterior.coords)[:-1], layer=layer, datatype=dt)) + else: # polygons with holes: boolean in gdstk keeps them as keyhole polygons + outer = gdstk.Polygon(np.asarray(poly.exterior.coords)[:-1]) + holes = [gdstk.Polygon(np.asarray(r.coords)[:-1]) for r in poly.interiors] + for p in gdstk.boolean(outer, holes, "not", layer=layer, datatype=dt): + cell.add(p) + + add(self.ground, *GROUND) + for g in self.conductors: + add(g, *CONDUCTOR) + if path is None: + with tempfile.TemporaryDirectory() as d: + lib.write_gds(Path(d) / "prepared.gds") + return (Path(d) / "prepared.gds").read_bytes() + lib.write_gds(str(path)) + return Path(path).read_bytes() + + def plot(self, ax=None, **kwargs): + """Draw the layout: ground grey, conductors coloured and named as the predictions name them. ``prepare_layout(gds).plot()``; + keyword arguments as ``render`` (labels, show_window, title, figsize, compact). Returns the matplotlib Axes.""" + fig = self.render(ax=ax, **kwargs) + return ax if ax is not None else fig.axes[0] + + def render(self, ax=None, show_window: bool = True, title: str | None = None, figsize=(6.4, 6.4), compact: bool = False, + labels=None): + """Matplotlib figure: ground (grey), conductors (coloured, labelled), unmodelled metal (hatched), window. When ground and + conductors share a layer, conductor piece #k is labelled Ck and ground pieces "G #k" (the numbers ground_pieces takes); + compact = smaller labels; labels = {name: text} renames conductors on the figure (e.g. {"C1": "star"}), False hides them.""" + import matplotlib.pyplot as plt + from matplotlib.patches import PathPatch, Rectangle + from matplotlib.path import Path as MPath + + def patch(g, **kw): + for poly in getattr(g, "geoms", [g]): + if poly.is_empty or poly.geom_type != "Polygon": + continue + verts, codes = [], [] + for ring in [poly.exterior, *poly.interiors]: + xy = np.asarray(ring.coords) + verts += list(xy) + codes += [MPath.MOVETO] + [MPath.LINETO] * (len(xy) - 2) + [MPath.CLOSEPOLY] + ax.add_patch(PathPatch(MPath(verts, codes), **kw)) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + else: + fig = ax.figure + patch(self.ground, facecolor=GROUND_COLOR, edgecolor="#8c8c8c", lw=0.4) + gd = self.info.get("ground_detection") + fs = 8 if compact else 11 + for g, nm, col in zip(self.conductors, self.names, conductor_colors([g.area for g in self.conductors])): + patch(g, facecolor=col, edgecolor="black", lw=0.4) + p = g.representative_point() if g.area > 0 else g.centroid + if labels is not False: + ax.annotate((labels or {}).get(nm, nm), (p.x, p.y), ha="center", va="center", fontsize=fs, weight="bold", + color=text_color(col), bbox=dict(boxstyle="round,pad=0.2", fc=col, ec="black", lw=0.6)) + for r in (gd or {}).get("pieces", []): + if r["role"] != "conductor": + x, y = r["label_xy"] + ax.annotate(f"{'G' if r['role'] == 'ground' else 'not modelled'} #{r['id']}", (x, y), ha="center", va="center", + fontsize=fs, weight="bold", color=INK, bbox=dict(boxstyle="round,pad=0.2", fc="#e5e7eb", ec="#374151", lw=0.6)) + for lab, g in self.extra_metal.items(): + patch(g, facecolor="none", edgecolor=UNMODELLED_COLOR, hatch="///", lw=0.6) + if show_window and self.window is not None: + x0, y0, x1, y1 = self.window + ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, ls="--", ec=WINDOW_COLOR, lw=1.0)) + b = shapely.union_all([self.ground, *self.conductors]).bounds + pad = 0.03 * max(b[2] - b[0], b[3] - b[1]) + ax.set_xlim(b[0] - pad, b[2] + pad) + ax.set_ylim(b[1] - pad, b[3] + pad) + ax.set_aspect("equal") + ax.set_xlabel("x (µm)") + ax.set_ylabel("y (µm)") + if title is None and gd: + title = (f"ground = piece {', '.join(f'#{i}' for i in gd['ground_pieces'])} ({gd['method']}, confidence {gd['confidence']}); " + f"{len(self.conductors)} conductors") + ax.set_title(title or f"{len(self.conductors)} conductors + ground; min gap {self.min_gap_um:.2f} µm", fontsize=10) + return fig + + +def prepare(path, ground_layers=(GROUND,), conductor_layers=(CONDUCTOR,), margin_gaps: float | str | None = None, + margin_um: float | None = None, ignore_layers=(), cell: str | None = None, select=None, select_box=None, + max_conductors: int = N_MAX_SIGNALS, ground_pieces=None) -> PreparedLayout: + """Extract the capacitance problem from a GDS file. + + - conductors: connected bodies of the conductor-layer polygons (touching/overlapping polygons are one net), in file + order; bodies that touch the ground metal are shorted to it and merged into the ground net (warning). + - ground: union of the ground-layer polygons. Default (margin_gaps=None, margin_um=None): no crop, the training + geometry (tlsq.uge.scene.scene_from_gds; TRAINING_PLAN Addendum R5; default since 2026-10-14). Optional crop to the + window = bbox(conductors + the etched pocket that contains them) expanded by `margin_um` if given, else `margin_gaps` + x (smallest conductor-to-ground gap), or ("auto") by max(100 gaps, half the conductor extent, 150 µm) (deploy/LIMITS.md). + - select: optional list of conductor-body indices (0-based, file order), or select_box = (x0, y0, x1, y1) µm (bodies + fully inside); the other bodies are not modelled and are flagged as extra metal when they fall inside the window. + - metal on layers that are neither ground, conductor nor in `ignore_layers` is flagged when inside the window. + - ground and conductors on one layer (ground_layers == conductor_layers, or a file with a single metal layer while the default + layers 1/0 and 1/10 are not both present): the layer's metal is split into connected pieces and the ground is detected + (detect_ground; result and confidence in info["ground_detection"], plus a warning). Pieces are numbered with the + automatically detected ground last and the others in file order, and conductor piece #k is named Ck, so the automatic + split names its conductors as the two-layer file does and names stay put when roles change. ground_pieces = piece + numbers (as in render()) overrides the pick; several pieces make one ground net. + """ + gl = {tuple(x) for x in ground_layers} + cl = {tuple(x) for x in conductor_layers} + il = {tuple(x) for x in ignore_layers} + if gl & cl and gl != cl: + raise LayoutError(f"layers {sorted(gl & cl)} are assigned both ground and conductor (assign the same layers to both to detect " + "the ground automatically)") + polys, _, top = read_polygons(path, cell) + warnings: list[str] = [] + metal = [k for k in polys if k not in il] + shared = None + if gl == cl: + shared = gl + elif gl == {GROUND} and cl == {CONDUCTOR} and len(metal) == 1 and not (GROUND in polys and CONDUCTOR in polys): + shared = set(metal) + if shared is None and ground_pieces is not None: + raise LayoutError("ground_pieces applies only when ground and conductors share one layer (the same ground and conductor " + "layers, or a single-layer file)") + pieces, gdet = [], None + if shared is not None: + gl = cl = shared + allp = [p for k in polys if k in shared for p in polys[k]] + if not allp: + raise LayoutError(f"no polygons on {sorted(shared)}; detected layers: {sorted(polys)}") + val = [_valid(p) for p in allp] + ok = [i for i, g in enumerate(val) if not g.is_empty and g.area > 0] + comps = [[ok[j] for j in c] for c in _components([val[i] for i in ok])] + pieces = [val[c[0]] if len(c) == 1 else _valid(shapely.union_all([val[i] for i in c])) for c in comps] + if len(pieces) < 2: + raise LayoutError(f"the metal on {sorted(shared)} is one connected piece: no floating conductor to compute") + auto, why, conf = detect_ground(pieces) + order = [i for i in range(len(pieces)) if i not in auto] + auto + pieces, comps = [pieces[i] for i in order], [comps[i] for i in order] + if ground_pieces is None: + gids, method = list(range(len(pieces) - len(auto), len(pieces))), "automatic" + else: + try: + gp = [x for x in ground_pieces.split(",") if x.strip()] if isinstance(ground_pieces, str) else list(ground_pieces) + gids = sorted({int(i) - 1 for i in gp}) + except (TypeError, ValueError) as e: + raise LayoutError(f"ground_pieces must be piece numbers such as [1] or '1,4' (got {ground_pieces!r})") from e + bad = [i + 1 for i in gids if not 0 <= i < len(pieces)] + if bad or not gids: + raise LayoutError(f"ground_pieces {bad or list(ground_pieces)} not valid: this layout has pieces 1..{len(pieces)} " + "(numbers as in the labelled figure)") + if len(gids) == len(pieces): + raise LayoutError("ground_pieces lists every piece: at least one piece must be a conductor") + why, conf, method = f"set by ground_pieces={[i + 1 for i in gids]}", "user", "user" + gset = {i for g in gids for i in comps[g]} + gpolys = [allp[i] for i in sorted(gset)] + cpolys = [allp[i] for i in range(len(allp)) if i not in gset] + lay_s = ", ".join(f"{k[0]}/{k[1]}" for k in sorted(shared)) + ids = ", ".join(f"#{g + 1}" for g in gids) + if method == "automatic": + warnings.append(f"ground and conductors share layer {lay_s}: the ground was detected automatically as piece {ids} ({why}; " + f"confidence {conf}). Check the numbered figure of the pieces and, if it is wrong, resubmit with " + "ground_pieces=[piece numbers].") + else: + warnings.append(f"ground and conductors share layer {lay_s}: ground = piece {ids} (set by ground_pieces)") + gdet = {"layers": [list(k) for k in sorted(shared)], "method": method, "ground_pieces": [g + 1 for g in gids], "reason": why, + "confidence": conf, "n_pieces": len(pieces)} + else: + gpolys = [p for k in polys if k in gl for p in polys[k]] + cpolys = [p for k in polys if k in cl for p in polys[k]] + if not gpolys: + raise LayoutError(f"no ground polygons on {sorted(gl)}; detected layers: {sorted(polys)}") + if not cpolys: + raise LayoutError(f"no conductor polygons on {sorted(cl)}; detected layers: {sorted(polys)}") + cvalid = [_valid(p) for p in cpolys] + keep = [i for i, g in enumerate(cvalid) if not g.is_empty and g.area > 0] + if len(keep) < len(cvalid): + warnings.append(f"{len(cvalid) - len(keep)} degenerate conductor polygon(s) (zero area) dropped") + cvalid = [cvalid[i] for i in keep] + G = _valid(shapely.union_all([_valid(g) for g in gpolys])) + bodies = [] + for comp in _components(cvalid): + bodies.append(cvalid[comp[0]] if len(comp) == 1 else _valid(shapely.union_all([cvalid[i] for i in comp]))) + n_merged = len(cvalid) - len(bodies) + if n_merged: + warnings.append(f"{len(cvalid)} conductor polygons form {len(bodies)} connected bodies (touching polygons merged into one net)") + # bodies in contact with ground metal are at ground potential + shorted = [i for i, b in enumerate(bodies) if shapely.intersects(b, G)] + if shorted: + warnings.append(f"{len(shorted)} conductor body(ies) touch the ground metal and were merged into the ground net") + G = _valid(shapely.union_all([G] + [bodies[i] for i in shorted])) + bodies = [b for i, b in enumerate(bodies) if i not in set(shorted)] + if not bodies: + raise LayoutError("every conductor body touches the ground: nothing floating to compute") + all_bodies = bodies + others = [] + if select is not None or select_box is not None: + if select_box is not None: + box = shapely.box(*select_box) + idx = [i for i, b in enumerate(bodies) if box.contains(b)] + else: + idx = [int(i) for i in select] + bad = [i for i in idx if i < 0 or i >= len(bodies)] + if bad: + raise LayoutError(f"select indices {bad} out of range (0..{len(bodies) - 1})") + if not idx: + raise LayoutError("the selection matched no conductor body") + bodies = [all_bodies[i] for i in idx] + others = [all_bodies[i] for i in range(len(all_bodies)) if i not in set(idx)] + if len(bodies) > max_conductors: + raise LayoutError(f"{len(bodies)} conductors found; this server is configured for at most {max_conductors} signal conductors " + "plus ground (a cost cap of the demo, not a limit of the models: pass prepare(max_conductors=...) " + "locally). Use `select` (indices or a box) to pick the conductors of interest.") + if len(bodies) > N_VALIDATED_SIGNALS: + warnings.append(f"{len(bodies)} conductors: beyond the validated range ({N_VALIDATED_SIGNALS} conductors plus ground). " + "The model applies the same pair function to every pair, but accuracy at this size has not been verified.") + metals = [G] + bodies + gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) + if not np.isfinite(gap) or gap <= 0: + raise LayoutError("zero gap between two nets (overlapping metal on different nets)") + window = None + if margin_um is not None or margin_gaps is not None: + gap_cg = min(shapely.distance(G, b) for b in bodies) # conductor-to-ground gap sets the scale of the ground's field + x0, y0, x1, y1 = _core_bounds(G, bodies, warnings) + if margin_um is not None: + m = float(margin_um) + elif margin_gaps == "auto": + # a training-like neighbourhood: the training chips extend ~150-330 µm (30-170 gaps) beyond the conductors + m = max(AUTO_GAPS * gap_cg, AUTO_FRAC * max(x1 - x0, y1 - y0), AUTO_MIN_UM) + else: + m = float(margin_gaps) * gap_cg + window = (x0 - m, y0 - m, x1 + m, y1 + m) + box = shapely.box(*window) + Gc = _valid(shapely.intersection(G, box)) + if Gc.is_empty: + raise LayoutError("no ground metal inside the window; increase the margin") + G = Gc + metals = [G] + bodies + gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) + if G.geom_type == "MultiPolygon" and len(G.geoms) > 1: + warnings.append(f"cropped ground consists of {len(G.geoms)} separate pieces (all treated as one net)") + box = shapely.box(*window) if window is not None else shapely.box(*shapely.union_all(metals).bounds) + extra = {} + for k, ps in polys.items(): + if k in gl or k in cl or k in il: + continue + inside = [p for p in ps if shapely.intersects(p, box)] + if inside: + extra[f"layer {k[0]}/{k[1]}"] = shapely.union_all([_valid(p) for p in inside]) + for i, b in enumerate(others): + if shapely.intersects(b, box): + extra.setdefault("unselected conductors", []) + extra["unselected conductors"].append(b) + if "unselected conductors" in extra: + n_un = len(extra["unselected conductors"]) + extra["unselected conductors"] = shapely.union_all(extra["unselected conductors"]) + warnings.append(f"{n_un} unselected conductor body(ies) lie inside the window and are NOT modelled (they would screen the selected ones)") + for lab in extra: + if lab.startswith("layer"): + warnings.append(f"metal on {lab} inside the window is not assigned (ground / conductor) and is ignored") + holes = sum(len(p.interiors) for b in bodies for p in getattr(b, "geoms", [b])) + if holes: + warnings.append(f"conductors contain {holes} hole(s): supported, but outside the training families") + size = max(np.subtract(shapely.union_all(metals).bounds[2:], shapely.union_all(metals).bounds[:2])) + if gap < 3 * size / 4096: + warnings.append(f"smallest gap {gap:.3g} µm is below the MoM resolution floor for a {size:.0f} µm layout " + f"(~{3 * size / 4096:.3g} µm): crop tighter or expect larger errors") + names = [f"C{i + 1}" for i in range(len(bodies))] + if gdet is not None: + gset = set(gdet["ground_pieces"]) + cond = sorted((k for k in range(1, len(pieces) + 1) if k not in gset), key=lambda k: comps[k - 1][0]) # file order = body order + piece_of = dict(zip(map(id, all_bodies), cond)) if len(cond) == len(all_bodies) else {} + names = [f"C{piece_of[id(b)]}" if piece_of else nm for b, nm in zip(bodies, names)] + info = {"cell": top, "margin_um": m if window else None, "n_conductor_polygons": len(cvalid), "n_bodies_total": len(all_bodies), "layout_size_um": float(size), + "extent_um": float(np.hypot(*np.subtract(shapely.union_all(bodies).bounds[2:], shapely.union_all(bodies).bounds[:2])))} + if gdet is not None: + info["ground_detection"] = _detection_info(gdet, pieces, comps, {piece_of[id(b)]: nm for b, nm in zip(bodies, names)} if piece_of else {}) + return PreparedLayout(G, bodies, names, window, float(gap), str(path), warnings, extra, info, pieces) + + +def _detection_info(gdet: dict, pieces: list, comps: list, name_of: dict) -> dict: + """JSON-ready record of the pieces and their roles (name_of: piece number -> conductor name of the modelled conductors).""" + gset = set(gdet["ground_pieces"]) + rows = [] + for i, g in enumerate(pieces, 1): + p = g.representative_point() + role = "ground" if i in gset else "conductor" if i in name_of else "not modelled" + rows.append({"id": i, "role": role, "name": "G" if i in gset else name_of.get(i), "area_um2": round(float(g.area), 3), + "bbox_um": [round(float(x), 3) for x in g.bounds], "n_polygons": len(comps[i - 1]), "label_xy": [float(p.x), float(p.y)]}) + return {**gdet, "pieces": rows} diff --git a/src/squadds/ml/capacitance/_core/learned_prior.py b/src/squadds/ml/capacitance/_core/learned_prior.py new file mode 100644 index 0000000000000000000000000000000000000000..ce0c22d4a88c843113e8dcc419e1311493b046a0 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/learned_prior.py @@ -0,0 +1,49 @@ +"""Fast tier: the learned prior surrogate (agents/learnedprior, t100_norm) in place of the two field solves. + +priors(model, prep, row) = the statements of scripts/learnedprior/lp_bench.py `Learned.from_gds` between the features and the +network: pack the scene-graph row with the P2d schema (scripts/learnedprior/lp_label.py `pack`), predict log P at 1.5 and 3 +panels per gap with lp_surrogate.predict_bucket (one layout), and return the symmetric positive mutual matrices that +infer.Predictor.from_features reads. Self / closure terms are not inputs, so the diagonals stay zero. +""" + +from __future__ import annotations + +import numpy as np + +from . import lp_surrogate as S +from ._tlsq.uge.blocks import edge_matrix + +PPG = (1.5, 3.0) + + +def load(path): + """(model, prep, checkpoint) on CPU (lp_surrogate.load_model).""" + return S.load_model(str(path), "cpu") + + +def pack(row: dict) -> dict: + """lp_label.pack: X (n, nodekeys), E (P, edgekeys), G (globkeys); pairs i < j in scene order.""" + n = len(row["names"]) + pairs = [(i, j) for i in range(n) for j in range(i + 1, n)] + nk = S.SCHEMA["nodekeys"] + 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) + E = edge_matrix(row["edges"], S.SCHEMA["edgekeys"], n) + Gv = np.array([row["global"][k] for k in S.SCHEMA["globkeys"]], np.float32) + return dict(X=X, E=E, G=Gv, names=row["names"]) + + +def priors(model, prep, row: dict) -> dict: + z = pack(row) + n = len(z["names"]) + b = dict(n=n, X=z["X"][None], E=z["E"][None], G=z["G"][None]) + lp = S.predict_bucket(model, prep, b, "cpu")[0] + iu = np.triu_indices(n, 1) + out = {} + for k, p in enumerate(PPG): + M = np.zeros((n, n)) + v = np.exp(lp[:, k]) + fl = getattr(prep, "floor_ff", None) + M[iu] = v if fl is None else np.maximum(v, fl) # registry learned_prior.floor_ff: the training minimum (agents/embedspeed) + out[p] = M + M.T + return out diff --git a/src/squadds/ml/capacitance/_core/levelpar.py b/src/squadds/ml/capacitance/_core/levelpar.py new file mode 100644 index 0000000000000000000000000000000000000000..6f559a8b701e04acbb38898590a2fedbd3829a7d --- /dev/null +++ b/src/squadds/ml/capacitance/_core/levelpar.py @@ -0,0 +1,98 @@ +"""Mesh levels of the prior concurrently (agents/embedspeed). The two thin-film solves (e.g. 1.5 and 3 panels per gap) are +independent; on macOS each runs its windows serially and keeps only ~2-5 cores busy, so the extra levels run in spawned +worker processes that install the same prior stack (geomgnn.api.set_prior_stack with the recorded registry prior and +threads) and execute the same statements as the in-process loop; the caller solves the first level meanwhile. + +TLSQ_LEVEL_PROCS: auto (default: TLSQ_LEVEL_MIN_N <= N <= TLSQ_LEVEL_MAX_N, default 30 and 150, on macOS or with >= 8 threads), +1 (always), 0 (never). +""" +from __future__ import annotations + +import os +import sys +import time +from concurrent.futures import ProcessPoolExecutor +from multiprocessing import get_context + +_EX: dict = {} + + +def enabled(sc, levels, threads: int = 2) -> bool: + from . import api as A + v = os.environ.get("TLSQ_LEVEL_PROCS", "auto") + if v == "0" or len(levels) < 2 or not A._STATE.get("pr"): + return False + if v == "1": + return True + n = len(sc.conductors) # measured (Mac, 18 threads): a gain at N = 67 (18.1 -> 11.9 s with spawned windows), a loss from + # N = 277 on (69 -> 75 s; grid_full 194 -> 238 s) where the spawned windows already fill the cores + # 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 + mid = int(os.environ.get("TLSQ_LEVEL_MIN_N", "30")) <= n <= int(os.environ.get("TLSQ_LEVEL_MAX_N", "150")) + return mid and (sys.platform == "darwin" or int(threads) >= int(os.environ.get("TLSQ_LEVEL_MIN_THREADS", "8"))) + + +def _init(paths, impl, pr, threads): + for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS", "TLSQ_NUM_THREADS"): + os.environ[k] = str(threads) + for p in reversed(paths): + if p not in sys.path: + sys.path.insert(0, p) + import torch + torch.set_num_threads(threads) + from squadds.ml.capacitance._core import api as A + A.set_prior_impl(impl) + A.set_prior_stack(pr, threads) + A._thread_limits(threads) + + +def solve_one(sc, p, threads, alpha, stack=None): + """The statements of the prior loop (geomgnn.api.predict_scene / paper.solve_levels) for one level; stack = (eps_r, thickness_um) + the prior is solved at (default the scene's).""" + from squadds.ml.capacitance._core import api as A + from squadds.ml.capacitance._core._tlsq.embed import fastprior, proxy + from squadds.ml.capacitance._core._tlsq.embed.fastprior_loc import micro_mom_loc + proxy.NUM_THREADS = threads + if set(A.V2_KWARGS) & set(A._STATE["patches"]): + from squadds.ml.capacitance._core import priorv2 + priorv2.clear() + old = fastprior.ALPHA_GAP_SHARE + t = time.perf_counter() + try: + if alpha is not None: + fastprior.ALPHA_GAP_SHARE = alpha + eps_r, t_um = stack or (sc.stack["substrate_eps_r"], sc.stack["substrate_thickness_um"]) + with proxy.substrate("slab_open", t_um), A._quiet_mixed_cast(): + mat, _, _ = micro_mom_loc(sc.conductors[0].geom, [c.geom for c in sc.conductors[1:]], eps_r=eps_r, ppg=p) + finally: + fastprior.ALPHA_GAP_SHARE = old + return -mat, time.perf_counter() - t + + +def _executor(n, threads): + from . import api as A + key = (n, threads, A._STATE["prior_impl"], repr(A._STATE["pr"])) + if _EX.get("key") != key: + if _EX.get("ex") is not None: + _EX["ex"].shutdown(wait=False, cancel_futures=True) + here = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 4)) # the directory holding squadds + main = sys.modules["__main__"] + saved = main.__dict__.pop("__file__", None) # spawn would otherwise re-run the calling script in the worker + try: + from ._spawn import boot + ini, args = boot(_init, [here], A._STATE["prior_impl"], A._STATE["pr"], threads) + ex = ProcessPoolExecutor(n, mp_context=get_context("spawn"), initializer=ini, initargs=args) + list(ex.map(int, range(n))) + finally: + if saved is not None: + main.__file__ = saved + _EX.update(key=key, ex=ex) + return _EX["ex"] + + +def solve(sc, levels, threads, alpha, stack=None) -> tuple[dict, dict]: + """{ppg: P} and {ppg: seconds} with levels[1:] in the workers and levels[0] here.""" + ex = _executor(len(levels) - 1, threads) + futs = [ex.submit(solve_one, sc, p, threads, alpha, stack) for p in levels[1:]] + first = solve_one(sc, levels[0], threads, alpha, stack) + res = [first] + [f.result() for f in futs] + return {p: r[0] for p, r in zip(levels, res)}, {f"{p:g}": r[1] for p, r in zip(levels, res)} diff --git a/src/squadds/ml/capacitance/_core/lp_surrogate.py b/src/squadds/ml/capacitance/_core/lp_surrogate.py new file mode 100644 index 0000000000000000000000000000000000000000..94c1294f5ca74de155a3dbb65fbd6a1f7daa3f62 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/lp_surrogate.py @@ -0,0 +1,396 @@ +"""learnedprior surrogate (PROTOCOL.md section 3): tri-GNN on the P2d scene-graph features -> (base, delta) per pair. + + python lp_surrogate.py train --p2d DIR [--gen DIR] --out DIR [--steps N] [--raw] [--gen-frac F] [--seed S] + python lp_surrogate.py predict --ckpt FILE --data DIR --kind p2d|gen --out FILE.npz + +Data buckets are homogeneous in conductor count n (no padding). Pairs i < j in the stored order. +""" +from __future__ import annotations + +import os + +os.environ.setdefault("PYTHONDONTWRITEBYTECODE", "1") +import argparse +import glob +import hashlib +import json +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +HERE = Path(__file__).resolve().parent +SCHEMA = json.loads((HERE / "schema_p2d.json").read_text()) +NK, EK, GK = SCHEMA["nodekeys"], SCHEMA["edgekeys"], SCHEMA["globkeys"] +NODE_DIM = {"log_area": 2, "log_perimeter": 1, "log_min_halfwidth": 1, "log_width": 1} +EDGE_DIM = {"log_dmin": 1, "log_cps": 1, "mom_0.5": 0.5, "mom_1": 0.0, "mom_2": -1.0} +EDGE_DIM.update({f"lg_{k}": v for k, v in list(EDGE_DIM.items())}) +GLOB_DIM = {"log_chip_area": 2, "log_pocket_area": 2, "log_substrate_t": 1} +GROUPS = ("geomfast", "base", "large", "scaled", "near") +T_GROUP = {"t1_near": "near", "t2_large": "large", "t3_scaled": "scaled"} + + +# ----------------------------------------------------------------------------------------------------------- data +def load_p2d(root) -> list: + out = [] + for p in sorted(glob.glob(f"{root}/n*.npz")): + d = np.load(p, allow_pickle=False) + out.append(dict(n=d["X"].shape[1], X=d["X"], E=d["E"][:, :, :len(EK)], G=d["G"], pri=d["pri"].astype(np.float64), key=d["key"], + split=d["split"], family=d["family"], group=np.full(len(d["key"]), "geomfast"), scale=np.ones(len(d["key"])))) + return out + + +def load_gen(roots) -> list: + """roots: one packed dir or several separated by "+" (v1 corpus + targeted corpus; no commas: sbatch --export splits on them).""" + out = [] + for p in sorted(f for root in str(roots).replace(",", "+").split("+") for f in glob.glob(f"{root}/n*.npz")): + d = np.load(p, allow_pickle=False) + grp = np.array([T_GROUP.get(str(s), str(s)) for s in d["stratum"]]) + out.append(dict(n=d["X"].shape[1], X=d["X"], E=d["E"], G=d["G"], pri=d["pri"].astype(np.float64), key=d["key"], split=d["split"], + family=np.char.add("gen_", d["stratum"].astype(str)), group=grp, scale=d["scale"])) + return out + + +def merge_buckets(bs: list) -> list: + by = {} + for b in bs: + by.setdefault(b["n"], []).append(b) + return [{k: (v[0][k] if k == "n" else np.concatenate([x[k] for x in v])) for k in v[0]} for n, v in sorted(by.items())] + + +def subset(b: dict, m: np.ndarray) -> dict: + return {k: (v if k == "n" else v[m]) for k, v in b.items()} + + +def log_L(X: np.ndarray) -> np.ndarray: + """(B,) log characteristic length: mean over signal nodes of 0.5 log_area.""" + sig = X[:, :, NK.index("role_ground")] < 0.5 + la = X[:, :, NK.index("log_area")] + return 0.5 * (la * sig).sum(1) / sig.sum(1).clip(1) + + +class Prep: + """Scale shift (optional) + robust scaling; TRAIN statistics only.""" + + def __init__(self, raw: bool = False): + self.raw = raw + self.nshift = np.array([NODE_DIM.get(k, 0.0) for k in NK]) + self.eshift = np.array([EDGE_DIM.get(k, 0.0) for k in EK]) + self.gshift = np.array([GLOB_DIM.get(k, 0.0) for k in GK]) + + def features(self, b: dict): + X, E, G = b["X"].astype(np.float64), b["E"].astype(np.float64), b["G"].astype(np.float64) + lL = log_L(b["X"]) if not self.raw else np.zeros(len(X)) + if not self.raw: + X = X - self.nshift * lL[:, None, None] + E = E - self.eshift * lL[:, None, None] + G = G - self.gshift * lL[:, None] + G = np.concatenate([G, lL[:, None]], 1) + return X, E, G, lL + + def targets(self, b: dict, lL: np.ndarray): + y = np.log(b["pri"]) - lL[:, None, None] + return np.stack([2 * y[..., 1] - y[..., 0], y[..., 1] - y[..., 0]], -1) + + def fit(self, buckets: list): + acc = {k: [] for k in "XEGT"} + rng = np.random.default_rng(0) + for b in buckets: + tr = np.flatnonzero(b["split"] == "train") + if not len(tr): + continue + tr = rng.choice(tr, min(len(tr), 3000), replace=False) + X, E, G, lL = self.features(subset(b, np.isin(np.arange(len(b["key"])), tr))) + acc["X"].append(X.reshape(-1, X.shape[-1])) + acc["E"].append(E.reshape(-1, E.shape[-1])) + acc["G"].append(G) + acc["T"].append(self.targets(subset(b, np.isin(np.arange(len(b["key"])), tr)), lL).reshape(-1, 2)) + self.stats = {} + for k in "XEG": + v = np.concatenate(acc[k]) + med = np.nanmedian(v, 0) + iq = np.nanpercentile(v, 75, 0) - np.nanpercentile(v, 25, 0) + self.stats[k] = (med, np.where(iq > 1e-6, iq, 1.0)) + t = np.concatenate(acc["T"]) + self.stats["T"] = (t.mean(0), t.std(0)) + return self + + def apply(self, b: dict): + X, E, G, lL = self.features(b) + out = [] + for k, z in (("X", X), ("E", E), ("G", G)): + med, iq = self.stats[k] + out.append(np.clip((np.where(np.isfinite(z), z, med) - med) / iq, -10, 10).astype(np.float32)) + return (*out, lL) + + def state(self): + return dict(raw=self.raw, stats={k: [np.asarray(x).tolist() for x in v] for k, v in self.stats.items()}) + + @classmethod + def from_state(cls, s): + p = cls(s["raw"]) + p.stats = {k: tuple(np.array(x) for x in v) for k, v in s["stats"].items()} + return p + + +# ---------------------------------------------------------------------------------------------------------- model +def mlp(i, o, w): + return nn.Sequential(nn.Linear(i, w), nn.SiLU(), nn.Linear(w, o)) + + +class Round(nn.Module): + def __init__(self, w): + super().__init__() + self.me, self.mh = nn.Linear(w, w), nn.Linear(w, w) + self.node = mlp(3 * w, w, w) + self.edge = mlp(3 * w, w, w) + self.ln_t = nn.LayerNorm(w) + self.ta, self.tb, self.tg = nn.Linear(w, w), nn.Linear(w, w), nn.Linear(w, w) + self.tout = nn.Sequential(nn.LayerNorm(w), nn.Linear(w, w)) + self.ln_h, self.ln_e = nn.LayerNorm(w), nn.LayerNorm(w) + + def forward(self, h, e, off): + # h (B,N,w), e (B,N,N,w) symmetric, off (N,N,1) off-diagonal mask + N = h.shape[1] + m = self.me(e) * self.mh(h)[:, None, :, :] * off # message j -> i + mean = m.sum(2) / max(N - 1, 1) + mx = (m + (off - 1) * 1e4).amax(2) if N > 1 else torch.zeros_like(mean) + h = h + self.node(torch.cat([self.ln_h(h), mean, mx], -1)) + hs, hd = h[:, :, None] + h[:, None], (h[:, :, None] - h[:, None]).abs() + e = e + self.edge(torch.cat([self.ln_e(e), hs, hd], -1)) * off + z = self.ln_t(e) + a, b = self.ta(z) * off, self.tb(z) * off + t = torch.einsum("bikc,bjkc->bijc", a, b) / max(N - 2, 1) + t = 0.5 * (t + t.transpose(1, 2)) + e = e + torch.sigmoid(self.tg(z)) * self.tout(t) * off + return h, e + + +class TriGNN(nn.Module): + def __init__(self, dx, de, dg, w=128, rounds=4): + super().__init__() + self.node_in, self.edge_in = mlp(dx + dg, w, w), mlp(de, w, w) + self.rounds = nn.ModuleList([Round(w) for _ in range(rounds)]) + self.head = mlp(3 * w, 2, w) + + def forward(self, X, Eu, G, iu): + """X (B,N,dx), Eu (B,P,de) upper-triangle pairs iu=(i,j), G (B,dg) -> (B,P,2) standardised (b, d).""" + B, N, _ = X.shape + i, j = iu + h = self.node_in(torch.cat([X, G[:, None].expand(-1, N, -1)], -1)) + eu = self.edge_in(Eu) + e = torch.zeros(B, N, N, eu.shape[-1], device=X.device, dtype=eu.dtype) + e[:, i, j] = eu + e[:, j, i] = eu + off = (1 - torch.eye(N, device=X.device, dtype=eu.dtype))[:, :, None] + for r in self.rounds: + h, e = r(h, e, off) + return self.head(torch.cat([e[:, i, j], h[:, i] + h[:, j], (h[:, i] - h[:, j]).abs()], -1)) + + +def build(dx, de, dg, w=128, rounds=4): + return TriGNN(dx, de, dg, w, rounds) + + +# ------------------------------------------------------------------------------------------------------- training +def pairs_of(n): + return np.array([(i, j) for i in range(n) for j in range(i + 1, n)]).T.reshape(2, -1) + + +def predict_bucket(model, prep, b, device, max_pairs=2**17): + """(B,P,2) log P (ppg 1.5, 3) predicted for every layout of bucket b.""" + n = b["n"] + iu = torch.as_tensor(pairs_of(n), device=device) + X, E, G, lL = prep.apply(b) + mu, sd = prep.stats["T"] + bs = max(1, max_pairs // (n * n)) + out = [] + model.eval() + with torch.inference_mode(): + for s in range(0, len(X), bs): + T = lambda a: torch.as_tensor(a[s:s + bs], device=device) # noqa: E731 + z = model(T(X), T(E), T(G), iu).double().cpu().numpy() * sd + mu + out.append(z) + z = np.concatenate(out) + bb, dd = z[..., 0], z[..., 1] + y3, y1 = bb - dd, bb - 2 * dd + return np.stack([y1, y3], -1) + lL[:, None, None] + + +def fidelity(logp_hat, pri): + """Per-entry C0 errors (C0 = exp(2 log P3 - log P1.5)): |rel| with 0.1 fF floor, abs fF; |delta error|.""" + c0 = np.exp(2 * np.log(pri[..., 1]) - np.log(pri[..., 0])) + c0h = np.exp(2 * logp_hat[..., 1] - logp_hat[..., 0]) + d = np.log(pri[..., 1] / pri[..., 0]) + dh = logp_hat[..., 1] - logp_hat[..., 0] + err = np.abs(c0h - c0) + return err / np.maximum(c0, 0.1), err, np.abs(dh - d), c0 + + +def summarize(rel, err): + rel, err = np.ravel(rel), np.ravel(err) + return dict(entries=int(len(rel)), median_percent=float(np.median(rel) * 100), p95_percent=float(np.percentile(rel, 95) * 100), + mae_fF=float(err.mean()), rmse_fF=float(np.sqrt((err ** 2).mean()))) + + +def cmd_train(a): + torch.manual_seed(a.seed) + rng = np.random.default_rng(a.seed) + dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") + out = Path(a.out) + out.mkdir(parents=True, exist_ok=False) + buckets = load_p2d(a.p2d) + if a.p2d_holdout_fold is not None: # out-of-fold surrogate for geomfast TRAIN (PROTOCOL amendment 2026-10-17) + for b in buckets: + f = np.array([int(hashlib.sha256(str(k).encode()).hexdigest(), 16) % a.p2d_nfolds for k in b["key"]]) + b.update(subset(b, ~((b["split"] == "train") & (f == a.p2d_holdout_fold)))) + if a.gen: + g = load_gen(a.gen) + if a.gen_frac < 1: # nested subsets by parent index hash (learning curve) + for b in g: + parent = np.array(["/".join(k.split("/")[:2]) for k in b["key"]]) + u = np.array([int(hashlib.sha256(p.encode()).hexdigest(), 16) % 10**6 / 1e6 for p in parent]) + keep = (b["split"] != "train") | (u < a.gen_frac) + b.update(subset(b, keep)) + buckets += g + buckets = [b for b in merge_buckets(buckets) if b["n"] >= 2] + prep = Prep(a.raw).fit(buckets) + data = [] + for b in buckets: + X, E, G, lL = prep.apply(b) + Y = ((prep.targets(b, lL) - prep.stats["T"][0]) / prep.stats["T"][1]).astype(np.float32) + data.append(dict(n=b["n"], X=torch.as_tensor(X), E=torch.as_tensor(E), G=torch.as_tensor(G), Y=torch.as_tensor(Y), + split=b["split"], group=b["group"], iu=torch.as_tensor(pairs_of(b["n"]), device=dev))) + index = {g: [] for g in GROUPS} + for k, d in enumerate(data): + for g in GROUPS: + idx = np.flatnonzero((d["split"] == "train") & (d["group"] == g)) + if len(idx): + index[g].append((k, idx)) + groups = [g for g in GROUPS if index[g]] + counts = {g: int(sum(len(i) for _, i in index[g])) for g in groups} + val = [(k, np.flatnonzero(d["split"] == "val")) for k, d in enumerate(data)] + model = build(data[0]["X"].shape[-1], data[0]["E"].shape[-1], data[0]["G"].shape[-1], a.width, a.rounds).to(dev) + opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=1e-4) + sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=a.lr, total_steps=a.steps, pct_start=0.03, anneal_strategy="cos") + sd = torch.as_tensor(prep.stats["T"][1], device=dev, dtype=torch.float32) + meta = dict(args=vars(a), host=platform.node(), device=str(dev), gpu=torch.cuda.get_device_name(0) if dev.type == "cuda" else None, + train_counts=counts, val_layouts=int(sum(len(i) for _, i in val)), params=sum(p.numel() for p in model.parameters())) + (out / "run.json").write_text(json.dumps(meta, indent=1)) + print(json.dumps(meta), flush=True) + + def batch_loss(k, idx): + d = data[k] + T = lambda z: z[idx].to(dev, non_blocking=True) # noqa: E731 + z = model(T(d["X"]), T(d["E"]), T(d["G"]), d["iu"]) * sd + y = T(d["Y"]) * sd + return (F.huber_loss(z[..., 0], y[..., 0], delta=0.05, reduction="none") + F.huber_loss(z[..., 1], y[..., 1], delta=0.05, reduction="none")).mean(1) + + def evaluate(maxn=600): + model.eval() + res = {} + with torch.inference_mode(): + for k, idx in val: + if not len(idx): + continue + d = data[k] + bs = max(1, a.pair_budget // (d["n"] ** 2)) + for s in range(0, min(len(idx), maxn), bs): + l = batch_loss(k, torch.as_tensor(idx[s:s + bs])) + for gname in set(d["group"][idx[s:s + bs]]): + m = d["group"][idx[s:s + bs]] == gname + res.setdefault(gname, []).extend(l[torch.as_tensor(m, device=dev)].tolist()) + model.train() + return {g: float(np.mean(v)) for g, v in res.items()} + + hist, t0, skipped = [], time.perf_counter(), 0 + for step in range(a.steps): + g = groups[rng.integers(len(groups))] + w = np.array([len(i) for _, i in index[g]], float) + k, idx = index[g][rng.choice(len(w), p=w / w.sum())] + n = data[k]["n"] + bs = int(max(1, min(a.max_batch, a.pair_budget // (n * n)))) + b = torch.as_tensor(rng.choice(idx, bs)) + loss = batch_loss(k, b).mean() + if not torch.isfinite(loss): # skipped and counted (PROTOCOL amendment 2026-10-17); abort if frequent + skipped += 1 + print(json.dumps(dict(step=step, skipped_nonfinite=skipped, n=int(n), batch=bs)), flush=True) + if skipped > 100: + raise RuntimeError(f"non-finite loss at step {step} ({skipped} skipped)") + opt.zero_grad(set_to_none=True) + sched.step() + continue + opt.zero_grad(set_to_none=True) + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 5) + opt.step() + sched.step() + if step % a.eval_every == 0 or step == a.steps - 1: + ev = evaluate() + hist.append(dict(step=step, loss=float(loss), seconds=time.perf_counter() - t0, val=ev)) + print(json.dumps(hist[-1]), flush=True) + torch.save(dict(state=model.state_dict(), prep=prep.state(), width=a.width, rounds=a.rounds, dims=[data[0]["X"].shape[-1], + data[0]["E"].shape[-1], data[0]["G"].shape[-1]], step=step, history=hist), out / "model.pt") + meta.update(train_seconds=time.perf_counter() - t0, history=hist, skipped_nonfinite=skipped) + (out / "run.json").write_text(json.dumps(meta, indent=1)) + print("TRAIN_DONE", time.perf_counter() - t0, flush=True) + + +def load_model(path, device="cpu"): + c = torch.load(path, map_location=device, weights_only=False) + m = build(*c["dims"], c["width"], c["rounds"]).to(device) + m.load_state_dict(c["state"]) + m.eval() + return m, Prep.from_state(c["prep"]), c + + +def cmd_predict(a): + dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model, prep, _ = load_model(a.ckpt, dev) + buckets = load_p2d(a.data) if a.kind == "p2d" else load_gen(a.data) + keys, logp = [], {} + for b in merge_buckets(buckets): + if b["n"] < 2: + continue + sel = b["split"] == "val" if a.split == "val" else np.ones(len(b["key"]), bool) + b = subset(b, sel) + if not len(b["key"]): + continue + lp = predict_bucket(model, prep, b, dev) + for k, v in zip(b["key"], lp): + logp[str(k)] = v.astype(np.float64) + np.savez_compressed(a.out, keys=np.array(list(logp)), **{f"k{i}": v for i, v in enumerate(logp.values())}) + print("PREDICTED", len(logp)) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + sp = ap.add_subparsers(dest="cmd", required=True) + p = sp.add_parser("train") + p.add_argument("--p2d", required=True) + p.add_argument("--gen") + p.add_argument("--gen-frac", type=float, default=1.0) + p.add_argument("--out", required=True) + p.add_argument("--raw", action="store_true") + p.add_argument("--steps", type=int, default=20000) + p.add_argument("--lr", type=float, default=1e-3) + p.add_argument("--width", type=int, default=128) + p.add_argument("--rounds", type=int, default=4) + p.add_argument("--pair-budget", type=int, default=2**16) + p.add_argument("--max-batch", type=int, default=256) + p.add_argument("--eval-every", type=int, default=1000) + p.add_argument("--seed", type=int, default=0) + p.add_argument("--p2d-holdout-fold", type=int) + p.add_argument("--p2d-nfolds", type=int, default=2) + p = sp.add_parser("predict") + p.add_argument("--ckpt", required=True) + p.add_argument("--data", required=True) + p.add_argument("--kind", choices=["p2d", "gen"], default="p2d") + p.add_argument("--split", choices=["val", "all"], default="val") + p.add_argument("--out", required=True) + a = ap.parse_args() + {"train": cmd_train, "predict": cmd_predict}[a.cmd](a) diff --git a/src/squadds/ml/capacitance/_core/overlap.py b/src/squadds/ml/capacitance/_core/overlap.py new file mode 100644 index 0000000000000000000000000000000000000000..d66d2dad8eb862e4d36e2527824bcc8f737a032a --- /dev/null +++ b/src/squadds/ml/capacitance/_core/overlap.py @@ -0,0 +1,82 @@ +"""Embedding concurrently with the prior solves (agents/embedspeed). Both read only the geometry, so the embedding row +(scene_graph + localtok.add_tokens, the same functions) is computed in one spawned worker process while the caller runs the +prior solves, and joined before the network: bitwise the same row and priors as the sequential path. + +The worker is spawned (never forked: macOS Accelerate; the prior forks its own window workers on Linux) once per process +and reused. TLSQ_OVERLAP=0 turns it off; layouts with fewer than TLSQ_OVERLAP_MIN_N conductors (default 30), and machines with fewer than +TLSQ_OVERLAP_MIN_THREADS threads (default 4), stay sequential. +""" +from __future__ import annotations + +import os +import sys +from concurrent.futures import Future, ProcessPoolExecutor +from multiprocessing import get_context + +_EX: dict = {} + + +def enabled(sc, threads: int = 2) -> bool: + """On for >= TLSQ_OVERLAP_MIN_N conductors (default 30) and >= TLSQ_OVERLAP_MIN_THREADS threads (default 4): measured on 2 x86 + 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).""" + return (os.environ.get("TLSQ_OVERLAP", "1") != "0" and len(sc.conductors) >= int(os.environ.get("TLSQ_OVERLAP_MIN_N", "30")) + and int(threads) >= int(os.environ.get("TLSQ_OVERLAP_MIN_THREADS", "4"))) + + +def _settings() -> dict: + from squadds.ml.capacitance._core._tlsq.uge import blocks + + return {"EMBED_MODE": dict(blocks.EMBED_MODE), "EMBED_CACHE": dict(blocks.EMBED_CACHE), + "FAR_DECIMATION": dict(blocks.FAR_DECIMATION)} + + +def _apply(threads: int, st: dict): + from squadds.ml.capacitance._core._tlsq.embed import proxy + from squadds.ml.capacitance._core._tlsq.uge import blocks + + proxy.NUM_THREADS = threads + for k, v in st.items(): + getattr(blocks, k).update(v) + + +def _init(threads: int, paths: list): + for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS", "TLSQ_NUM_THREADS"): + os.environ[k] = str(threads) + for p in reversed(paths): + if p not in sys.path: + sys.path.insert(0, p) + + +def _embed(sc, threads: int, st: dict) -> tuple: + import time + + from squadds.ml.capacitance._core._tlsq.uge import localtok as lt + from squadds.ml.capacitance._core._tlsq.uge.graph import scene_graph + + _apply(threads, st) + t = time.perf_counter() + return lt.add_tokens(sc, scene_graph(sc)), time.perf_counter() - t + + +def _executor(threads: int) -> ProcessPoolExecutor: + if _EX.get("key") != threads: + if _EX.get("ex") is not None: + _EX["ex"].shutdown(wait=False, cancel_futures=True) + here = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 4)) # the directory holding squadds + main = sys.modules["__main__"] + saved = main.__dict__.pop("__file__", None) # spawn would otherwise re-run the calling script in the worker + try: + from ._spawn import boot + ini, args = boot(_init, threads, [here]) + ex = ProcessPoolExecutor(1, mp_context=get_context("spawn"), initializer=ini, initargs=args) + ex.submit(int, 0).result() # start the worker now, while __file__ is hidden + finally: + if saved is not None: + main.__file__ = saved + _EX.update(key=threads, ex=ex) + return _EX["ex"] + + +def start(sc, threads: int) -> Future: + """Future of (embedding row, worker seconds) of scene sc, computed in the worker process.""" + return _executor(threads).submit(_embed, sc, threads, _settings()) diff --git a/src/squadds/ml/capacitance/_core/paper.py b/src/squadds/ml/capacitance/_core/paper.py new file mode 100644 index 0000000000000000000000000000000000000000..fe5f7586dfc098e4fe484008c76247bec87b3eec --- /dev/null +++ b/src/squadds/ml/capacitance/_core/paper.py @@ -0,0 +1,369 @@ +"""Paper Space arms (deploy/registry.yaml: paper_hub, paper_arms; deploy/GNN_SPACE.md "Paper Space"). + +Every arm of the paper's ladder and routes tables that runs from a layout file on a CPU, through one code path: +scene (geomgnn.api.scene_from_prepared) -> geometric embedding -> priors at the arm's mesh levels under the arm's prior stack +-> the arm's combination. Kinds: + gnn geomfast networks (infer.Predictor): full_gnn / direct_gnn / full_mlp / pair_mlp checkpoints; the two levels are + fed as the networks' (1.5, 3) inputs (the coarser-pair arm reads R(0.75, 1.5) there, as it was trained); + learned_prior: the fast model's surrogate replaces the solves + multifid cheap-physics networks (x1_core.Multifid, scripts/multifid/train_mf.py); learned-exponent arms (curve) use the + train_mf.fit anchor (finest level) and curve=True + physics no learned parameter: one level (to_maxwell) or a Richardson pair (x1_core.c0) + final the prior-generation model and its fast mode (tlsq_infer.final, unchanged) +Prior stacks (paper_hub.prior_stacks) are process-wide (geomgnn.api.set_prior_stack); each request installs its arm's stack. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np + +from . import __version__ +from . import api as A +from . import infer as I +from . import x1_core as X +from ._tlsq.embed import fastprior, proxy +from ._tlsq.uge.graph import scene_graph + +lt = I.lt +ALPHA = 0.49685219816506904 # TRAIN-fitted gap share of every paper prior (P2d physics.alpha) +_CACHE: dict = {} + + +def arms(reg) -> dict: + return reg.data.get("paper_arms") or {} + + +def live(reg) -> list[str]: + return [k for k, v in arms(reg).items() if v.get("status", "available") == "available"] + + +def _sha(p) -> str: + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +def _model_dir(model_dir=None): + return os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir + + +def files(reg, name, key="checkpoints", model_dir=None) -> list[Path]: + """Bundle copies (//info.json) or the registry's source paths.""" + a = arms(reg)[name] + md = _model_dir(model_dir) + info = Path(md) / name / "info.json" if md else None + if info is not None and info.exists(): + return [Path(md) / name / f for f in json.loads(info.read_text()).get(key, [])] + src = a.get(key) or [] + if key == "surrogate": + src = [a["learned_prior"]["checkpoint"]] if a.get("learned_prior") else [] + return [reg.root / c["path"] for c in src] + + +def _hashes(a, key): + if key == "surrogate": + return [a["learned_prior"]["checkpoint"]["sha256"]] if a.get("learned_prior") else [] + return [c["sha256"] for c in a.get(key) or []] + + +def available(name, reg, model_dir=None) -> bool: + a = arms(reg)[name] + if a["kind"] == "final": + from tlsq_infer import final as F + return F.available(a["final_model"], reg) + return all(f.exists() for k in ("checkpoints", "surrogate") for f in files(reg, name, k, model_dir)) + + +def stack_of(reg, a) -> dict | None: + s = a.get("stack") + return None if s is None else reg["paper_hub"]["prior_stacks"][s] + + +def _check(reg, name, model_dir=None): + a = arms(reg)[name] + for key in ("checkpoints", "surrogate"): + fs, hs = files(reg, name, key, model_dir), _hashes(a, key) + assert len(fs) == len(hs), (name, key) + for f, h in zip(fs, hs): + if _sha(f) != h: + raise RuntimeError(f"{name}: {f.name} SHA256 differs from the registry ({h[:12]})") + return a + + +class _Curve: + """Learned-exponent cheap-physics arms (train_mf.fit with curve=True): anchor = log of the finest level, slope = finest - + next level, the head's exponent p sets m = anchor + slope / (2^p - 1); otherwise x1_core.Multifid.predict_arrays.""" + + def __init__(self, paths, threads=2): + import torch + + from .train_mf import build + torch.set_num_threads(threads) + self.models = [] + for p in paths: + c = torch.load(p, map_location="cpu", weights_only=False) + assert c["curve"] + m = build(len(c["scales"]["X"]["median"]), len(c["scales"]["E"]["median"]), len(c["scales"]["G"]["median"]), 2) + m.load_state_dict(c["state"]) + m.eval() + self.models.append((c, m)) + self.levels = self.models[0][0]["levels"] + assert all(c["levels"] == self.levels for c, _ in self.models) + + def predict(self, row, levels): + nk, ek, gk = X.schema_of(self.models[0][0]) + X0, E0, G0, pairs = X.raw_arrays(row, nk, ek, gk) + i, j = pairs.T + sig = np.array([nm != "G" for nm in row["names"]]) + lev = {p: np.asarray(levels[p], float)[i, j] for p in self.levels} + import torch + out = [] + for c, m in self.models: + L = [np.log(np.asarray(lev[p], float)) for p in self.levels] + assert all(np.isfinite(v).all() for v in L) + lf, lc = L[-1], L[-2] + anchor, slope = lf, lf - lc + E = np.concatenate([E0] + [(L[k + 1] - L[k])[:, None].astype(np.float32) for k in range(len(L) - 1)], -1) + Xn, En, Gn = X.norm(X0, c["scales"]["X"])[None], X.norm(E, c["scales"]["E"])[None], X.norm(G0[None], c["scales"]["G"]) + bbase = np.where(sig, c["closure"]["1"], c["closure"]["0"]).astype(np.float32)[None] + T = lambda a: torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32)) # noqa: E731 + n = len(sig) + with torch.inference_mode(): + C = m(T(Xn), T(En), T(Gn), torch.ones((1, n), dtype=torch.bool), torch.ones((1, len(pairs)), dtype=torch.bool), + torch.from_numpy(pairs), T(anchor[None].astype(np.float32)), T(slope[None].astype(np.float32)), T(bbase), True)[0] + out.append(C[0].numpy().astype(np.float64)) + r = np.mean(out, 0) + assert np.isfinite(r).all() + return r + + +def load(name, reg, model_dir=None, threads=2): + """The arm's network object (cached): infer.Predictor (gnn, with .surrogate), x1_core.Multifid / _Curve (multifid), None.""" + key = (str(reg.path), name, str(_model_dir(model_dir)), int(threads)) + if key in _CACHE: + return _CACHE[key] + a = _check(reg, name, model_dir) + obj = None + if a["kind"] == "gnn": + obj = I.Predictor(files(reg, name, "checkpoints", model_dir), threads=threads) + if obj.arm != a["arm"]: + raise RuntimeError(f"{name}: checkpoints are arm {obj.arm!r}, registry says {a['arm']!r}") + phys = obj.models[0][0].get("schema", {}).get("physics", {}) + if not obj.direct and float(phys.get("alpha")) != ALPHA: + raise RuntimeError(f"{name}: checkpoint alpha {phys.get('alpha')} != {ALPHA}") + obj.surrogate = None + if a.get("learned_prior"): + from . import learned_prior + model, prep, _ = learned_prior.load(files(reg, name, "surrogate", model_dir)[0]) + prep.floor_ff = a["learned_prior"].get("floor_ff") + obj.surrogate = (model, prep) + if obj.direct != (a.get("stack") is None and not a.get("learned_prior")): + raise RuntimeError(f"{name}: solver-free checkpoints iff no prior stack and no learned prior") + elif a["kind"] == "multifid": + paths = files(reg, name, "checkpoints", model_dir) + import torch + curve = torch.load(paths[0], map_location="cpu", weights_only=False)["curve"] + obj = _Curve(paths, threads) if curve else X.Multifid(paths, threads) + if [float(p) for p in obj.levels] != [float(p) for p in a["levels"]]: + raise RuntimeError(f"{name}: checkpoint levels {obj.levels} != registry {a['levels']}") + _CACHE[key] = obj + return obj + + +def levels_of(a) -> list[float]: + return [float(p) for p in (a.get("levels") or a.get("ppg") or [])] + + +def apply_stack(reg, a, threads=2): + st = stack_of(reg, a) + if st is not None: + A.set_prior_impl("frozen") + A.set_prior_stack(st, threads) + A._thread_limits(threads) + + +def solve_levels(sc, levels, threads=2, stack=None) -> tuple[dict, dict]: + """Positive-mutual prior matrices P = -C at each level under the installed stack (the statements of + geomgnn.api.predict_scene's prior loop, any level list); stack = (eps_r, thickness_um) of the substrate the prior is solved at + (default the scene's, i.e. the training stack).""" + from ._tlsq.embed.fastprior_loc import micro_mom_loc + from . import levelpar + eps_r, t_um = stack or (sc.stack["substrate_eps_r"], sc.stack["substrate_thickness_um"]) + if levelpar.enabled(sc, levels, threads): # the levels concurrently (spawned workers, same stack and statements) + return levelpar.solve(sc, list(levels), threads, ALPHA, (eps_r, t_um)) + proxy.NUM_THREADS = threads + if set(A.V2_KWARGS) & set(A._STATE["patches"]): + from . import priorv2 + priorv2.clear() + out, tm = {}, {} + old = fastprior.ALPHA_GAP_SHARE + try: + fastprior.ALPHA_GAP_SHARE = ALPHA + for p in levels: + t = time.perf_counter() + with proxy.substrate("slab_open", t_um), A._quiet_mixed_cast(): + mat, _, _ = micro_mom_loc(sc.conductors[0].geom, [c.geom for c in sc.conductors[1:]], eps_r=eps_r, ppg=p) + out[p] = -mat + tm[f"{p:g}"] = time.perf_counter() - t + finally: + fastprior.ALPHA_GAP_SHARE = old + return out, tm + + +def combine(a, obj, row, P) -> np.ndarray: + """The arm's Maxwell matrix from the embedding row and the priors P {ppg: -C} (scene order).""" + k = a["kind"] + if k == "physics": + lv = levels_of(a) + return X.to_maxwell(P[lv[0]]) if len(lv) == 1 else X.c0(P, lv[0], lv[1]) + if k == "multifid": + return obj.predict(row, P) + if obj.direct: + return obj.from_features(row) + if obj.surrogate is not None: + from . import learned_prior + return obj.from_features(row, learned_prior.priors(*obj.surrogate, row)) + lo, hi = levels_of(a) + return obj.from_features(row, {1.5: P[lo], 3.0: P[hi]}) + + +def predict_scene(reg, name, sc, threads=2, model_dir=None, stack=None) -> dict: + """The arm's prediction; an arm's `embedding: {far_k, d_far_um}` (flagship tiers only, agents/embedspeed Part A) selects the + far-sample decimation of the pair vectors for this call (the paper's arms always use the exact embedding).""" + from ._tlsq.uge import blocks as _B + emb = {} if os.environ.get("TLSQ_EMBEDDING_EXACT") == "1" else (arms(reg)[name].get("embedding") or {}) # tests of the exact recipe + old = dict(_B.FAR_DECIMATION) + _B.FAR_DECIMATION.update(k=int(emb.get("far_k", 0)), d_far=float(emb.get("d_far_um", 100.0))) + try: + return _predict_scene(reg, name, sc, threads, model_dir, stack) + finally: + _B.FAR_DECIMATION.clear() + _B.FAR_DECIMATION.update(old) + + +def _predict_scene(reg, name, sc, threads=2, model_dir=None, stack=None) -> dict: + a = arms(reg)[name] + obj = load(name, reg, model_dir, threads) + apply_stack(reg, a, threads) + t0 = time.perf_counter() + need = [] if (a["kind"] == "gnn" and (obj.direct or obj.surrogate is not None)) else levels_of(a) + from . import overlap as OV + fut = OV.start(sc, threads) if need and OV.enabled(sc, threads) else None # the embedding runs in the worker during the priors + row = None if fut else lt.add_tokens(sc, scene_graph(sc)) + t1 = time.perf_counter() + P, tl = solve_levels(sc, need, threads, stack) if need else ({}, {}) + t2 = time.perf_counter() + extra = {} + if fut is not None: + row, embed_s = fut.result() + extra = dict(overlap=True, geometry_worker=embed_s, geometry_wait_after_prior=time.perf_counter() - t2) + t2 = time.perf_counter() + C = np.asarray(combine(a, obj, row, P), float) + t3 = time.perf_counter() + return dict(C=C, names=row["names"], row=row, priors=P, + timing=dict(geometry=t1 - t0, prior=t2 - t1, prior_levels=tl, network=t3 - t2, total=t3 - t0, **extra)) + + +def route(a, eps, t_um) -> tuple[dict, list]: + """Substrate route of an arm (geomgnn.api.substrate_route): arms that solve a prior solve it at (eps, t_um); learned-prior arms (the + Fast tier) are eps-rescaled off the stack with a warning; the solver-free arm has neither and serves the training stack only.""" + if a["kind"] == "gnn" and a.get("stack") is None and not a.get("learned_prior"): + if not A.on_training_stack(eps, t_um): + raise ValueError(f"the solver-free model has no physics prior to solve at another stack: it is served for Si (eps_r " + f"{A.EPS_TRAIN:g}), {A.T_TRAIN_UM:g} um only (requested eps_r {eps:g}, {t_um:g} um)") + return A.substrate_route(eps, t_um, solves_prior=False) + sub, w = A.substrate_route(eps, t_um, solves_prior=not a.get("learned_prior")) + if a["kind"] == "physics" and sub.get("caveat"): + sub["caveat"] = "physics prior alone (no network), solved at your stack" + return sub, w + + +def predict(prepared, name, reg, substrate="Si (cryogenic, training)", thickness_um=350.0, model_dir=None, threads=None, + self_from_rows=True, trust_rule=None) -> dict: + """Full N x N Maxwell matrix (fF; ground row/column 0) of a prepared layout with a paper_arms entry.""" + a = arms(reg)[name] + threads = int(threads or os.environ.get("TLSQ_NUM_THREADS") or 2) + if a["kind"] == "final": + from tlsq_infer import final as F + tr = bool(reg["final_defaults"].get("trust_rule", True)) if trust_rule is None else bool(trust_rule) + res = F.predict_final(prepared, a["final_model"], substrate=substrate, thickness_um=thickness_um, self_from_rows=bool(self_from_rows), + trust_rule=tr if a.get("trust_rule_applies") else False) + res.update(arm=name, arm_title=a["title"], paper_name=a["paper_name"], route=a.get("route")) + return res + eps, t_um = reg.eps_of(substrate), float(thickness_um) + sub, sub_w = route(a, eps, t_um) + stack = None if A.on_training_stack(eps, t_um) else (eps, t_um) + t = time.perf_counter() + load(name, reg, model_dir, threads) + load_s = time.perf_counter() - t + sc = A.scene_from_prepared(prepared) + try: + r = predict_scene(reg, name, sc, threads, model_dir, stack) + except AssertionError as e: + raise ValueError(f"{name}: the prior or the features of this layout are not finite (no matrix returned): {e}") from e + C = r["C"] if stack is None or sub["eps_rescale_factor"] is None else r["C"] * sub["eps_rescale_factor"] + chk = A.physical_checks(C) + warnings = [w for w in prepared.warnings if "beyond the validated range" not in w] + if a.get("warning"): + warnings.insert(0, a["warning"]) + pw = A.physical_warning(chk, C) + if pw: + warnings.insert(0, pw) + warnings += sub_w + st = stack_of(reg, a) + tm = r["timing"] + return {"names": ["G"] + list(prepared.names), "matrix_fF": C.tolist(), "units": "fF", + "convention": "Maxwell matrix: diagonal = self, off-diagonal = -mutual; row/column 0 = ground", + "self_capacitance": a.get("self_note") or ("predicted by the network (learned positive row-sum closure). The ground self term " + "depends on the chip boundary: indicative only"), + "model": name, "arm": name, "arm_title": a["title"], "paper_name": a["paper_name"], "route": a.get("route"), "kind": a["kind"], + "network_arm": a.get("arm"), "levels_ppg": levels_of(a) if a["kind"] != "gnn" or not (a.get("learned_prior") or a.get("stack") is None) else [], + "weights_sha256": _hashes(a, "checkpoints"), "learned_prior_sha256": (_hashes(a, "surrogate") or [None])[0], + "prior_stack": (None if st is None else {"name": a["stack"], "patches": A._STATE.get("patches", []), "mode": A._STATE.get("mode") or "frozen", + "alpha": ALPHA, "method": "local_gap micro-MoM (slab)"}), + "package_version": f"geomgnn {__version__}", "registry_version": reg["version"], + "substrate": substrate if not isinstance(substrate, (int, float)) else f"custom eps={eps:g}", "eps_r": eps, "thickness_um": t_um, + "substrate_route": sub, "training_stack": {"eps_r": A.EPS_TRAIN, "thickness_um": A.T_TRAIN_UM}, + "timing_s": {"load_s": load_s, "geometry_s": tm["geometry"], "prior_s": tm["prior"], "prior_levels_s": tm["prior_levels"], + "network_s": tm["network"], "total_s": tm["total"], "threads": threads}, + "paper": a.get("paper") or {}, "checks": chk, "warnings": warnings, "stored": False} + + +STARTUP: dict = {} + + +def preload(reg, example=None, names=None) -> dict: + """Server start: load every live arm (SHA checks) and run the default arm on a small example (numba warmup of the compiled + solver included), so the first request does not pay the compile.""" + t0 = time.perf_counter() + for k in names or live(reg): + if arms(reg)[k]["kind"] != "final" and available(k, reg): + load(k, reg) + STARTUP["load_all_s"] = time.perf_counter() - t0 + d = reg["paper_hub"]["default_arm"] + if example is not None and Path(example).exists(): + from .layout import prepare + t = time.perf_counter() + predict(prepare(str(example)), d, reg) + STARTUP["example_s"] = time.perf_counter() - t + if os.environ.get("TLSQ_PRELOAD_ALL", "1") != "0": # every live arm once (each stack's compile, the surrogates) + t = time.perf_counter() + for k in names or live(reg): + if k != d and arms(reg)[k]["kind"] != "final" and available(k, reg): + predict(prepare(str(example)), k, reg) + STARTUP["example_all_arms_s"] = time.perf_counter() - t + t = time.perf_counter() + from ._tlsq.uge import nnk + STARTUP["nn_kernel"] = nnk.available() and nnk._STATE.get("arith") # probe + compile of the exact NN kernel + from . import overlap + th = int(os.environ.get("TLSQ_NUM_THREADS") or 2) + if th >= int(os.environ.get("TLSQ_OVERLAP_MIN_THREADS", "4")): + overlap._executor(th) # the embedding worker of large layouts, spawned now + STARTUP["kernel_and_worker_s"] = time.perf_counter() - t + STARTUP.update(default=d, numba_warmup_s=A._STATE.get("warmup_s"), total_s=time.perf_counter() - t0) + print("preload " + json.dumps({k: (round(v, 2) if isinstance(v, float) else v) for k, v in STARTUP.items()}), flush=True) + return dict(STARTUP) diff --git a/src/squadds/ml/capacitance/_core/priorv2.py b/src/squadds/ml/capacitance/_core/priorv2.py new file mode 100644 index 0000000000000000000000000000000000000000..e216c68d79ecf4709ea3e6c167bbf2000646ae7a --- /dev/null +++ b/src/squadds/ml/capacitance/_core/priorv2.py @@ -0,0 +1,215 @@ +"""Prior v2 = frozen geomfast prior + rejtail fix fc (rescue panels), as a monkeypatch of fastprior._window_solve. +Logic copied from scripts/rejtail/rt.py (policies 'exact' and 'fc' only; no wp dependency). Vendor files untouched. +Import after the geomfast vendor dir is on sys.path. Usage: + import priorv2; with priorv2.installed(): ... fastprior.micro_mom / micro_mom_loc ... +fc acts only on windowed solves (all_rhs False, N > 9) whose FIRST attempt leaves a metal without a panel; everything +else runs the frozen code path.""" +import time +import contextlib +import numpy as np +import shapely +from ._tlsq.embed import fastprior as F, proxy as P + +PRIOR_VERSION = 'v2_fc_dipfill' +TRACE = [] +POLICY = ['fc'] + + +def _solve(c, wh, o, metals, cols, eps_r, all_rhs): + if len(c) <= P.DENSE_MAX: + A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) + Bm = (o[:, None] == cols[None, :]).astype(float) + Q = P._chol_solve(A, Bm) if all_rhs else F._sym_solve(A, Bm) + else: + Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)[:, cols] + return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) + + +def _mesh(metals, n_core, hh, cap, refined, majority, levels): + if not refined: + return F._lite_mesh(metals, hh, cap, n_core, levels) + if levels: + return F._graded_mesh(metals, n_core, hh, levels, majority) + return P.mesh_flagship(metals, hh, cap, majority=majority) + + +def _rescue_panels(metals, miss, h): + """Each panel-less metal cut by a lattice of pitch min(h, sqrt(area) / 2) anchored at its bbox; one panel per piece, + centre = centroid (point on surface if outside), size = piece bbox (the frozen cut-piece form).""" + cs, whs, os_ = [], [], [] + for a in miss: + g = metals[a] + x0, y0, x1, y1 = g.bounds + p = min(h, np.sqrt(g.area) / 2) + nx, ny = max(1, int(np.ceil((x1 - x0) / p))), max(1, int(np.ceil((y1 - y0) / p))) + gx, gy = np.meshgrid(x0 + p * np.arange(nx), y0 + p * np.arange(ny)) + pcs = shapely.intersection(shapely.box(gx.ravel(), gy.ravel(), gx.ravel() + p, gy.ravel() + p), g) + pcs = pcs[shapely.area(pcs) > 1e-12] + bb = shapely.bounds(pcs) + cen = shapely.get_coordinates(shapely.centroid(pcs)) + inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1]) + if not inside.all(): + cen[~inside] = shapely.get_coordinates(shapely.point_on_surface(pcs[~inside])) + cs.append(cen) + whs.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6)) + os_.append(np.full(len(pcs), a)) + return np.concatenate(cs), np.concatenate(whs), np.concatenate(os_).astype(int) + + +def window_solve(metals, n_core, h, budget, eps_r, all_rhs, levels=()): + pol = POLICY[0] if not all_rhs else 'exact' + cols = np.arange(len(metals)) if all_rhs else np.arange(1, 1 + n_core) + t_mesh = t_sol = 0.0 + hh, cap, refined, majority = h, budget, 0, False + tr = dict(n_core=n_core, n_metals=len(metals), all_rhs=all_rhs, policy=pol, attempts=[]) + best, hist = None, [] + while True: + t = time.perf_counter() + c, wh, o, hh, n_raw = _mesh(metals, n_core, hh, cap, refined, majority, levels) + miss = np.nonzero(np.bincount(o, minlength=len(metals)) == 0)[0] + att = dict(refined=refined, majority=majority, panels=len(c), missing=miss.tolist()) + t_mesh += time.perf_counter() - t + tr['attempts'].append(att) + cs, whs, os_ = c, wh, o + if pol != 'exact' and len(miss): + empty = np.array([metals[a].is_empty for a in miss]) + if pol == 'fc' and not refined and (not empty.any() or len(c) <= P.DENSE_MAX): + t = time.perf_counter() + if not empty.all(): + r = _rescue_panels(metals, miss[~empty], hh) + cs, whs, os_ = np.concatenate([c, r[0]]), np.concatenate([wh, r[1]]), np.concatenate([o, r[2]]).astype(o.dtype) + att['rescued'] = int(len(r[0])) + if empty.any(): + att['accept'] = 'empty' + t_mesh += time.perf_counter() - t + else: + att['defer'] = True + if att.get('defer'): + doomed = len(c) > P.DENSE_MAX + hist.append(('doomed',) if doomed else ('mesh', c, wh, o)) + att['solve'] = 'doomed' if doomed else 'deferred' + ok = False + else: + t = time.perf_counter() + try: + R = _solve(cs, whs, os_, metals, cols, eps_r, all_rhs) + off = np.ones(R.shape, bool) + off[np.arange(len(cols)), cols] = False + ok = bool(np.all(np.bincount(os_, minlength=len(metals)) > 0) and (not all_rhs or np.all(R[off] < 0))) + if att.get('accept') == 'empty': + ok = True + att['solve'] = 'ok' + best = R + hist.append(('R', R)) + except np.linalg.LinAlgError as e: + ok = False + att['solve'], att['err'] = 'error', str(e)[:120] + hist.append(('err',)) + t_sol += time.perf_counter() - t + if ok or majority: + break + if refined < F.LITE_REFINE: + hh, cap, refined = hh / 2, np.inf, refined + 1 + else: + majority = True + if not ok: # frozen R binding: the latest attempt that solved (deferred dense attempts solved lazily, newest first) + R = None + t = time.perf_counter() + for e in reversed(hist): + if e[0] == 'R': + R = e[1] + break + if e[0] == 'mesh': + try: + R = _solve(e[1], e[2], e[3], metals, cols, eps_r, all_rhs) + break + except np.linalg.LinAlgError: + continue + t_sol += time.perf_counter() - t + assert R is not None, 'no attempt solved (the frozen code raises here too)' + else: + R = best + tr['fired'] = bool(pol == 'fc' and tr['attempts'][0]['missing']) + TRACE.append(tr) + return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, + "assemble_s": 0.0, "solve_s": t_sol} + + +FILL = [] # one entry per formula_prior call replaced by the dipole fill: number of pairs +MARGIN = [] # one entry per window whose margin was widened: (d, margin) +_FROZEN = dict(formula_prior=F.formula_prior, lite_window=F._lite_window, dipole_far=F.dipole_far) +K_TOL = 1e-4 + + +def slab_R(d, t_um=350.0, eps_r=11.45): + """src/tlsq/embed/fastprior_farv4.slab_R verbatim: R(d) = 1 + 2 sum_n (-K)^n (1 - 8 n^2 t^2/d^2)/(1 + 4 n^2 t^2/d^2)^(5/2).""" + d = np.asarray(d, float) + K = (eps_r - 1) / (eps_r + 1) + n_max = int(np.ceil(np.log(K_TOL) / np.log(K))) if K > 0 else 0 + n = np.arange(1, n_max + 1)[:, None] + u = (n * t_um / d[None]) ** 2 + return 1 + 2 * np.sum((-K) ** n * (1 - 8 * u) / (1 + 4 * u) ** 2.5, 0) + + +def dipole_far_slab(G, conds, pairs, eps_r=11.45, gap=None): + """src/tlsq/embed/fastprior_farv4.dipole_far_v4 verbatim: the frozen dipole_far with (1 + eps_r) -> 1 + eps_r R(d).""" + base = _FROZEN['dipole_far'](G, conds, pairs, eps_r, gap) + pairs = np.asarray(pairs, int).reshape(-1, 2) + cen = shapely.get_coordinates(shapely.centroid(np.array([G] + list(conds), dtype=object))) + d = np.hypot(*(cen[pairs[:, 0]] - cen[pairs[:, 1]]).T) + return base * (1 + eps_r * slab_R(d, float(P.SUBSTRATE["t_um"]), eps_r)) / (1 + eps_r) + + +def formula_as_dipole(G, conds, eps_r=11.45, step_um=None, R_gaps=None, pairs=None, gap=None, screen_um=None, workers=1, max_core=8): + """Replaces formula_prior inside micro_mom (its only caller there: same-pocket far pairs): the same pairs get + dipole_far(G, conds, pairs, eps_r, gap), the fill micro_mom uses for cross-pocket far pairs.""" + pairs = np.asarray(pairs, int).reshape(-1, 2) + N = len(conds) + 1 + C = np.zeros((N, N)) + v = F.dipole_far(G, conds, pairs, eps_r, gap) + C[pairs[:, 0], pairs[:, 1]] = v + C[pairs[:, 1], pairs[:, 0]] = v + FILL.append(len(pairs)) + return C, {"dipole_fill_pairs": len(pairs)} + + +def lite_window_margin(G, conds, core, R_g, margin, fill_um, tree, etched): + """Frozen _lite_window, except margin' = 2 d when d = max distance of a core conductor to the chip ground > margin.""" + d = max(shapely.distance(conds[i], G) for i in core) + if d > margin: + MARGIN.append((float(d), float(margin))) + margin = 2 * d + return _FROZEN['lite_window'](G, conds, core, R_g, margin, fill_um, tree, etched) + + +@contextlib.contextmanager +def installed(policy='fc', dip=True, margin=False, slab_alpha=None): + """Install prior v2 pieces: window solve policy 'fc' (or 'exact' = traced frozen copy, or None = vendor as is), the + dipole fill of same-pocket far pairs (dip), the window margin widening (margin) and, for arm v2-slab, the slab dipole + for every far pair with ALPHA_GAP_SHARE = slab_alpha. Always restored.""" + saved = (F._window_solve, F.formula_prior, F._lite_window, F.dipole_far, F.ALPHA_GAP_SHARE) + if policy is not None: + POLICY[0] = policy + F._window_solve = window_solve + if dip: + F.formula_prior = formula_as_dipole + if margin: + F._lite_window = lite_window_margin + if slab_alpha is not None: + F.dipole_far, F.ALPHA_GAP_SHARE = dipole_far_slab, float(slab_alpha) + try: + yield + finally: + F._window_solve, F.formula_prior, F._lite_window, F.dipole_far, F.ALPHA_GAP_SHARE = saved + POLICY[0] = 'fc' + + +def clear(): + TRACE.clear() + FILL.clear() + MARGIN.clear() + + +def fired(trace): + """True if fc changed the solve of any window of the traced call.""" + return any(t.get('fired') for t in trace) diff --git a/src/squadds/ml/capacitance/_core/rejtail_fv.py b/src/squadds/ml/capacitance/_core/rejtail_fv.py new file mode 100644 index 0000000000000000000000000000000000000000..e1f3e9a1c4d168780cd664c493e7e4c87cd11a75 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/rejtail_fv.py @@ -0,0 +1,115 @@ +"""rejtail fix fv (agents/rejtail/RESULTS.md, scripts/rejtail/rt.py; user approval 2026-10-17): value-preserving removal of +the rejection tail of the windowed micro-MoM prior (`fastprior._window_solve`, all_rhs=False, layouts with > 8 conductors). + +A window attempt whose mesh leaves a metal without a panel is always rejected, whatever its solve returns. The frozen code +still solves it, and above DENSE_MAX panels the H-matrix PCG cannot converge: the panel-less metal has a zero right-hand +side, so the residual is 0/0 = NaN, and it runs 1,000 iterations before raising. fv meshes such attempts but does not +solve them. If the loop ends without an accepted attempt, the result the unpatched code returns is rebuilt by solving +the deferred dense attempts lazily: + keep_last_solved=True (frozen geomfast stage): the latest attempt whose solve succeeded, newest first; + keep_last_solved=False (tlsq_infer vendor): the last attempt's own solve, else the same RuntimeError. +Every accepted solve is the same call on the same mesh, so the result is bit-identical (621 layouts in RESULTS.md; +deploy/tests/test_gnn_space.py re-checks it). all_rhs=True calls (single window, N <= 8) run the original function. +The same file is shipped as geomgnn/rejtail_fv.py and tlsq_infer/_vendor/rejtail_fv.py; only the import line differs. +""" +from __future__ import annotations + +import time + +import numpy as np + +from ._tlsq.embed import fastprior as F +from ._tlsq.embed import proxy as P + +KEEP_LAST_SOLVED = True +_ORIG = {} + + +def _solve(c, wh, o, metals, cols, eps_r): + """One attempt solved exactly as the original loop does (windowed: LDL^T dense, H-matrix PCG above DENSE_MAX). + Returns (R, assemble seconds).""" + t = time.perf_counter() + t_asm = 0.0 + if len(c) <= P.DENSE_MAX: + A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) + t_asm = time.perf_counter() - t + Bm = (o[:, None] == cols[None, :]).astype(float) + Q = F._sym_solve(A, Bm) + else: + Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)[:, cols] + return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1), t_asm + + +def window_solve(metals: list, n_core: int, h: float, budget: float, eps_r: float, all_rhs: bool, levels: tuple = ()) -> tuple: + if all_rhs: + return _ORIG["window_solve"](metals, n_core, h, budget, eps_r, all_rhs, levels) + cols = np.arange(1, 1 + n_core) + t_mesh = t_asm = t_sol = 0.0 + hh, cap, refined, majority = h, budget, 0, False + hist = [] # per attempt, oldest first: ("R", R) | ("err",) | ("mesh", c, wh, o) deferred dense | ("doomed",) deferred H-matrix + while True: + t = time.perf_counter() + if not refined: + c, wh, o, hh, n_raw = F._lite_mesh(metals, hh, cap, n_core, levels) + elif levels: + c, wh, o, hh, n_raw = F._graded_mesh(metals, n_core, hh, levels, majority) + else: + c, wh, o, hh, n_raw = P.mesh_flagship(metals, hh, cap, majority=majority) + t_mesh += time.perf_counter() - t + if not np.all(np.bincount(o, minlength=len(metals)) > 0): + hist.append(("doomed",) if len(c) > P.DENSE_MAX else ("mesh", c, wh, o)) + ok = False + else: + t = time.perf_counter() + try: + R, ta = _solve(c, wh, o, metals, cols, eps_r) + t_asm += ta + hist.append(("R", R)) + ok = True + except np.linalg.LinAlgError: + hist.append(("err",)) + ok = False + t_sol += time.perf_counter() - t + if ok or majority: + break + if refined < F.LITE_REFINE: + hh, cap, refined = hh / 2, np.inf, refined + 1 + else: + majority = True + if ok: + R = hist[-1][1] + else: + R = None + t = time.perf_counter() + for e in reversed(hist if KEEP_LAST_SOLVED else hist[-1:]): + if e[0] == "R": + R = e[1] + break + if e[0] == "mesh": + try: + R = _solve(e[1], e[2], e[3], metals, cols, eps_r)[0] + break + except np.linalg.LinAlgError: + continue + t_sol += time.perf_counter() - t + if R is None: + raise RuntimeError(f"window solve failed: no positive-definite system after {refined} refinements (h={hh:.4g} um); " + "the window has no valid solution at this mesh") + return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, + "assemble_s": t_asm, "solve_s": t_sol} + + +def install() -> None: + """Replace fastprior._window_solve (a module global, looked up at call time, also in the forked window workers).""" + if not _ORIG: + _ORIG["window_solve"] = F._window_solve + F._window_solve = window_solve + + +def uninstall() -> None: + if _ORIG: + F._window_solve = _ORIG.pop("window_solve") + + +def installed() -> bool: + return bool(_ORIG) diff --git a/src/squadds/ml/capacitance/_core/schema_p2d.json b/src/squadds/ml/capacitance/_core/schema_p2d.json new file mode 100644 index 0000000000000000000000000000000000000000..13943022ba85c7b66321f18b38e8bd08303d022c --- /dev/null +++ b/src/squadds/ml/capacitance/_core/schema_p2d.json @@ -0,0 +1,123 @@ +{ + "nodekeys": [ + "compactness", + "fourier_00", + "fourier_01", + "fourier_02", + "fourier_03", + "fourier_04", + "fourier_05", + "fourier_06", + "fourier_07", + "fourier_08", + "fourier_09", + "fourier_10", + "fourier_11", + "fourier_12", + "fourier_13", + "fourier_14", + "fourier_15", + "fourier_16", + "fourier_17", + "fourier_18", + "fourier_19", + "fourier_20", + "fourier_21", + "fourier_22", + "fourier_23", + "fourier_24", + "fourier_25", + "fourier_26", + "fourier_27", + "fourier_28", + "fourier_29", + "fourier_30", + "fourier_31", + "fourier_32", + "gran_00", + "gran_01", + "gran_02", + "gran_03", + "gran_04", + "gran_05", + "gran_06", + "gran_07", + "gran_08", + "gran_09", + "gran_10", + "gran_11", + "gran_12", + "gran_13", + "gran_14", + "gran_15", + "log_Imajor_over_A2", + "log_area", + "log_aspect", + "log_elongation", + "log_min_halfwidth", + "log_perimeter", + "log_width", + "n_holes", + "role_ground", + "solidity", + "missing_log_min_halfwidth" + ], + "edgekeys": [ + "is_ground_pair", + "lg_log_cps", + "lg_log_dmin", + "lg_mom_0.5", + "lg_mom_1", + "lg_mom_2", + "lg_sep_00", + "lg_sep_01", + "lg_sep_02", + "lg_sep_03", + "lg_sep_04", + "lg_sep_05", + "lg_sep_06", + "lg_sep_07", + "lg_sep_08", + "lg_sep_09", + "log_cps", + "log_dmin", + "lt_e150", + "lt_e400", + "lt_e50", + "lt_g150", + "lt_g400", + "lt_g50", + "lt_o150", + "lt_o400", + "lt_o50", + "mom_0.5", + "mom_1", + "mom_2", + "sep_00", + "sep_01", + "sep_02", + "sep_03", + "sep_04", + "sep_05", + "sep_06", + "sep_07", + "sep_08", + "sep_09", + "share_absdiff", + "share_mean" + ], + "globkeys": [ + "log_chip_area", + "log_pocket_area", + "log_substrate_t", + "eps_eff" + ], + "base_sha": "03edcbc72325f1522ad3998aff25b9b0ec86e0af4f479a872c76b144c45605bc", + "extra_sha": "b72762b01169a9e754265a7fc256c4f8a11930a235da340ebc948e04463007c1", + "physics": { + "prior_method": "local_gap", + "alpha": 0.49685219816506904, + "ensemble": "arithmetic mean of complete predicted Maxwell matrices", + "audit": "prior_audit.json" + } +} \ No newline at end of file diff --git a/src/squadds/ml/capacitance/_core/winpool.py b/src/squadds/ml/capacitance/_core/winpool.py new file mode 100644 index 0000000000000000000000000000000000000000..61cbed3138feda48e1a06ed3e970937de6c16cd0 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/winpool.py @@ -0,0 +1,138 @@ +"""Window solves of the prior on spawned workers (agents/embedspeed; macOS). The vendor's window pool forks, which macOS +cannot do with Accelerate, so on macOS fastprior_pkg runs the windows serially (a few cores busy). Here the vendor's own +micro_mom runs with `workers` > 1 and its ProcessPoolExecutor / get_context("fork") are swapped, for that call only, for a +spawn pool whose workers install the same prior stack (geomgnn.api.set_prior_stack with the recorded registry prior), copy the +running call's layout (fastprior._LITE, the k-d tree rebuilt) and the module settings, and run fastprior_pkg's window job. +Each window is the same statements; BLAS threads per window differ (one per worker), so the result is numerically exact, +not bitwise (gate: <= 1e-9 relative vs the serial windows). + +TLSQ_WINDOW_PROCS: auto (default: macOS, CPUs from TLSQ_NUM_THREADS / os.cpu_count()), (force n workers), 0 (off). +""" +from __future__ import annotations + +import os +import sys +from concurrent.futures import ProcessPoolExecutor +from multiprocessing import get_context + +_ON: dict = {"n": 0} + + +def workers() -> int: + v = os.environ.get("TLSQ_WINDOW_PROCS", "auto") + if v == "0": + return 0 + if v != "auto": + return int(v) + return (os.cpu_count() or 1) if sys.platform == "darwin" else 0 + + +def _init(paths, impl, pr, state): + os.environ["TLSQ_WINDOW_PROCS"] = "0" + os.environ.update({k: "1" for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS", + "TLSQ_NUM_THREADS", "VECLIB_MAXIMUM_THREADS")}) + for p in reversed(paths): + if p not in sys.path: + sys.path.insert(0, p) + import shapely + import torch + torch.set_num_threads(1) + from squadds.ml.capacitance._core import api as A + from squadds.ml.capacitance._core._tlsq.embed import fastprior as F + from squadds.ml.capacitance._core._tlsq.embed import proxy + A.set_prior_impl(impl) + A.set_prior_stack(pr, 1) + A._thread_limits(1) + proxy.NUM_THREADS = 1 + proxy.SUBSTRATE.clear() + proxy.SUBSTRATE.update(state["substrate"]) + for k in ("ALPHA_GAP_SHARE", "LITE_WINDOW_BUDGET", "LITE_REFINE", "LITE_GROWTH", "FORMULA_STEP_UM", "ROW_SUM_EPS"): + setattr(F, k, state["F"][k]) + F.LITE_WINDOW_PPG[:] = state["F"]["LITE_WINDOW_PPG"] + F.LITE_MAX_CORE[:] = state["F"]["LITE_MAX_CORE"] + lite = dict(state["lite"]) + lite["tree"] = shapely.STRtree(lite["conds"]) + F._LITE.clear() + F._LITE.update(lite) + + +class _SpawnPool(ProcessPoolExecutor): + def __init__(self, max_workers, mp_context=None): + from . import api as A + from ._tlsq.embed import fastprior as F + from ._tlsq.embed import proxy + here = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 4)) # the directory holding squadds + state = dict(substrate=dict(proxy.SUBSTRATE), lite={k: v for k, v in F._LITE.items() if k != "tree"}, + F={k: getattr(F, k) for k in ("ALPHA_GAP_SHARE", "LITE_WINDOW_BUDGET", "LITE_REFINE", "LITE_GROWTH", + "FORMULA_STEP_UM", "ROW_SUM_EPS")} + | {"LITE_WINDOW_PPG": list(F.LITE_WINDOW_PPG), "LITE_MAX_CORE": list(F.LITE_MAX_CORE)}) + main = sys.modules["__main__"] + self._saved = main.__dict__.pop("__file__", None) # spawn would otherwise re-run the calling script + from ._spawn import boot + ini, args = boot(_init, [here], A._STATE["prior_impl"], A._STATE["pr"], state) + super().__init__(max_workers, mp_context=get_context("spawn"), initializer=ini, initargs=args) + + def shutdown(self, *a, **k): + try: + super().shutdown(*a, **k) + finally: + if self._saved is not None: + sys.modules["__main__"].__file__ = self._saved + self._saved = None + + +class _Serial: + """In-process stand-in for the other pools of the call (formula_prior's rows): what macOS runs today.""" + + def __init__(self, *a, **k): + pass + + def __enter__(self): + return self + + def __exit__(self, *e): + return False + + def map(self, fn, *its, **k): + return map(fn, *its) + + +def _pool(max_workers, mp_context=None): + """Spawned workers for the windows of a call with >= TLSQ_WINDOW_MIN_CORES windows (default 5; measured on the Mac: the + 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.""" + from ._tlsq.embed import fastprior as F + big = len(F._LITE.get("cores", ())) >= int(os.environ.get("TLSQ_WINDOW_MIN_CORES", "5")) + return _SpawnPool(max_workers) if F._LITE and big else _Serial() + + +def install() -> bool: + """Wrap the installed stack's micro_mom so that its windows run on spawned workers (idempotent; macOS by default).""" + from . import api as A + from . import fastprior_pkg as fp + from ._tlsq.embed import fastprior as F + n = workers() + if n < 2 or not A._STATE.get("pr") or not A._STATE.get("mode") or "micro_mom" not in fp._ORIG: + return False + if getattr(F.micro_mom, "_winpool", False): + _ON["n"] = n + return True + vendor = fp._ORIG["micro_mom"] + sig = fp._ORIG["micro_mom_sig"] + + def micro_mom(*args, **kw): + ba = sig.bind(*args, **kw) + if _ON["n"] < 2: + return fp._micro_mom(*args, **kw) + ba.arguments["workers"] = _ON["n"] + fp._PARENT[0] = os.getpid() + old = F.ProcessPoolExecutor, F.get_context + F.ProcessPoolExecutor, F.get_context = _pool, (lambda method=None: None) + try: + return vendor(*ba.args, **ba.kwargs) + finally: + F.ProcessPoolExecutor, F.get_context = old + + micro_mom._winpool = True + F.micro_mom = micro_mom + _ON["n"] = n + return True diff --git a/src/squadds/ml/capacitance/_core/x1_core.py b/src/squadds/ml/capacitance/_core/x1_core.py new file mode 100644 index 0000000000000000000000000000000000000000..812f6c236d28772038835056f0773ec4d236c2b6 --- /dev/null +++ b/src/squadds/ml/capacitance/_core/x1_core.py @@ -0,0 +1,116 @@ +"""X1 shared model code (agents/v4test/PROTOCOL.md): row -> arrays, multifid forward, surrogate priors. No solver, no labels.""" +import numpy as np + +from ._tlsq.uge.blocks import edge_matrix + +PPG = (0.375, 0.75, 1.5, 3.0) + + +def schema_of(ck): + s = ck.get('schema', ck) + return s['nodekeys'], s['edgekeys'], s.get('globkeys', ['log_chip_area', 'log_pocket_area', 'log_substrate_t', 'eps_eff']) + + +def raw_arrays(row, nk, ek, gk): + """Unnormalised X (n, nk), E (P, ek), G (gk) exactly as geomfast infer.Predictor.from_features builds them.""" + n = len(row['names']) + pairs = np.array([(i, j) for i in range(n) for j in range(i + 1, n)]) + 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) + E = edge_matrix(row['edges'], ek, n) + G = np.array([row['global'][k] for k in gk], np.float32) + return X, E, G, pairs + + +def norm(z, scale): + med, iqr = np.array(scale['median']), np.array(scale['iqr']) + return np.clip((np.where(np.isfinite(z), z, med) - med) / iqr, -10, 10).astype(np.float32) + + +class Multifid: + """multifid residual arm (scripts/multifid/train_mf.py Net), seeds averaged as full matrices (analyze.py).""" + + def __init__(self, paths, threads=2): + import torch + from .train_mf import build + torch.set_num_threads(threads) + self.models = [] + for p in paths: + c = torch.load(p, map_location='cpu', weights_only=False) + assert not c['curve'] + m = build(len(c['scales']['X']['median']), len(c['scales']['E']['median']), len(c['scales']['G']['median']), 2) + m.load_state_dict(c['state']) + m.eval() + self.models.append((c, m)) + self.levels = self.models[0][0]['levels'] + assert all(c['levels'] == self.levels for c, _ in self.models) + + def predict(self, row, levels): + """levels: {ppg: positive mutual matrix (n, n)} in row order.""" + nk, ek, gk = schema_of(self.models[0][0]) + X, E, G, pairs = raw_arrays(row, nk, ek, gk) + i, j = pairs.T + sig = np.array([nm != 'G' for nm in row['names']]) + return self.predict_arrays(X, E, G, pairs, sig, {p: np.asarray(levels[p], float)[i, j] for p in self.levels}) + + def predict_arrays(self, X0, E0, G0, pairs, sig, lev): + """raw (unnormalised) X (n, f), E (P, f), G (g), pairs (P, 2), sig (n,), lev {ppg: positive mutual (P,)}.""" + import torch + out = [] + for c, m in self.models: + assert schema_of(c) == schema_of(self.models[0][0]) + L = [np.log(np.asarray(lev[p], float)) for p in self.levels] + assert all(np.isfinite(v).all() for v in L) + X, E, G = X0, E0, G0 + lf, lc = L[-1], L[-2] + anchor, slope = 2 * lf - lc, lf - lc + E = np.concatenate([E] + [(L[k + 1] - L[k])[:, None].astype(np.float32) for k in range(len(L) - 1)], -1) + X, E, G = norm(X, c['scales']['X'])[None], norm(E, c['scales']['E'])[None], norm(G[None], c['scales']['G']) + bbase = np.where(sig, c['closure']['1'], c['closure']['0']).astype(np.float32)[None] + T = lambda a: torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32)) # noqa: E731 + n = len(sig) + with torch.inference_mode(): + C = m(T(X), T(E), T(G), torch.ones((1, n), dtype=torch.bool), torch.ones((1, len(pairs)), dtype=torch.bool), + torch.from_numpy(pairs), T(anchor[None]), T(slope[None]), T(bbase), False)[0] + out.append(C[0].numpy().astype(np.float64)) + r = np.mean(out, 0) + assert np.isfinite(r).all() + return r + + +class Surrogate: + """learnedprior surrogate (lp_surrogate.predict_bucket on lp_label.pack(row)) -> priors at ppg 1.5, 3.""" + + def __init__(self, path): + from . import lp_surrogate as S + self.S = S + self.model, self.prep, _ = S.load_model(path, 'cpu') + sch = S.SCHEMA + self.nk, self.ek, self.gk = sch['nodekeys'], sch['edgekeys'], sch['globkeys'] + + def priors(self, row): + X, E, G, pairs = raw_arrays(row, self.nk, self.ek, self.gk) + n = len(row['names']) + lp = self.S.predict_bucket(self.model, self.prep, dict(n=n, X=X[None], E=E[None], G=G[None]), 'cpu')[0] + iu = np.triu_indices(n, 1) + pri = {} + for k, p in enumerate((1.5, 3.0)): + M = np.zeros((n, n)) + M[iu] = np.exp(lp[:, k]) + pri[p] = M + M.T + return pri + + +def c0(levels, lo=1.5, hi=3.0): + """Richardson extrapolation in log of positive mutual / self matrices: exp(2 log c(hi) - log c(lo)); Maxwell form.""" + a, b = np.abs(np.asarray(levels[lo], float)), np.abs(np.asarray(levels[hi], float)) + m = np.exp(2 * np.log(np.maximum(b, 1e-300)) - np.log(np.maximum(a, 1e-300))) + n = len(m) + off = ~np.eye(n, dtype=bool) + C = np.where(off, -m, m) + return C + + +def to_maxwell(P): + """stored prior P = -C (positive mutuals) -> Maxwell C.""" + return -np.asarray(P, float) diff --git a/src/squadds/ml/capacitance/_runtime.py b/src/squadds/ml/capacitance/_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab59786d3cc170f164a2e8fdd9e6525a9c7d49d --- /dev/null +++ b/src/squadds/ml/capacitance/_runtime.py @@ -0,0 +1,144 @@ +"""Layout preparation, layout hashing and the process-wide thread settings shared by the predictor and the priors.""" + +from __future__ import annotations + +import functools +import hashlib +import os +import platform +import subprocess +import tempfile +import threading +from pathlib import Path + +TRAIN_EPS_R, TRAIN_THICKNESS_UM = 11.45, 350.0 +GROUND_LAYER, CONDUCTOR_LAYER = (1, 0), (1, 10) +LOCK = threading.RLock() # the prior stack and thread pools of the frozen stage are process-wide +_USER_ENV = {k: os.environ.get(k) for k in ("TLSQ_WINDOW_PROCS", "TLSQ_LEVEL_PROCS")} +_TP: list = [] + + +def prepare_layout( + layout, ground_layers=(GROUND_LAYER,), conductor_layers=(CONDUCTOR_LAYER,), max_conductors: int = 1000, **kwargs +): + """A ``PreparedLayout`` (ground net + conductor bodies, names C1..Cn in file order) from a GDS path, a gdstk Library or + Cell, or a ``PreparedLayout`` (returned unchanged). Extra keyword arguments go to ``_core.layout.prepare`` (crop margins, + selections, ignored layers, cell, ``ground_pieces``). + + Ground and conductors on one layer (the same ``ground_layers`` and ``conductor_layers``, or a single-layer file): the metal + is split into connected pieces and the ground is detected automatically, with a warning; check the numbered figure + (``inspect_layout``) and, if it is wrong, pass ``ground_pieces=[piece numbers]``.""" + from ._core.layout import PreparedLayout, prepare + + if isinstance(layout, PreparedLayout): + return layout + if isinstance(layout, (str, os.PathLike)): + return prepare( + str(layout), + ground_layers=ground_layers, + conductor_layers=conductor_layers, + max_conductors=max_conductors, + **kwargs, + ) + import gdstk + + if isinstance(layout, gdstk.Cell): + lib = gdstk.Library(unit=1e-6, precision=1e-9) + lib.add(layout, *layout.dependencies(True)) + layout = lib + if isinstance(layout, gdstk.Library): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "layout.gds" + layout.write_gds(str(p)) + lay = prepare( + str(p), + ground_layers=ground_layers, + conductor_layers=conductor_layers, + max_conductors=max_conductors, + **kwargs, + ) + lay.source = "" + return lay + raise TypeError( + f"cannot read a layout from {type(layout).__name__}: pass a GDS path, a gdstk Library / Cell or a PreparedLayout" + ) + + +def inspect_layout( + layout, + ground_layers=(GROUND_LAYER,), + conductor_layers=(CONDUCTOR_LAYER,), + ground_pieces=None, + figsize=(6.4, 6.4), + **kwargs, +) -> dict: + """The roles a prediction would use, before predicting: ``pieces`` (id, role, name, area, bounding box; empty when ground + and conductors are on separate layers), ``ground_pieces``, ``reason``, ``confidence`` ("high" / "low" / "user"), + ``warnings``, the ``PreparedLayout`` and a labelled matplotlib ``figure`` (ground grey, conductors coloured, every piece + numbered). If the ground is wrong, predict with ``ground_pieces=[...]`` using the numbers of the figure.""" + lay = prepare_layout(layout, ground_layers, conductor_layers, ground_pieces=ground_pieces, **kwargs) + gd = lay.info.get("ground_detection") or {} + return { + "detected": bool(gd), + "pieces": gd.get("pieces", []), + "ground_pieces": gd.get("ground_pieces"), + "reason": gd.get("reason"), + "confidence": gd.get("confidence"), + "names": lay.names, + "warnings": list(lay.warnings), + "prepared": lay, + "figure": lay.render(figsize=figsize), + } + + +def layout_hash(lay) -> str: + """sha256 of the prepared geometry (WKB of ground and conductors) and the conductor names.""" + import shapely + + h = hashlib.sha256(repr(list(lay.names)).encode()) + for g in [lay.ground, *lay.conductors]: + h.update(shapely.to_wkb(g)) + return h.hexdigest() + + +def configure(threads: int) -> int: + """One knob for every pool of the pipeline: torch, BLAS (threadpoolctl), and on macOS the spawned window workers of the + prior (TLSQ_WINDOW_PROCS = threads) and the level workers (TLSQ_LEVEL_PROCS: only from 4 threads). Explicit environment + settings of the user win.""" + import torch + + threads = max(1, int(threads)) + torch.set_num_threads(threads) + try: + from threadpoolctl import threadpool_limits + + _TP[:] = [threadpool_limits(threads)] + except Exception: # noqa: BLE001 (Accelerate ignores it) + pass + os.environ["TLSQ_NUM_THREADS"] = str(threads) + if _USER_ENV["TLSQ_WINDOW_PROCS"] is None and platform.system() == "Darwin": # elsewhere: the Space default (off) + os.environ["TLSQ_WINDOW_PROCS"] = str(threads if threads >= 2 else 0) + if _USER_ENV["TLSQ_LEVEL_PROCS"] is None: + os.environ["TLSQ_LEVEL_PROCS"] = "auto" if threads >= 4 else "0" + return threads + + +@functools.lru_cache(maxsize=1) +def machine() -> str: + cpu = platform.processor() or platform.machine() + if platform.system() == "Darwin": + try: + cpu = ( + subprocess.run( + ["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True, timeout=5 + ).stdout.strip() + or cpu + ) + except Exception: # noqa: BLE001 + pass + elif Path("/proc/cpuinfo").exists(): + for line in Path("/proc/cpuinfo").read_text().splitlines(): + if line.startswith("model name"): + cpu = line.split(":", 1)[1].strip() + break + return f"{cpu}, {os.cpu_count()} CPUs, {platform.system()} {platform.machine()}" diff --git a/src/squadds/ml/capacitance/benchmark.py b/src/squadds/ml/capacitance/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..83d7937b9c13ccaff791b26d3e1a813f9cb6f802 --- /dev/null +++ b/src/squadds/ml/capacitance/benchmark.py @@ -0,0 +1,379 @@ +"""Scoring of capacitance models with the paper's metric rules. + +Per layout and entry kind: the median over its entries of ``|p - y| / max(|y|, 0.1 fF)`` in %, the MAE and the RMSE in fF; then +the mean over layouts (the layout mean), so a 68-conductor chip and a two-pad capacitor count once each. Kinds: ``mutual`` +(every off-diagonal pair, the headline), ``signal-signal``, ``signal-ground``, ``signal_self``, ``ground_self``. Unknown +(NaN) label entries are dropped and counted. Every report carries the wall time, machine and thread count. + +Validation scoring is open to everyone. Test scoring (``split="test"``) is maintainer-only: once per declared model, recorded +in a ledger, and only for models whose training keys are disjoint from the scored layouts (the paper model, TRAIN split). +""" + +from __future__ import annotations + +import json +import os +import time +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np + +FLOOR_FF = 0.1 +KINDS = ("mutual", "signal-signal", "signal-ground", "signal_self", "ground_self") + + +# ---------------------------------------------------------------------------------------------------------------- models +def checkpoint_paths(model) -> list[Path]: + """Checkpoint files of a model given as a CapacitanceModel, a run dir / .pt path, or a list of them.""" + from .models import CapacitanceModel + + if isinstance(model, CapacitanceModel): + if model.entry.get("learned_prior") or model.entry.get("stack") is None: + raise ValueError( + f"{model.key}: array scoring needs a prior-based model (not a learned-prior / solver-free model)" + ) + return [Path(model.root) / c["path"] for c in model.entry["checkpoints"]] + if isinstance(model, (str, os.PathLike)): + p = Path(model) + return [p / "model.pt" if p.is_dir() else p] + if isinstance(model, (list, tuple)): + return [q for m in model for q in checkpoint_paths(m)] + raise TypeError(f"cannot read checkpoints from {type(model).__name__}") + + +def load_checkpoints(model, threads: int = 2) -> list[tuple[dict, object]]: + """[(checkpoint dict, network in eval mode)] of a model (CapacitanceModel, path(s), run dir(s), or checkpoint dict(s)).""" + import torch + + from .network import build_model + + torch.set_num_threads(int(threads)) + items = model if isinstance(model, (list, tuple)) and model and isinstance(model[0], dict) else None + if isinstance(model, dict): + items = [model] + if items is None: + items = [torch.load(p, map_location="cpu", weights_only=False) for p in checkpoint_paths(model)] + out = [] + for c in items: + s = c["scales"] + net = build_model(len(s["X"]["median"]), len(s["E"]["median"]), len(s["G"]["median"]), c["rounds"]) + net.load_state_dict(c["state"]) + net.eval() + out.append((c, net)) + if len({c["arm"] for c, _ in out}) != 1: + raise ValueError("an ensemble must share one arm") + return out + + +def _cols(src: list, dst: list) -> list[int]: + missing = [k for k in dst if k not in src] + if missing: + raise KeyError(f"features {missing[:5]} of the checkpoint are not in the data") + return [src.index(k) for k in dst] + + +def predict_arrays(models, d: dict, schema: dict, rows=None, chunk: int = 64) -> np.ndarray: + """Ensemble-mean Maxwell matrices (fF) of shard rows ``rows`` of one shard dict ``d`` (all rows by default): the + checkpoint's own standardisation, intercepts and arm, as ``infer.Predictor.from_features`` does per layout.""" + import torch + + rows = np.arange(len(d["key"])) if rows is None else np.asarray(rows) + pairs = d["pairs"] + out = np.zeros((len(rows), d["sig"].shape[1], d["sig"].shape[1])) + for c, net in models: + cs = c.get("schema", schema) + nk, ek, gk = cs["nodekeys"], cs["edgekeys"], cs.get("globkeys", schema["globkeys"]) + xi, ei_, gi = _cols(schema["nodekeys"], nk), _cols(schema["edgekeys"], ek), _cols(schema["globkeys"], gk) + arm = c["arm"] + direct = arm == "direct_gnn" + eg = ek.index("is_ground_pair") + ni = nk.index("role_ground") + for s in range(0, len(rows), chunk): + b = rows[s : s + chunk] + X, E, G = d["X"][b][:, :, xi].copy(), d["E"][b][:, :, ei_].copy(), d["G"][b][:, gi].copy() + kinds = E[:, :, eg].astype(int) + if direct: + di = c["direct_intercepts"] + base = np.where(kinds == 0, di["0"], di["1"]).astype(np.float32) + else: + lp = np.log(d["pri"][b].astype(np.float32)) + base = (2 * lp[:, :, 1] - lp[:, :, 0]).astype(np.float32) + E = np.concatenate([E, (lp[:, :, 1] - lp[:, :, 0])[:, :, None]], -1).astype(np.float32) + if arm in ("pair_mlp", "mesh", "lofo_pair"): + X, G = X[:, :, [ni]], np.zeros((len(b), 1), np.float32) + zs = [] + for name, z in (("X", X), ("E", E), ("G", G)): + med, iqr = np.array(c["scales"][name]["median"]), np.array(c["scales"][name]["iqr"]) + zs.append(np.clip((np.where(np.isfinite(z), z, med) - med) / iqr, -10, 10).astype(np.float32)) + cl = c["closure_intercepts"] + bbase = np.where(d["sig"][b], cl.get("1", cl.get("True")), cl.get("0", cl.get("False"))).astype(np.float32) + T = torch.from_numpy + M = torch.ones(d["sig"][b].shape, dtype=torch.bool) + PM = torch.ones(base.shape, dtype=torch.bool) + with torch.inference_mode(): + C, _ = net(T(zs[0]), T(zs[1]), T(zs[2]), M, PM, T(pairs), T(base), T(bbase), direct) + out[s : s + len(b)] += C.numpy().astype(np.float64) + out /= len(models) + if not np.isfinite(out).all(): + raise FloatingPointError("non-finite prediction") + return out + + +# ---------------------------------------------------------------------------------------------------------------- metrics +def entry_kinds(sig: np.ndarray, pairs: np.ndarray) -> np.ndarray: + i, j = pairs.T + return np.where(sig[i] & sig[j], "signal-signal", "signal-ground") + + +def layout_rows(y: np.ndarray, p: np.ndarray, sig: np.ndarray, pairs: np.ndarray, key: str, family: str) -> list[dict]: + """Per-kind metrics of one layout (y, p: Maxwell matrices in fF).""" + i, j = pairs.T + yk, pk = -y[i, j], -p[i, j] + kk = entry_kinds(sig, pairs) + dy, dp = np.diag(y), np.diag(p) + sets = { + "mutual": (yk, pk), + "signal-signal": (yk[kk == "signal-signal"], pk[kk == "signal-signal"]), + "signal-ground": (yk[kk == "signal-ground"], pk[kk == "signal-ground"]), + "signal_self": (dy[sig], dp[sig]), + "ground_self": (dy[~sig], dp[~sig]), + } + out = [] + for kind, (a, b) in sets.items(): + m = np.isfinite(a) + if not m.any(): + continue + a, b = a[m].astype(float), b[m].astype(float) + err = np.abs(b - a) + out.append( + dict( + key=key, + family=family, + kind=kind, + n=int(m.sum()), + dropped=int((~m).sum()), + median_pct=float(np.median(err / np.maximum(np.abs(a), FLOOR_FF)) * 100), + mae_fF=float(err.mean()), + rmse_fF=float(np.sqrt(np.mean(err**2))), + ) + ) + return out + + +def summarize(layouts) -> tuple: + """(per family x kind layout means, overall per kind layout means) of a layout-metric frame.""" + import pandas as pd + + L = layouts if isinstance(layouts, pd.DataFrame) else pd.DataFrame(layouts) + agg = dict( + layouts=("key", "size"), entries=("n", "sum"), median_pct=("median_pct", "mean"), mae_fF=("mae_fF", "mean") + ) + agg["rmse_fF"] = ("rmse_fF", "mean") + fam = L.groupby(["family", "kind"]).agg(**agg).reset_index() + tot = L.groupby("kind").agg(**agg).reset_index() + return fam, tot + + +@dataclass +class ScoreReport: + layouts: object + by_family: object + overall: object + timing: dict = field(default_factory=dict) + split: str = "val" + model: str = "" + + def headline(self, kind: str = "mutual") -> dict: + r = self.overall[self.overall.kind == kind].iloc[0] + return dict( + kind=kind, + layouts=int(r.layouts), + median_pct=float(r.median_pct), + mae_fF=float(r.mae_fF), + rmse_fF=float(r.rmse_fF), + ) + + def __str__(self) -> str: + h = self.headline() + t = self.timing + return ( + f"{self.model} on {self.split}: {h['layouts']} layouts, layout-mean median {h['median_pct']:.4f} % " + f"(MAE {h['mae_fF']:.4f} fF, RMSE {h['rmse_fF']:.4f} fF); {t.get('seconds', 0):.1f} s, " + f"{t.get('threads')} threads, {t.get('machine')}" + ) + + def to_dict(self) -> dict: + return dict( + model=self.model, + split=self.split, + headline=self.headline(), + overall=self.overall.to_dict("records"), + by_family=self.by_family.to_dict("records"), + timing=self.timing, + ) + + +# ---------------------------------------------------------------------------------------------------------------- guards +def _guard(split, maintainer, keys, models, ledger_dir, model_id): + if split != "test": + return None + if not maintainer: + raise PermissionError( + "test scoring is maintainer-only (once per declared model, paper-TRAIN models only); score on split='val'" + ) + if ledger_dir is None: + raise ValueError("maintainer test scoring needs ledger_dir (the once-per-model ledger)") + if models is not None: + trained = set().union(*[set(map(str, c.get("train_keys", []))) for c, _ in models]) + overlap = trained & set(map(str, keys)) + if overlap: + raise PermissionError( + f"{len(overlap)} scored test layouts are training layouts of this model (e.g. {sorted(overlap)[:3]})" + ) + lp = Path(ledger_dir) / f"test__{model_id}.scored" + lp.parent.mkdir(parents=True, exist_ok=True) + try: + fd = os.open(lp, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + except FileExistsError: + raise PermissionError(f"model {model_id} was already scored on test ({lp.read_text().strip()})") from None + with os.fdopen(fd, "w") as f: + f.write(json.dumps(dict(time=time.strftime("%Y-%m-%dT%H:%M:%S%z"), layouts=len(keys)))) + return lp + + +def _model_id(models) -> str: + import hashlib + + h = hashlib.sha256() + for _, net in models: + for k, v in sorted(net.state_dict().items()): + h.update(k.encode()) + h.update(v.numpy().tobytes()) + return h.hexdigest()[:16] + + +# ---------------------------------------------------------------------------------------------------------------- score +def score( + model, + data, + labels=None, + split: str = "val", + maintainer: bool = False, + threads: int = 2, + families=None, + keys=None, + ledger_dir=None, + name: str | None = None, + **predict_kwargs, +) -> ScoreReport: + """Score a model on the ``split`` rows of a shard dir, or on layouts with labels. + + model: ``"flagship"`` / ``"fast"`` / ``"paper"`` (released), a CapacitanceModel, a run dir / + .pt path (or a list = ensemble), or checkpoint dict(s). data: a shard dir (array route: the stored embedding and priors) or + a list of layouts (GDS paths / PreparedLayouts, predicted end to end) with ``labels`` = one (names, Maxwell matrix fF) or + ``cap_matrix.csv`` path per layout. ``families`` / ``keys`` restrict the shard rows.""" + from ._runtime import machine + from .training_data import read_q3d_csv, read_schema, read_shards + + if split == "test" and not maintainer: + _guard(split, maintainer, [], None, ledger_dir, "") + t0 = time.perf_counter() + rows = [] + if isinstance(data, (str, os.PathLike)) and Path(data).is_dir(): + if isinstance(model, str) and model in ("paper", "flagship", "fast"): + from .models import load_model + + model = load_model(model) + models = load_checkpoints(model, threads) + schema = read_schema(data) + sel = [] + for d in read_shards(data): + m = d["split"] == split + if families is not None: + m &= np.isin(d["family"], list(families)) + if keys is not None: + m &= np.isin(d["key"], list(keys)) + if m.any(): + sel.append((d, np.flatnonzero(m))) + all_keys = [str(k) for d, ix in sel for k in d["key"][ix]] + if not all_keys: + raise ValueError(f"no {split!r} rows in {data}") + mid = _model_id(models) + _guard(split, maintainer, all_keys, models, ledger_dir, mid) + tn = 0.0 + for d, ix in sel: + t = time.perf_counter() + P = predict_arrays(models, d, schema, ix) + tn += time.perf_counter() - t + for b, p in zip(ix, P): + rows += layout_rows( + d["C"][b].astype(float), p, d["sig"][b], d["pairs"], str(d["key"][b]), str(d["family"][b]) + ) + timing = dict( + network_s=tn, per_layout_network_s=tn / len(all_keys), route="shard arrays (stored embedding + priors)" + ) + label = name or f"{models[0][0]['arm']} x{len(models)} ({mid})" + else: + from .models import CapacitanceModel, load_model + from .predictor import CapacitancePredictor + + items = list(data) if isinstance(data, (list, tuple)) else [data] + if labels is None or len(labels) != len(items): + raise ValueError("layout scoring needs one label per layout") + if split == "test": + raise PermissionError("maintainer test scoring runs on shard dirs (train keys are checked there)") + if isinstance(model, str): + model = load_model(model) + if not isinstance(model, CapacitanceModel): + from .train import trained_model + + model = trained_model(checkpoint_paths(model)) + pred = CapacitancePredictor(model, threads=threads) + times = [] + for k, (lay, lab) in enumerate(zip(items, labels)): + names, C = (read_q3d_csv(lab)[:2]) if isinstance(lab, (str, os.PathLike)) else lab + r = pred.predict(lay, **predict_kwargs) + times.append(r.timing_s["total_s"]) + if sorted(r.names) != sorted(names): + raise ValueError(f"layout {k}: predicted nets {r.names} differ from the label nets {names}") + idx = [list(names).index(x) for x in r.names] + y = np.asarray(C, float)[np.ix_(idx, idx)] + sig = np.array([x != "G" for x in r.names]) + rows += layout_rows( + y, + r.matrix_fF, + sig, + np.array([(i, j) for i in range(len(sig)) for j in range(i + 1, len(sig))]), + str(getattr(lay, "source", lay)), + "layouts", + ) + timing = dict( + total_s=float(np.sum(times)), + per_layout_median_s=float(np.median(times)), + route="end to end from the layout", + ) + label = name or model.key + import pandas as pd + + L = pd.DataFrame(rows) + fam, tot = summarize(L) + timing.update(seconds=time.perf_counter() - t0, threads=int(threads), machine=machine()) + return ScoreReport(L, fam, tot, timing, split, label) + + +def paired_difference(a, b, kind: str = "mutual", n_boot: int = 2000, seed: int = 0) -> dict: + """Layout-paired difference a - b of the layout means (median % and MAE fF) with a layout-bootstrap 95% interval. + a, b: ScoreReports or layout frames scored on the same layouts.""" + La = (a.layouts if hasattr(a, "layouts") else a).query("kind == @kind").set_index("key") + Lb = (b.layouts if hasattr(b, "layouts") else b).query("kind == @kind").set_index("key") + common = La.index.intersection(Lb.index) + if len(common) != len(La) or len(common) != len(Lb): + raise ValueError("the two scores are not on the same layouts") + rng = np.random.default_rng(seed) + out = {"layouts": len(common)} + for col in ("median_pct", "mae_fF", "rmse_fF"): + d = (La.loc[common, col] - Lb.loc[common, col]).to_numpy() + boot = d[rng.integers(0, len(d), (n_boot, len(d)))].mean(1) if len(d) > 1 else np.array([d.mean()] * 2) + out[col] = dict(diff=float(d.mean()), lo=float(np.percentile(boot, 2.5)), hi=float(np.percentile(boot, 97.5))) + return out diff --git a/src/squadds/ml/capacitance/bridge.py b/src/squadds/ml/capacitance/bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bfbb1d69a1abcb782d5b4076d25594304b12a6cb --- /dev/null +++ b/src/squadds/ml/capacitance/bridge.py @@ -0,0 +1,448 @@ +"""Bridges from the planar capacitance models into the existing SQuADDS workflows. + +- ``MLSimulator``: the call and result shape of the capacitance (Q3D / LOM) path of ``AnsysSimulator`` + (``simulate(device_dict)`` -> ``{"design", "sim_options", "sim_results"}``) plus ``fidelity="ml:"`` and ``timing``. + Input: a Qiskit Metal design or component, a SQuADDS row (rebuilt with the component registry) or a GDS path. +- ``predict_dataframe``: predictions for the rows of an Analyzer result (``Analyzer.predict_capacitance`` calls it). +- ``transmon_cross_capacitances`` / ``EC_MHz`` / ``g_MHz`` / ``EC_MHz_from_matrix``: feed ``squadds.calcs``. + +Export (``export=``): ``"auto"`` (default) writes a component of a dataset family (``squadds.layouts.dataset_export``: +interdigital / paddle, concentric, star, Xmon, TransmonPocket, shielded concentric) exactly as the dataset was exported, +so the model sees the input it was trained on; any other layout (e.g. quantum-metal ``TransmonCross``, several +components) goes through ``export_qgeometry_gds`` (square ground domain, 169 um padding). ``"dataset"`` / ``"qgeometry"`` +force one. The result records it in ``export``. Star rows of the SQuADDS view carry their style in +``notes.export_style``. Conductor bodies are named from the qgeometry they overlap (``planar_capacitance_view.QGEOMETRY_NETS``), so the +``sim_results`` keys match the SQuADDS configs (``north_to_south``, ``cross_to_claw``, ...). +""" + +from __future__ import annotations + +import importlib +import os +import tempfile +import time +from copy import deepcopy +from pathlib import Path +from typing import Any + +import numpy as np + +from squadds.database.planar_capacitance_view import QGEOMETRY_NETS, net_name, sim_results_from_matrix + +QISKIT_METAL_CLASSES = { + "TransmonCross": "qiskit_metal.qlibrary.qubits.transmon_cross", + "TransmonPocket": "qiskit_metal.qlibrary.qubits.transmon_pocket", +} +GAP_OPTION_KEYS = ("cpw_gap", "claw_gap", "ground_spacing", "gap_ground", "ground_gap", "min_trace_gap", "cross_gap") +DEFAULT_CLEARANCE_UM = 5.0 +EXPORTS = ("auto", "dataset", "qgeometry") + + +# ------------------------------------------------------------------------------------------------ rows -> components +def _clean(value): + """Drop ``None`` / NaN entries (union-schema padding of HF rows) and numpy scalars from an options tree.""" + if isinstance(value, dict): + return {k: _clean(v) for k, v in value.items() if not _is_missing(v)} + if isinstance(value, (list, tuple)): + return [_clean(v) for v in value] + if isinstance(value, np.generic): + return value.item() + return value + + +def _is_missing(v) -> bool: + return v is None or (isinstance(v, float) and np.isnan(v)) + + +def row_options_and_class(row, component_name: str | None = None) -> tuple[dict, str]: + """(design_options, component class name) of a SQuADDS row: nested HF record, flattened DataFrame row (Series or + dict) or an ``AnsysSimulator`` device dict.""" + from squadds.core.json_utils import deserialize_json_like + + if hasattr(row, "to_dict"): + row = row.to_dict() + rec = row["design"] if isinstance(row.get("design"), dict) else row + opts = deserialize_json_like(rec.get("design_options", row.get("design_options"))) + if not isinstance(opts, dict): + raise ValueError("row has no design_options") + cls = component_name + for key in ("component_class", "component_name", "coupler_type"): + if cls is None and isinstance(rec.get(key), str) and rec.get(key): + cls = rec[key] + if cls is None and "cross_length" in opts: + cls = "TransmonCross" + if cls is None: + raise ValueError("cannot tell the component class of this row: pass component_name=") + return _clean(opts), cls + + +def component_class(name: str): + """Qiskit Metal class of a dataset component name (SQuADDS registry first, then quantum-metal qubits).""" + from squadds.components import get_component_class + + try: + return get_component_class(name) + except ValueError: + if name in QISKIT_METAL_CLASSES: + return getattr(importlib.import_module(QISKIT_METAL_CLASSES[name]), name) + raise + + +def build_component(row, component_name: str | None = None, design=None, name: str = "component"): + """Rebuild the component of a SQuADDS row in ``design`` (a new ``DesignPlanar`` by default).""" + from qiskit_metal import designs + + opts, cls = row_options_and_class(row, component_name) + design = design if design is not None else designs.DesignPlanar({}, overwrite_enabled=True) + comp = component_class(cls)(design, name, options=opts) + design.rebuild() + return comp + + +# ------------------------------------------------------------------------------------------------ rendering and naming +def _length_um(design, value) -> float | None: + try: + v = float(design.parse_value(value)) * 1e3 + except Exception: # noqa: BLE001 + return None + return v if v > 0 else None + + +def default_clearance_um(design) -> float: + """Signal-to-ground clearance for the exported ground: the smallest lead / claw / ground gap option of the components + (the native etch stays authoritative; the clearance only closes open CPW ends).""" + found = [] + + def scan(opts): + for k, v in opts.items(): + if isinstance(v, dict): + scan(v) + elif any(k.endswith(g) for g in GAP_OPTION_KEYS) and isinstance(v, (str, int, float)): + for part in str(v).split(","): + um = _length_um(design, part.strip()) if part.strip() else None + if um: + found.append(um) + + for comp in design.components.values(): + scan(dict(comp.options)) + return min(found) if found else DEFAULT_CLEARANCE_UM + + +def render_gds(design, path, clearance_um: float | None = None) -> Path: + """Export ``design`` to a GDS in the training layer convention (ground (1, 0), conductors (1, 10)).""" + from squadds.layouts.qmetal_gds import export_qgeometry_gds + + path = Path(path) + clearance = float(clearance_um or default_clearance_um(design)) + export_qgeometry_gds(design, path, include_ground_domain=True, minimum_ground_clearance_um=clearance) + return path + + +def _qgeometry_elements(design) -> list[tuple[str, str, str, Any]]: + """(component class, component name, element name, geometry in µm) of every conductor qgeometry element.""" + from shapely import affinity + + out = [] + for table in ("poly", "path"): + for r in design.qgeometry.tables[table].itertuples(index=False): + if bool(r.helper) or bool(r.subtract): + continue + g = r.geometry + if table == "path": + g = g.buffer(float(r.width) / 2, cap_style="flat", join_style="round") + comp = design._components[r.component] + out.append((type(comp).__name__, comp.name, r.name, affinity.scale(g, 1e3, 1e3, origin=(0, 0)))) + return out + + +def body_labels(conductors, design) -> tuple[list[str], str | None]: + """Dataset net label (``N``, ``S``, ``P1``, ...) of each conductor body, and the component class when the layout has a + single component. Unmapped bodies keep the predictor's name ``C``; with several components the labels are + ``:``.""" + elems = _qgeometry_elements(design) + classes = {e[0] for e in elems} + single = next(iter(classes)) if len({e[1] for e in elems}) == 1 else None + labels = [] + for k, body in enumerate(conductors): + hits = [e for e in elems if body.intersection(e[3]).area > 1e-6 * max(e[3].area, 1e-12)] + lab = None + if single and hits: + cands = {QGEOMETRY_NETS.get(single, {}).get(e[2]) for e in hits} + cands.discard(None) + lab = cands.pop() if len(cands) == 1 else None + elif hits: + lab = "+".join(sorted({f"{e[1]}:{e[2]}" for e in hits})) + lab = lab or f"C{k + 1}" + while lab in labels: + lab = f"{lab}'" + labels.append(lab) + return labels, single + + +# ------------------------------------------------------------------------------------------------ simulator +class MLSimulator: + """Capacitance from the planar capacitance models, in the result shape of ``AnsysSimulator``'s capacitance path. + + sim = MLSimulator(analyzer, device_dict) # like AnsysSimulator(analyzer, device_dict) + res = sim.simulate() # {"design", "sim_options", "sim_results", ...} + MLSimulator(model="fast").predict("chip.gds") # or a component, a design or a SQuADDS row + + model: ``"flagship"`` (default), ``"fast"``, ``"paper"`` or a loaded ``CapacitanceModel``. ``predictor``: any object with ``predict(layout) -> CapacitanceResult`` (tests). + export: ``"auto"`` (dataset export for the dataset families, else ``"qgeometry"``), ``"dataset"`` or + ``"qgeometry"``; ``export_style`` / ``margin_gaps`` / ``ground_gap_um`` override the dataset export + (``squadds.layouts.dataset_export.export_dataset_gds``; a row's ``notes.export_style`` is used when not set). + """ + + def __init__( + self, + analyzer=None, + design_options=None, + model="flagship", + threads: int = 2, + predictor=None, + clearance_um: float | None = None, + workdir=None, + export: str = "auto", + export_style: str | None = None, + margin_gaps: float | None = None, + ground_gap_um: float | None = None, + tier=None, + **predict_kwargs, + ): + from .models import no_tier + + no_tier(tier) + self.analyzer = analyzer + self.device_dict = deepcopy(design_options) if design_options is not None else None + self.model, self.threads = model or "flagship", int(threads) + self.clearance_um = clearance_um + if export not in EXPORTS: + raise ValueError(f"export must be one of {EXPORTS}") + self.export, self.export_style = export, export_style + self.margin_gaps, self.ground_gap_um = margin_gaps, ground_gap_um + self.workdir = Path(workdir) if workdir is not None else None + self.predict_kwargs = predict_kwargs + self._predictor = predictor + + def __repr__(self) -> str: + return f"MLSimulator(model={getattr(self.model, 'key', self.model)!r})" + + @property + def predictor(self): + if self._predictor is None: + from squadds.ml.capacitance import CapacitancePredictor + + self._predictor = CapacitancePredictor(self.model, threads=self.threads) + return self._predictor + + @property + def fidelity(self) -> str: + m = getattr(self._predictor, "model", None) or self.model + return f"ml:{getattr(m, 'name', m)}" + + def simulate(self, device_dict=None, run_async: bool = False) -> dict: + """``AnsysSimulator.simulate`` for single components (capacitance only).""" + if run_async: + raise NotImplementedError("MLSimulator predicts synchronously (about a second per design).") + if self.analyzer is not None and isinstance(getattr(self.analyzer, "selected_system", None), list): + raise NotImplementedError( + "MLSimulator predicts capacitance matrices of single components; the eigenmode part of a qubit-cavity " + "system stays with AnsysSimulator." + ) + device_dict = device_dict if device_dict is not None else self.device_dict + if device_dict is None: + raise ValueError("no device dict: pass design_options= to MLSimulator or device_dict= to simulate()") + name = None + if self.analyzer is not None and not _row_declares_class(device_dict): + name = getattr(self.analyzer, "selected_coupler", None) or getattr( + self.analyzer, "selected_component_name", None + ) + return self.predict(device_dict, component_name=name) + + def predict(self, obj, component_name: str | None = None) -> dict: + """Prediction for a GDS path, a Qiskit Metal design or component, or a SQuADDS row / device dict.""" + from qiskit_metal.designs import QDesign + from qiskit_metal.qlibrary.core import QComponent + + t0 = time.perf_counter() + design, options, cls_name, gds, notes = None, None, None, None, {} + if isinstance(obj, (str, os.PathLike)): + gds = Path(obj) + elif isinstance(obj, QComponent): + design, options, cls_name = obj.design, dict(obj.options), type(obj).__name__ + elif isinstance(obj, QDesign): + design = obj + else: + comp = build_component(obj, component_name) + design, options, cls_name = comp.design, dict(comp.options), type(comp).__name__ + notes = row_notes(obj) + warnings = [] + if notes.get("geometry_reproducible") is False: + warnings.append( + f"{notes.get('design_id', 'this row')}: the stored options do not rebuild the solved GDS exactly; the " + "prediction is for the rebuilt layout" + ) + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + export = {"convention": "gds", "path": str(gds)} if gds is not None else None + if gds is None: + out = (self.workdir or Path(tmp)) / f"{cls_name or 'design'}_{int(time.time() * 1e6)}.gds" + gds, design, export = self._export(obj if isinstance(obj, QComponent) else design, out, notes) + render_s = time.perf_counter() - t0 + from squadds.ml.capacitance._runtime import prepare_layout + + lay = prepare_layout(str(gds)) + res = self.predictor.predict(lay, **self.predict_kwargs) + if design is not None: + bodies, single = body_labels(lay.conductors, design) + labels = ["G", *bodies] + else: + labels, single = list(res.names), None + sim_results = sim_results_from_matrix(labels, res.matrix_fF, single or "") + timing = {"render_s": render_s, **dict(res.timing_s), "wall_s": time.perf_counter() - t0} + return { + "design": { + "design_options": _clean(options) if options is not None else None, + "design_tool": "qiskit-metal", + "component_class": cls_name, + "gds": str(gds) if self.workdir is not None or export["convention"] == "gds" else None, + "export": export, + }, + "sim_options": { + "sim_type": "cap_matrix", + "setup": {"model": res.model, "threads": res.threads, "prior": res.prior_version}, + "layer_stack": dict(res.substrate), + "simulator": f"squadds.ml.capacitance ({res.model})", + }, + "sim_results": sim_results, + "fidelity": f"ml:{res.model}", + "timing": timing, + "net_names": {lab: net_name(single or "", lab) for lab in labels}, + "checks": dict(res.checks), + "warnings": warnings + list(res.warnings), + "export": export, + "prediction": res, + } + + def _export(self, obj, out: Path, notes: dict): + """Write ``obj`` (a component or a design) to ``out``: ``(gds, design whose qgeometry names the bodies, export + record)``.""" + from qiskit_metal.designs import QDesign + + from squadds.layouts.dataset_export import dataset_export_layout, family_of, write_dataset_gds + + out.parent.mkdir(parents=True, exist_ok=True) + family = family_of(obj) + if self.export == "dataset" and family is None: + raise ValueError("export='dataset' needs one component of a dataset family; use export='qgeometry'") + if self.export == "qgeometry" or family is None: + design = obj if isinstance(obj, QDesign) else obj.design + clearance = float(self.clearance_um or default_clearance_um(design)) + gds = render_gds(design, out, clearance) + return gds, design, {"convention": "qgeometry", "clearance_um": clearance} + style = self.export_style or (notes.get("export_style") if family == "star" else None) + gap = self.ground_gap_um if self.ground_gap_um is not None else notes.get("ground_gap_um") + cell, design, settings = dataset_export_layout(obj, None, self.margin_gaps, style, gap) + return write_dataset_gds(cell, out), design, settings + + +def row_notes(row) -> dict: + """``notes`` of a SQuADDS row (nested record or flattened DataFrame row); {} for a device dict without notes.""" + if hasattr(row, "to_dict"): + row = row.to_dict() + if not isinstance(row, dict): + return {} + notes = row.get("notes") + if isinstance(notes, dict): + return notes + keys = ("design_id", "export_style", "geometry_reproducible", "ground_gap_um") + return {k: row[k] for k in keys if k in row and not _is_missing(row[k])} + + +def _row_declares_class(row) -> bool: + if hasattr(row, "to_dict"): + row = row.to_dict() + rec = row["design"] if isinstance(row.get("design"), dict) else row + return any( + isinstance(rec.get(k), str) and rec.get(k) for k in ("component_class", "component_name", "coupler_type") + ) + + +def predict_dataframe(df, model="flagship", component_name=None, simulator=None, **kwargs): + """One prediction per row of a SQuADDS DataFrame (closest designs, interpolated designs): a DataFrame with the same + index, the predicted ``sim_results`` columns (suffix ``_ml``), ``fidelity``, ``ml_total_s`` and ``ml_result``.""" + import pandas as pd + + sim = simulator or MLSimulator(model=model, **kwargs) + if isinstance(df, dict): + df = pd.DataFrame([df]) + out = [] + for _, row in df.iterrows(): + name = component_name if not _row_declares_class(row) else None + r = sim.predict(row, component_name=name) + rec = {f"{k}_ml": v for k, v in r["sim_results"].items() if k not in ("maxwell_matrix", "units")} + rec.update( + maxwell_matrix_ml=r["sim_results"]["maxwell_matrix"], + fidelity=r["fidelity"], + ml_total_s=r["timing"].get("wall_s"), + ml_result=r, + ) + out.append(rec) + return pd.DataFrame(out, index=df.index) + + +# ------------------------------------------------------------------------------------------------ calcs helpers +def _sim_results_of(x) -> dict: + if hasattr(x, "to_sim_results"): + return x.to_sim_results() + if hasattr(x, "to_dict"): + x = x.to_dict() + return x["sim_results"] if isinstance(x.get("sim_results"), dict) else x + + +def transmon_cross_capacitances(x) -> dict: + """``cross_to_claw`` and ``cross_to_ground`` (fF) of a TransmonCross / Xmon prediction or row, the inputs of + ``squadds.calcs.transmon_cross`` (EC, g). x: an MLSimulator result, a ``sim_results`` dict or a DataFrame row.""" + sr = _sim_results_of(x) + missing = [k for k in ("cross_to_claw", "cross_to_ground") if sr.get(k) is None] + if missing: + raise KeyError(f"not a TransmonCross / Xmon result (missing {missing})") + return {"cross_to_claw": float(sr["cross_to_claw"]), "cross_to_ground": float(sr["cross_to_ground"])} + + +def EC_MHz(x) -> float: + """Charging energy (MHz) with the existing SQuADDS convention ``C_sum = cross_to_ground + cross_to_claw`` + (``squadds.calcs.transmon_cross.EC_numba``). A second claw is not included: use ``EC_MHz_from_matrix`` for it.""" + from squadds.calcs.transmon_cross import EC_numba + + c = transmon_cross_capacitances(x) + return 1e3 * float(EC_numba(c["cross_to_claw"], c["cross_to_ground"])) + + +def g_MHz(x, EJ_GHz: float, f_r_GHz: float, res_type: str = "quarter", Z0: float = 50.0) -> float: + """Qubit-claw coupling g (MHz) from ``squadds.calcs.transmon_cross.g_from_cap_matrix_numba`` with the predicted + ``cross_to_ground`` (C_Q) and ``cross_to_claw`` (C_g).""" + from squadds.calcs.transmon_cross import g_from_cap_matrix_numba + + c = transmon_cross_capacitances(x) + return float(g_from_cap_matrix_numba(c["cross_to_ground"], c["cross_to_claw"], EJ_GHz, f_r_GHz, res_type, Z0)) + + +def EC_MHz_from_matrix(C, names, nodes) -> float: + """Charging energy (MHz) of a qubit mode from a full Maxwell matrix (fF, every other conductor held at ground). + + nodes: one conductor name (grounded transmon: C_sum = C_ii, every coupling included) or two (floating transmon, the + differential mode: 1 / C_eff = (C^-1)_aa + (C^-1)_bb - 2 (C^-1)_ab of the two-pad block).""" + from scipy.constants import Planck, e + + C = np.asarray(C, float) + names = list(names) + nodes = [nodes] if isinstance(nodes, str) else list(nodes) + idx = [names.index(n) for n in nodes] + if len(idx) == 1: + c_eff = C[idx[0], idx[0]] + elif len(idx) == 2: + inv = np.linalg.inv(C[np.ix_(idx, idx)]) + c_eff = 1.0 / (inv[0, 0] + inv[1, 1] - 2 * inv[0, 1]) + else: + raise ValueError("nodes: one conductor (grounded) or two (floating pair)") + return e**2 / (2 * c_eff * 1e-15) / Planck * 1e-6 diff --git a/src/squadds/ml/capacitance/cli.py b/src/squadds/ml/capacitance/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..6b071036fa7748759e25e54b816f8812fbc17cc6 --- /dev/null +++ b/src/squadds/ml/capacitance/cli.py @@ -0,0 +1,90 @@ +"""``squadds-ml predict``: GDS -> full Maxwell capacitance matrix (fF, ground first) from the command line.""" + +from __future__ import annotations + +import argparse +import atexit +import json +import sys + + +def _layers(s: str) -> list[tuple[int, int]]: + return [tuple(int(v) for v in x.split("/")) for x in s.split(",") if x] + + +def _no_exit_ansi_reset() -> None: + """numba colours its messages with colorama, whose exit hook writes an ANSI reset to a terminal stdout: drop that hook + so CSV / JSON output ends with the data.""" + ini = sys.modules.get("colorama.initialise") + if ini is not None: + atexit.unregister(ini.reset_all) + + +def cmd_predict(a) -> int: + from squadds.ml import require_ml + + require_ml() + from .models import load_model + from .predictor import CapacitancePredictor + + model = load_model(a.model, path=a.model_path, revision=a.revision) + pred = CapacitancePredictor(model, threads=a.threads) + kw = {"ground_layers": _layers(a.ground), "conductor_layers": _layers(a.conductor)} + if a.ground_pieces: + kw["ground_pieces"] = [int(x) for x in a.ground_pieces.split(",") if x.strip()] + res = pred.predict( + a.gds if len(a.gds) > 1 else a.gds[0], + eps_r=a.eps_r, + thickness_um=a.thickness_um, + workers=a.workers, + **kw, + ) + res = res if isinstance(res, list) else [res] + _no_exit_ansi_reset() + if a.format == "json": + out = [r.to_dict() for r in res] + print(json.dumps(out if len(out) > 1 else out[0], indent=1)) + else: + for path, r in zip(a.gds, res): + print(f"# {path}: {r.model}, {r.timing_s['total_s']:.3g} s ({r.threads} threads, {r.machine})") + for w in r.warnings: + print(f"# warning: {w}") + print(r.to_dataframe().to_csv(float_format="%.6g"), end="") + return 0 + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(prog="squadds-ml", description="SQuADDS planar capacitance models") + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("predict", help="GDS -> full N x N Maxwell capacitance matrix (fF, ground first)") + p.add_argument("gds", nargs="+") + p.add_argument("--model", default="flagship", choices=["flagship", "fast", "paper"]) + p.add_argument( + "--model-path", default=None, help="local model bundle (else $SQUADDS_CAPML_MODELS, else Hugging Face)" + ) + p.add_argument("--revision", default=None) + p.add_argument("--threads", type=int, default=2) + p.add_argument("--workers", type=int, default=1, help="processes for several GDS files") + p.add_argument("--ground", default="1/0", help="ground layers, e.g. 1/0,2/0") + p.add_argument("--conductor", default="1/10", help="conductor layers, e.g. 1/10") + p.add_argument( + "--ground-pieces", + default=None, + help="ground and conductors on one layer: the metal pieces that form the ground (numbers as in the figure of " + "inspect_layout, e.g. 1 or 1,4); default = detected automatically, with a warning", + ) + p.add_argument("--eps-r", type=float, default=11.45, help="substrate permittivity (the prior is solved at it)") + p.add_argument( + "--thickness-um", type=float, default=350.0, help="substrate thickness in µm (the prior is solved at it)" + ) + p.add_argument("--format", default="csv", choices=["csv", "json"]) + p.set_defaults(func=cmd_predict) + from .train import add_train_subcommand + + add_train_subcommand(sub) + a = ap.parse_args(argv) + return a.func(a) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/squadds/ml/capacitance/contribute.py b/src/squadds/ml/capacitance/contribute.py new file mode 100644 index 0000000000000000000000000000000000000000..1a058b4c46435fb078c186917ec785bd7e709283 --- /dev/null +++ b/src/squadds/ml/capacitance/contribute.py @@ -0,0 +1,640 @@ +"""Contributing planar capacitance data and models to ``SQuADDS/SQuADDS_PlanarCapacitance`` (Hugging Face pull requests). + +Data: a contribution directory in the template layout (``squadds/database/templates/planar_capacitance_contribution``):: + + manifest.yaml contributor, licence, solver, stack, setup, layer map, units, generator, family + designs.csv design, gds, family, params_json, net_order (G first, then conductors in GDS file order), notes + gds/.gds + sims///cap_matrix.csv Q3D export as is (one row per pass) or matrix.csv / matrix.parquet + sims///convergence.txt the Q3D .conv file (optional) + sims///run.json solver version, cores, solve_s, wall_s, peak_mem_GB, machine (optional) + nets/.json {net: [conductor-layer polygon indices]} (optional explicit net map) + +``validate_capacitance_contribution(dir)`` runs the dataset validator (schema, GDS readback, net names, label QC, duplicates, +stack, licence, privacy) and ``contribute_capacitance(dir)`` opens a pull request adding ``contrib/-/`` and its +``validation_report.md``. Maintainers merge, compute the priors on HPC and ingest the rows as ``source="community"``, +``split="none"``. + +Models: ``contribute_model(repo_id, revision)`` validates a model repository (checkpoints load, sha256, required metadata, +validation score with median % and MAE / RMSE in fF plus time, machine and threads) and opens a pull request adding its entry +to ``model_zoo.yaml``. Test-set scores are never self-reported: they are run by the maintainers, once per declared model, only +for models trained on the paper's TRAIN split. +""" + +from __future__ import annotations + +import csv +import io +import json +import os +import re +import time +from pathlib import Path + +import numpy as np + +from squadds.datasets.planar_capacitance_schema import REPO_ID + +from . import qc as Q + +LICENCES = {"cc-by-4.0": "CC-BY-4.0", "cc0-1.0": "CC0-1.0", "cc0": "CC0-1.0", "cc-by 4.0": "CC-BY-4.0"} +MANIFEST_REQUIRED = { + "contributor": dict, + "licence": str, + "solver": dict, + "stack": dict, + "setup": dict, + "layer_map": dict, + "ground_net_name": str, + "units": dict, + "generator": dict, + "family": str, + "description": str, +} +DESIGN_COLUMNS = ("design", "gds", "family", "params_json", "net_order", "notes") +MATRIX_FILES = ("cap_matrix.csv", "matrix.csv", "matrix.parquet") +CONV_FILES = ("convergence.txt",) +UPLOAD_DIRS = ("gds", "sims", "nets") +ZOO_FILE = "model_zoo.yaml" +MODEL_META_FILES = ("squadds_model.yaml", "squadds_model.json") +MODEL_REQUIRED = ("name", "title", "licence", "training_data", "val_score", "contributor") +VAL_REQUIRED = ("median_pct", "mae_fF", "rmse_fF", "layouts", "machine", "threads") +VAL_TIME = ("seconds", "seconds_per_layout") +_ABS = re.compile(r"^(/|~/|[A-Za-z]:[\\/]|\\\\)") + + +def _slug(s: str) -> str: + return re.sub(r"[^a-z0-9._-]+", "-", str(s).lower()).strip("-.") + + +def _yaml(): + try: + import yaml + except ImportError as e: + raise ImportError("contributions need pyyaml: pip install pyyaml (or 'squadds[ml]')") from e + return yaml + + +def _api(api=None, token=None): + if api is not None: + return api + from huggingface_hub import HfApi + + from squadds.database.contributor_env import load_contributor_environment + + load_contributor_environment() + return HfApi(token=token or os.getenv("HUGGINGFACE_API_KEY") or None) + + +def submitter_record() -> dict: + """The contributor block of the repo-root ``.env`` (GROUP_NAME, PI_NAME, INSTITUTION, USER_NAME, CONTRIB_MISC).""" + from squadds.database.contributor_env import build_contributor_record + + return build_contributor_record() + + +# ---------------------------------------------------------------------------------------------------------------- privacy +def _scrub(o, path: str, fixes: list): + """Absolute local paths -> file names (recorded in ``fixes``).""" + if isinstance(o, dict): + return {k: _scrub(v, f"{path}.{k}", fixes) for k, v in o.items()} + if isinstance(o, list): + return [_scrub(v, f"{path}[{i}]", fixes) for i, v in enumerate(o)] + if isinstance(o, str) and _ABS.match(o.strip()) and len(o.strip()) > 1: + fixes.append(f"{path}: absolute path replaced by its file name") + return re.split(r"[\\/]", o.strip().rstrip("/\\"))[-1] + return o + + +def sanitized_manifest(manifest: dict) -> tuple[dict, list[str]]: + """The manifest as it is uploaded: absolute paths stripped, the e-mail dropped unless ``contributor.email_public``.""" + fixes: list[str] = [] + m = _scrub(manifest, "manifest", fixes) + c = dict(m.get("contributor") or {}) + if c.get("email") and not c.get("email_public"): + c.pop("email") + fixes.append("manifest.contributor.email removed (email_public is not true)") + m["contributor"] = c + return m, fixes + + +def _sanitized_designs_csv(rows: list[dict], fixes: list[str]) -> str: + out = io.StringIO() + cols = list(dict.fromkeys([*DESIGN_COLUMNS, *(k for r in rows for k in r)])) + w = csv.DictWriter(out, fieldnames=cols) + w.writeheader() + for r in rows: + w.writerow({k: _scrub(r.get(k, ""), f"designs.csv[{r.get('design')}].{k}", fixes) for k in cols}) + return out.getvalue() + + +# ---------------------------------------------------------------------------------------------------------------- reading +def load_manifest(path) -> dict: + p = Path(path) / "manifest.yaml" + if not p.exists(): + raise FileNotFoundError(f"{p} not found (copy the template manifest.yaml)") + return _yaml().safe_load(p.read_text()) or {} + + +def read_designs(path) -> list[dict]: + p = Path(path) / "designs.csv" + if not p.exists(): + raise FileNotFoundError(f"{p} not found (copy the template designs.csv)") + with open(p, newline="") as f: + return [ + {k.strip(): (v or "").strip() for k, v in r.items() if k} + for r in csv.DictReader(line for line in f if not line.lstrip().startswith("#")) + ] + + +def parse_net_order(s: str) -> list[str]: + s = (s or "").strip() + if s.startswith("["): + return [str(x) for x in json.loads(s)] + return [x.strip() for x in re.split(r"[;|,\s]+", s) if x.strip()] + + +def read_sim(sim_dir, unit: str = "fF") -> dict: + """One simulation directory -> {"names", "C" (label, given unit), "passes", "unit", "convergence", "run"}.""" + d = Path(sim_dir) + out: dict = {"convergence": None, "run": None} + if (d / "cap_matrix.csv").exists(): + m = Q.read_cap_matrix(d / "cap_matrix.csv") + complete = [(p, C) for p, C in m["passes"] if np.isfinite(C).all()] + out.update(names=m["names"], passes=m["passes"], unit="fF", units_found=m["units"], freq_GHz=m["freq_GHz"]) + out["C"] = complete[-1][1] if complete else np.full((len(m["names"]),) * 2, np.nan) + else: + f = next((d / n for n in ("matrix.parquet", "matrix.csv") if (d / n).exists()), None) + if f is None: + raise FileNotFoundError(f"{d}: no {' / '.join(MATRIX_FILES)}") + import pandas as pd + + df = pd.read_parquet(f) if f.suffix == ".parquet" else pd.read_csv(f) + val = "C_fF" if "C_fF" in df else "C" + if val not in df or not {"net_a", "net_b"} <= set(df.columns): + raise ValueError(f"{f}: needs columns net_a, net_b and C_fF (or C in the manifest unit)") + u = "fF" if val == "C_fF" else unit + order = list(dict.fromkeys([*map(str, df.net_a), *map(str, df.net_b)])) + names = ([Q.GROUND] if Q.GROUND in order else []) + [x for x in order if x != Q.GROUND] + ix = {n: i for i, n in enumerate(names)} + + def mat(sub): + C = np.full((len(names), len(names)), np.nan) + for a, b, v in zip(sub.net_a, sub.net_b, sub[val]): + C[ix[str(a)], ix[str(b)]] = C[ix[str(b)], ix[str(a)]] = float(v) + return C + + if "pass" in df: + passes = [(int(p), mat(g)) for p, g in df.groupby("pass")] + out.update(passes=passes, C=passes[-1][1]) + else: + out.update(passes=None, C=mat(df)) + out.update(names=names, unit=u) + conv = next((p for p in [*(d / n for n in CONV_FILES), *sorted(d.glob("*.conv"))] if p.exists()), None) + if conv is not None: + out["convergence"] = Q.read_conv(conv) + if (d / "run.json").exists(): + out["run"] = json.loads((d / "run.json").read_text()) + return out + + +# ---------------------------------------------------------------------------------------------------------------- validator +def _manifest_qc(m: dict) -> Q.QCReport: + r = Q.QCReport("manifest") + for k, t in MANIFEST_REQUIRED.items(): + if k not in m or m[k] in (None, "", {}): + r.error(f"manifest field {k!r} missing") + elif not isinstance(m[k], t): + r.error(f"manifest field {k!r} must be a {t.__name__}") + c = m.get("contributor") or {} + if isinstance(c, dict) and not (c.get("name") and c.get("affiliation")): + r.error("contributor needs name and affiliation") + lic = LICENCES.get(str(m.get("licence", "")).strip().lower()) + if lic is None: + r.error(f"licence {m.get('licence')!r} not accepted: data contributions must be CC-BY-4.0 or CC0-1.0") + r.info["licence"] = lic + solver = m.get("solver") or {} + if isinstance(solver, dict) and not solver.get("name"): + r.error("solver.name missing") + units = m.get("units") or {} + cap = str(units.get("capacitance", "")).strip() if isinstance(units, dict) else "" + try: + Q.to_fF(1.0, cap) + except ValueError: + r.error(f"units.capacitance {cap!r} not one of {sorted(Q.TO_FF)} (or 'pF*1e15')") + lm = m.get("layer_map") or {} + if isinstance(lm, dict) and not (lm.get("ground") and lm.get("conductor")): + r.error("layer_map needs ground and conductor layer lists, e.g. {ground: [[1, 0]], conductor: [[1, 10]]}") + return r + + +def validate_capacitance_contribution( + path, + reference="auto", + check_prior: bool = False, + threads: int = 2, + report_path=None, + revision: str | None = None, +) -> Q.QCReport: + """Validate a contribution directory (``PLAN_DATASET_HF.md`` §4.2). Returns a ``QCReport`` with one child per design. + + reference: the dataset's designs (DataFrame with ``design_id``, ``geom_hash``, ``split``) for the duplicate check; + ``"auto"`` reads them with ``PlanarCapacitanceDB`` (a warning when the dataset is not reachable), None skips it. + check_prior: also compare every label with ``optimized_physics_prior`` (needs ``[ml]``; seconds per design; report only). + report_path: also write the markdown report there.""" + root = Path(path) + rep = Q.QCReport(f"contribution {root.name}") + try: + m = load_manifest(root) + rows = read_designs(root) + except (FileNotFoundError, ValueError) as e: + rep.error(str(e)) + return _finish(rep, report_path) + except Exception as e: # noqa: BLE001 (YAML / CSV syntax) + rep.error(f"cannot parse the manifest or designs.csv: {e}") + return _finish(rep, report_path) + rep.extend(_manifest_qc(m), "manifest") + _, fixes = sanitized_manifest(m) + rep.fixes += fixes + _sanitized_designs_csv(rows, rep.fixes) + st = m.get("stack") if isinstance(m.get("stack"), dict) else {} + freq = (m.get("setup") or {}).get("freq_GHz") if isinstance(m.get("setup"), dict) else None + rep.extend(Q.stack_qc(st, freq), "stack") + if not rows: + rep.error("designs.csv has no rows") + missing_cols = [c for c in ("design", "gds", "net_order") if rows and c not in rows[0]] + if missing_cols: + rep.error(f"designs.csv misses columns {missing_cols} (template columns: {', '.join(DESIGN_COLUMNS)})") + return _finish(rep, report_path) + names = [r["design"] for r in rows] + dup_names = sorted({n for n in names if names.count(n) > 1}) + if dup_names: + rep.error(f"design names repeated in designs.csv: {dup_names[:5]}") + unit = str((m.get("units") or {}).get("capacitance", "fF")) + layer_map = m.get("layer_map") or Q.DEFAULT_LAYERS + gname = str(m.get("ground_net_name") or Q.GROUND) + hashes = {} + for row in rows: + child = _validate_design(root, row, unit, layer_map, gname, check_prior, threads) + rep.children.append(child) + hashes[row["design"]] = child.info.get("geom_hash") + if isinstance(reference, str) and reference == "auto": + try: + reference = Q.reference_hashes(revision=revision) + except Exception as e: # noqa: BLE001 + rep.warn(f"dataset not reachable for the duplicate check ({type(e).__name__}: {e}); maintainers rerun it") + reference = None + rep.extend(Q.duplicate_qc(hashes, reference), "duplicates") + rep.info.update( + designs=len(rows), + designs_ok=sum(c.ok for c in rep.children), + simulations=sum(c.info.get("simulations", 0) for c in rep.children), + family=m.get("family"), + licence=rep.info.get("licence"), + ) + return _finish(rep, report_path) + + +def _finish(rep: Q.QCReport, report_path) -> Q.QCReport: + if report_path is not None: + Path(report_path).write_text(rep.to_markdown("Validation report")) + return rep + + +def _validate_design(root: Path, row: dict, unit, layer_map, gname, check_prior, threads) -> Q.QCReport: + d = row["design"] + r = Q.QCReport(d) + if not re.fullmatch(r"[A-Za-z0-9._-]+", d or ""): + r.error(f"design name {d!r}: use letters, digits, '.', '_' or '-'") + return r + order = parse_net_order(row.get("net_order", "")) + order = [Q.GROUND if x == gname else x for x in order] + if not order: + r.error("net_order is empty") + return r + gds = row.get("gds") or f"gds/{d}.gds" + gp = root / gds if not _ABS.match(gds) else root / "gds" / Path(gds).name + if not gp.exists(): + r.error(f"GDS {gds} not found") + return r + nets = None + if (root / "nets" / f"{d}.json").exists(): + nets = json.loads((root / "nets" / f"{d}.json").read_text()) + g = Q.gds_qc(gp, layer_map, nets, subject="gds") + r.extend(g, "gds") + if "n_conductors" in g.info: + r.extend(Q.conductor_count_qc(g.info["n_conductors"], order), "nets") + if nets and [Q.GROUND, *nets] != order: + r.error(f"net_order {order} differs from the nets map order {[Q.GROUND, *nets]}") + sims = sorted(p for p in (root / "sims" / d).glob("*") if p.is_dir()) if (root / "sims" / d).exists() else [] + r.info["simulations"] = len(sims) + if not sims and str(row.get("unlabelled", "")).lower() not in ("1", "true", "yes"): + r.error( + f"no simulation under sims/{d}// (declare the design unlabelled=true to contribute geometry only)" + ) + for s in sims: + try: + sim = read_sim(s, unit) + except Exception as e: # noqa: BLE001 + r.error(f"{s.name}: cannot read the matrix ({e})") + continue + sim_names = [Q.GROUND if x == gname else x for x in sim["names"]] + lq = Q.label_qc( + sim["C"], + sim_names, + net_order=order, + unit=sim["unit"], + passes=sim["passes"], + convergence=sim["convergence"], + flagged_zero=_flagged(row), + subject=s.name, + ) + mat = lq.info.pop("matrix_fF", None) + r.extend(lq, f"sim {s.name}") + if sim.get("run"): + fx: list[str] = [] + _scrub(sim["run"], f"sims/{d}/{s.name}/run.json", fx) + r.fixes += fx + if check_prior and lq.ok and mat is not None: + r.extend(Q.prior_sanity(mat, order, gp, layer_map, threads=threads), f"sim {s.name}") + return r + + +def _flagged(row: dict) -> list[tuple[str, str]]: + s = row.get("zero_entries", "") + return [tuple(p.split("-", 1)) for p in re.split(r"[;\s]+", s) if "-" in p] + + +# ---------------------------------------------------------------------------------------------------------------- data PR +def _upload_files(root: Path) -> list[Path]: + files = [] + for top in UPLOAD_DIRS: + if (root / top).exists(): + files += [p for p in sorted((root / top).rglob("*")) if p.is_file() and not p.name.startswith(".")] + return files + + +def contribute_capacitance( + path, + repo_id: str = REPO_ID, + dry_run: bool = False, + org: str | None = None, + batch: str | None = None, + reference="auto", + check_prior: bool = False, + api=None, + token: str | None = None, +) -> dict: + """Validate ``path`` and open a pull request on the dataset ``repo_id`` adding ``contrib/-/`` (manifest, + designs, GDS, simulations, ``validation_report.md``, ``submission.json`` with the ``.env`` contributor block). + + A contribution with errors is refused (``ValueError``). dry_run: validate and return the planned files without any + network call. Returns ``{"ok", "pr_url", "folder", "files", "report"}``.""" + from huggingface_hub import CommitOperationAdd + + root = Path(path) + rep = validate_capacitance_contribution(root, reference=reference, check_prior=check_prior) + if not rep.ok: + raise ValueError("the contribution failed validation:\n- " + "\n- ".join(rep.all_errors()[:20])) + m = load_manifest(root) + org = _slug(org or m.get("org") or (m.get("contributor") or {}).get("affiliation") or "community") + batch = _slug(batch or m.get("batch") or time.strftime("%Y%m%d")) + folder = f"contrib/{org}-{batch}" + man, _ = sanitized_manifest(m) + fx: list[str] = [] + designs_csv = _sanitized_designs_csv(read_designs(root), fx) + try: + sub = submitter_record() + except Exception as e: # noqa: BLE001 + sub = {"note": f".env contributor block not read: {e}"} + md = rep.to_markdown(f"Validation report: {folder}") + md += "\n## Submitted by (.env)\n\n" + "\n".join(f"- {k}: {v}" for k, v in sub.items() if v) + "\n" + yaml = _yaml() + blobs = { + "manifest.yaml": yaml.safe_dump(man, sort_keys=False).encode(), + "designs.csv": designs_csv.encode(), + "validation_report.md": md.encode(), + "submission.json": json.dumps( + {"submitted_by": sub, "created": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "validator": _version()}, indent=1 + ).encode(), + } + ops = [CommitOperationAdd(path_in_repo=f"{folder}/{k}", path_or_fileobj=v) for k, v in blobs.items()] + for p in _upload_files(root): + rel = p.relative_to(root).as_posix() + if p.name == "run.json": + fxr: list[str] = [] + data = json.dumps(_scrub(json.loads(p.read_text()), rel, fxr), indent=1).encode() + ops.append(CommitOperationAdd(path_in_repo=f"{folder}/{rel}", path_or_fileobj=data)) + else: + ops.append(CommitOperationAdd(path_in_repo=f"{folder}/{rel}", path_or_fileobj=str(p))) + files = [o.path_in_repo for o in ops] + out = {"ok": True, "folder": folder, "files": files, "report": md, "pr_url": None, "repo_id": repo_id} + if dry_run: + return out + info = _api(api, token).create_commit( + repo_id=repo_id, + repo_type="dataset", + operations=ops, + commit_message=f"Contribution {org}-{batch}: {rep.info.get('designs')} designs ({m.get('family')})", + commit_description=md[:60000], + create_pr=True, + ) + out["pr_url"] = getattr(info, "pr_url", None) or str(info) + return out + + +def _version() -> str: + try: + from squadds import __version__ + + return f"squadds {__version__}" + except Exception: # noqa: BLE001 + return "squadds" + + +# ---------------------------------------------------------------------------------------------------------------- models +def _model_meta(root: Path) -> dict: + for n in MODEL_META_FILES: + p = root / n + if p.exists(): + return _yaml().safe_load(p.read_text()) if p.suffix == ".yaml" else json.loads(p.read_text()) + return {} + + +def _load_contributed(root: Path, meta: dict, paths: list[Path]): + base = meta.get("base") or {} + if base.get("name") in ("flagship", "fast", "paper"): + from .models import load_model + + return load_model(base["name"], path=root) + from .train import trained_model + + return trained_model(paths, name=_slug(meta.get("name", "contributed")) or "contributed", title=meta.get("title")) + + +def validate_model( + model_repo_id: str, + revision: str | None = None, + local_dir=None, + metadata: dict | None = None, + val_data=None, + threads: int = 2, + api=None, + token: str | None = None, + loader=None, +) -> tuple[Q.QCReport, dict]: + """Validate a model repository for the model zoo. Returns (report, zoo entry). + + The repository holds ``*.pt`` checkpoints (``squadds-ml train`` run dirs or ``model.pt`` files) and ``squadds_model.yaml`` + with ``name``, ``title``, ``licence``, ``contributor``, ``training_data`` (``sha256``, ``split_used``, ``description``) and + ``val_score`` (``median_pct``, ``mae_fF``, ``rmse_fF``, ``layouts``, ``seconds`` or ``seconds_per_layout``, ``machine``, + ``threads``); ``metadata`` + overrides the file. val_data: a validation shard dir: the score is then computed here with ``benchmark.score`` and replaces + the self-reported one. local_dir: a local copy of the repository (no download).""" + from .models import sha256_file + + rep = Q.QCReport(f"model {model_repo_id}@{revision or 'main'}") + hf = None + if local_dir is None: + hf = _api(api, token) + sha = hf.repo_info(model_repo_id, revision=revision).sha + local_dir = hf.snapshot_download(repo_id=model_repo_id, revision=sha) + revision = sha + elif not (revision and re.fullmatch(r"[0-9a-f]{40}", str(revision))): + rep.warn(f"revision {revision!r} is not a full commit sha: the zoo entry must pin one") + root = Path(local_dir) + meta = {**_model_meta(root), **(metadata or {})} + for k in MODEL_REQUIRED: + if not meta.get(k): + rep.error(f"model metadata field {k!r} missing (squadds_model.yaml)") + lic = str(meta.get("licence", "")).strip() + if lic and not re.fullmatch(r"[A-Za-z0-9.+-]+", lic): + rep.error(f"licence {lic!r} is not an SPDX identifier") + td = meta.get("training_data") or {} + if not td.get("sha256"): + rep.error("training_data.sha256 missing (sha256 of the training shards / model_input used)") + split_used = str(td.get("split_used", "")).lower() + if not split_used: + rep.error("training_data.split_used missing (train | train+val | all | custom)") + test_eligible = split_used == "train" + if "test" in split_used or split_used == "all": + rep.warn( + "trained on test layouts: the model is listed without any test score (not eligible for maintainer scoring)" + ) + paths = sorted(p for p in root.rglob("*.pt") if not any(x.startswith(".") for x in p.relative_to(root).parts)) + if not paths: + rep.error("no *.pt checkpoint in the repository") + files = [{"path": p.relative_to(root).as_posix(), "sha256": sha256_file(p)} for p in paths] + model = None + if paths: + try: + model = (loader or _load_contributed)(root, meta, paths) + rep.info["arm"] = (getattr(model, "entry", {}) or {}).get("arm") + except Exception as e: # noqa: BLE001 + rep.error(f"checkpoints do not load: {type(e).__name__}: {e}") + val = dict(meta.get("val_score") or {}) + if val_data is not None and model is not None: + from .benchmark import score + + s = score(model, val_data, split="val", threads=threads) + h = s.headline() + computed = { + "median_pct": h["median_pct"], + "mae_fF": h["mae_fF"], + "rmse_fF": h["rmse_fF"], + "layouts": h["layouts"], + "seconds": s.timing.get("seconds"), + "machine": s.timing.get("machine"), + "threads": s.timing.get("threads"), + "split": "val", + "source": "computed by contribute_model", + } + if val and val.get("median_pct") is not None and abs(float(val["median_pct"]) - h["median_pct"]) > 1e-3: + rep.warn( + f"self-reported val median {val['median_pct']} % differs from the computed {h['median_pct']:.4f} %" + ) + val = computed + elif val: + val.setdefault("source", "self-reported") + rep.warn("validation score self-reported (pass val_data to compute it here)") + if str(val.get("split", "val")).lower() == "test": + rep.error("val_score is a test score: test scores are maintainer-run only, report the validation split") + miss = [k for k in VAL_REQUIRED if val.get(k) in (None, "")] + if all(val.get(k) in (None, "") for k in VAL_TIME): + miss.append(" or ".join(VAL_TIME)) + if meta.get("val_score") is not None or val_data is not None: + if miss: + rep.error(f"val_score misses {miss} (median % with MAE and RMSE in fF, plus time, machine and threads)") + rep.info.update(files=len(files), val_median_pct=val.get("median_pct"), val_mae_fF=val.get("mae_fF")) + entry = { + "id": _slug(meta.get("name", model_repo_id.split("/")[-1])), + "repo_id": model_repo_id, + "revision": revision, + "title": meta.get("title"), + "arm": rep.info.get("arm"), + "base": meta.get("base"), + "licence": lic or None, + "contributor": meta.get("contributor"), + "files": files, + "training_data": td, + "val_score": val, + "test_eligible": test_eligible, + "validated": {"date": time.strftime("%Y-%m-%d"), "by": _version()}, + } + return rep, entry + + +def contribute_model( + model_repo_id: str, + revision: str | None = None, + registry_repo: str = REPO_ID, + metadata: dict | None = None, + val_data=None, + dry_run: bool = False, + local_dir=None, + threads: int = 2, + api=None, + token: str | None = None, + loader=None, +) -> dict: + """Validate a model repository (``validate_model``) and open a pull request on ``registry_repo`` adding its entry to + ``model_zoo.yaml`` plus ``model_zoo//validation_report.md``. A model with errors is refused (``ValueError``). + Returns ``{"ok", "pr_url", "entry", "report", "files"}``.""" + from huggingface_hub import CommitOperationAdd + + hf = None if (dry_run and local_dir is not None and api is None) else _api(api, token) + rep, entry = validate_model( + model_repo_id, revision, local_dir, metadata, val_data, threads, api=hf, token=token, loader=loader + ) + if not rep.ok: + raise ValueError("the model failed validation:\n- " + "\n- ".join(rep.all_errors()[:20])) + zoo = {"version": 1, "models": []} + if hf is not None: + try: + p = hf.hf_hub_download(repo_id=registry_repo, repo_type="dataset", filename=ZOO_FILE) + zoo = _yaml().safe_load(Path(p).read_text()) or zoo + except Exception as e: # noqa: BLE001 + if "404" not in str(e) and "EntryNotFound" not in type(e).__name__ and "not found" not in str(e).lower(): + raise + zoo.setdefault("models", []) + if any(x.get("repo_id") == entry["repo_id"] and x.get("revision") == entry["revision"] for x in zoo["models"]): + raise ValueError(f"{entry['repo_id']}@{entry['revision']} is already in {ZOO_FILE}") + zoo["models"].append(entry) + md = rep.to_markdown(f"Model validation report: {model_repo_id}@{entry['revision']}") + ops = [ + CommitOperationAdd(path_in_repo=ZOO_FILE, path_or_fileobj=_yaml().safe_dump(zoo, sort_keys=False).encode()), + CommitOperationAdd(path_in_repo=f"model_zoo/{entry['id']}/validation_report.md", path_or_fileobj=md.encode()), + ] + out = {"ok": True, "entry": entry, "report": md, "files": [o.path_in_repo for o in ops], "pr_url": None} + if dry_run: + return out + info = hf.create_commit( + repo_id=registry_repo, + repo_type="dataset", + operations=ops, + commit_message=f"Model zoo: add {entry['id']} ({model_repo_id}@{str(entry['revision'])[:8]})", + commit_description=md[:60000], + create_pr=True, + ) + out["pr_url"] = getattr(info, "pr_url", None) or str(info) + return out diff --git a/src/squadds/ml/capacitance/dataset.py b/src/squadds/ml/capacitance/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..74b992d18e7d3671f1945cbf070dbcfac9fa7818 --- /dev/null +++ b/src/squadds/ml/capacitance/dataset.py @@ -0,0 +1,323 @@ +"""Query the ``SQuADDS/SQuADDS_PlanarCapacitance`` dataset (raw and processed tables) with pandas / pyarrow only. + +No ``[ml]`` dependency: this module needs pandas, pyarrow and huggingface_hub (all core SQuADDS dependencies), so +``from squadds.ml.capacitance.dataset import PlanarCapacitanceDB`` works on a plain ``pip install squadds``. + + db = PlanarCapacitanceDB() # HF repo (private: needs a token with access) + db = PlanarCapacitanceDB(local_dir="/path/to/SQuADDS_PlanarCapacitance") # or env SQUADDS_PLANAR_CAP_DATA + ids = db.designs(family="interdigital", split="val").design_id[:5] + db.labels(ids) # {design_id: N x N Maxwell matrix (pandas DataFrame, fF, ground first)} + +Tables are read file by file with pyarrow column / row filters, so a query never loads more of the dataset than it asks for. +""" + +from __future__ import annotations + +import fnmatch +import json +import os +from pathlib import Path + +import numpy as np +import pandas as pd + +from squadds.datasets.planar_capacitance_schema import ( + GLOBAL_FEATURES, + NODE_FEATURES, + REPO_ID, + TABLES, +) + +ENV_VAR = "SQUADDS_PLANAR_CAP_DATA" +# pinned HF commit of REPO_ID (2026-11-03: README/CHANGELOG only, synthetic-dataset link + known limitation); revision="main" for the latest +DATASET_REVISION = "13d46953620b06958d952aff0736ba8af881fbb5" + +TABLE_GLOBS = { + "designs": "data/designs/*.parquet", + "layouts": "data/layouts/*.parquet", + "simulations": "data/simulations/*.parquet", + "labels": "data/labels/*.parquet", + "label_passes": "data/label_passes/*.parquet", + "geometric_embedding_nodes": "data/geometric_embedding/nodes-*.parquet", + "geometric_embedding_edges": "data/geometric_embedding/edges-*.parquet", + "geometric_embedding_globals": "data/geometric_embedding/globals-*.parquet", + "coarse_physics_prior": "data/coarse_physics_prior/*.parquet", + "optimized_physics_prior": "data/optimized_physics_prior/*.parquet", + "model_input": "data/model_input/*.parquet", +} +DESIGN_COLUMNS = [c for c, _ in TABLES["designs"] if c != "params"] +NEAREST_FEATURES = ( + [*GLOBAL_FEATURES, "log_n_conductors"] + [f"mean_{f}" for f in NODE_FEATURES] + [f"max_{f}" for f in NODE_FEATURES] +) + + +def long_to_matrix( + df: pd.DataFrame, value: str, i: str = "a_idx", j: str = "b_idx", a: str = "net_a", b: str = "net_b" +): + """Symmetric N x N DataFrame (index = columns = net names, in index order) from long-format entries ``i <= j``. + + A table that stores mutual entries only (no diagonal) gets the Maxwell diagonal from closure: + ``C_ii = -sum_{j != i} C_ij`` (the ground net is one of the nets, so this is exact for a closed system). + """ + n = int(max(df[i].max(), df[j].max())) + 1 + names = [None] * n + for ii, jj, na, nb in zip(df[i], df[j], df[a], df[b]): + names[int(ii)], names[int(jj)] = na, nb + C = np.full((n, n), np.nan) + ii, jj, v = df[i].to_numpy(int), df[j].to_numpy(int), df[value].to_numpy(float) + C[ii, jj] = v + C[jj, ii] = v + diag = np.isnan(np.diag(C)) + if diag.any(): + off = np.where(np.eye(n, dtype=bool), 0.0, np.nan_to_num(C)) + C[diag, diag] = -off.sum(1)[diag] + return pd.DataFrame(C, index=names, columns=names) + + +class PlanarCapacitanceDB: + """Read access to the planar capacitance dataset. + + Args: + revision: HF revision (commit sha, tag or branch) of ``repo_id``; default ``DATASET_REVISION`` (the pinned commit), + ``"main"`` for the latest; ignored with a local directory. + local_dir: a local copy of the repo (same layout as on HF). Default: env ``SQUADDS_PLANAR_CAP_DATA``, else HF. + repo_id: HF dataset repo (default ``SQuADDS/SQuADDS_PlanarCapacitance``). + token: HF token for the private repo (default: the logged-in token). + """ + + def __init__(self, revision: str | None = None, local_dir=None, repo_id: str = REPO_ID, token: str | None = None): + local_dir = local_dir or os.environ.get(ENV_VAR) + self.local_dir = Path(local_dir).expanduser() if local_dir else None + if self.local_dir is not None and not self.local_dir.is_dir(): + raise FileNotFoundError(f"planar capacitance data directory not found: {self.local_dir}") + self.repo_id, self.revision, self.token = repo_id, revision or DATASET_REVISION, token + self._repo_files: list[str] | None = None + self._nearest_cache: dict = {} + + def __repr__(self) -> str: + where = str(self.local_dir) if self.local_dir else f"hf://datasets/{self.repo_id}@{self.revision}" + return f"PlanarCapacitanceDB({where})" + + # ------------------------------------------------------------------------------------------------ files + def _list_repo_files(self) -> list[str]: + if self._repo_files is None: + from huggingface_hub import HfApi + + self._repo_files = HfApi(token=self.token).list_repo_files( + self.repo_id, repo_type="dataset", revision=self.revision + ) + return self._repo_files + + def _download(self, filename: str) -> Path: + from huggingface_hub import hf_hub_download + + return Path( + hf_hub_download(self.repo_id, filename, repo_type="dataset", revision=self.revision, token=self.token) + ) + + def tables(self) -> dict[str, list[str]]: + """Available tables -> their files (repo-relative paths); tables with no file are left out.""" + if self.local_dir is not None: + rel = [p.relative_to(self.local_dir).as_posix() for p in self.local_dir.glob("data/**/*.parquet")] + else: + rel = self._list_repo_files() + out = {t: sorted(f for f in rel if fnmatch.fnmatch(f, g)) for t, g in TABLE_GLOBS.items()} + return {t: f for t, f in out.items() if f} + + def files(self, table: str) -> list[Path]: + if table not in TABLE_GLOBS: + raise KeyError(f"unknown table {table!r}; tables: {sorted(TABLE_GLOBS)}") + if self.local_dir is not None: + return sorted(self.local_dir.glob(TABLE_GLOBS[table])) + return [self._download(f) for f in self.tables().get(table, [])] + + def read(self, table: str, columns=None, design_ids=None, filters=None) -> pd.DataFrame: + """Rows of one table (all its split files) with optional column selection and pyarrow row filters + (``[("split", "=", "val")]``); ``design_ids`` adds ``design_id in design_ids``.""" + import pyarrow.parquet as pq + + flt = list(filters or []) + if design_ids is not None: + ids = list(dict.fromkeys(design_ids)) + if not ids: + return pd.DataFrame(columns=columns or [c for c, _ in TABLES.get(table, ())]) + flt.append(("design_id", "in", ids)) + parts = [] + for f in self.files(table): + names = set(pq.read_schema(f).names) + if any(c not in names for c, _, _ in flt): + continue + cols = [c for c in columns if c in names] if columns else None + t = pq.read_table(f, columns=cols, filters=flt or None) + if t.num_rows: + parts.append(t.to_pandas()) + if not parts: + return pd.DataFrame(columns=columns or [c for c, _ in TABLES.get(table, ())]) + return pd.concat(parts, ignore_index=True) + + # ------------------------------------------------------------------------------------------------ raw tables + def designs( + self, + family=None, + split=None, + n_conductors=None, + collection=None, + config=None, + columns=None, + design_ids=None, + ) -> pd.DataFrame: + """Design rows (without the ``params`` JSON unless asked for in ``columns``). ``family`` matches ``family``, + ``paper_family`` or ``model_family``; ``config`` is the SQuADDS config name; each filter takes a value or a list.""" + + def as_list(v): + return [v] if isinstance(v, (str, int, np.integer)) else list(v) + + flt = [] + for col, v in (("split", split), ("collection", collection), ("squadds_config", config)): + if v is not None: + flt.append((col, "in", as_list(v))) + df = self.read("designs", columns=columns or DESIGN_COLUMNS, design_ids=design_ids, filters=flt) + if family is not None: + fam = set(as_list(family)) + mask = np.zeros(len(df), bool) + for col in ("family", "paper_family", "model_family"): + if col in df: + mask |= df[col].isin(fam).to_numpy() + df = df[mask] + if n_conductors is not None: + df = df[df["n_conductors"].isin([float(x) for x in as_list(n_conductors)])] + return df.reset_index(drop=True) + + def params(self, design_ids) -> dict[str, dict]: + """Generator / component options of each design (parsed ``params`` JSON).""" + df = self.read("designs", columns=["design_id", "params"], design_ids=design_ids) + return {d: json.loads(p) if p else {} for d, p in zip(df.design_id, df.params)} + + def simulations(self, design_ids=None, role: str | None = None, columns=None) -> pd.DataFrame: + flt = [("role", "=", role)] if role else None + return self.read("simulations", columns=columns, design_ids=design_ids, filters=flt) + + def label_passes(self, design_ids, columns=None) -> pd.DataFrame: + return self.read("label_passes", columns=columns, design_ids=design_ids) + + def labels(self, design_ids, role: str | None = "reference") -> dict[str, pd.DataFrame]: + """Final Maxwell matrices (fF, ground first) keyed by design_id (``role`` = simulation role, default the reference + Q3D solve); ``role=None`` returns every simulation keyed by simulation_id. Designs without a public label (test + split) are absent.""" + sims = self.simulations(design_ids, role=role, columns=["simulation_id", "design_id", "role"]) + if sims.empty: + return {} + lab = self.read( + "labels", + columns=["simulation_id", "design_id", "net_a", "net_b", "a_idx", "b_idx", "C_fF"], + filters=[("simulation_id", "in", sims.simulation_id.tolist())], + ) + key = "design_id" if role else "simulation_id" + return {k: long_to_matrix(g, "C_fF") for k, g in lab.groupby(key, sort=False)} + + def gds_path(self, design_id: str) -> Path: + """Local path of the design's GDS (downloaded from the HF repo when needed).""" + d = self.designs(design_ids=[design_id], columns=["design_id", "layout_id"]) + if d.empty: + raise KeyError(f"unknown design_id {design_id!r}") + lay = self.read("layouts", columns=["layout_id", "path"], filters=[("layout_id", "=", d.layout_id.iloc[0])]) + if lay.empty: + raise KeyError(f"no layout row for {design_id!r} ({d.layout_id.iloc[0]})") + rel = lay.path.iloc[0] + return self.local_dir / rel if self.local_dir is not None else self._download(rel) + + # ------------------------------------------------------------------------------------------------ processed tables + def _prior(self, table: str, design_ids, value: str) -> dict[str, pd.DataFrame]: + df = self.read(table, design_ids=design_ids) + return {k: long_to_matrix(g, value, "i", "j") for k, g in df.groupby("design_id", sort=False)} + + def coarse_physics_prior(self, design_ids, value: str = "C_fF") -> dict[str, pd.DataFrame]: + """Single thin-film MoM solve at p = 0.375 as N x N Maxwell matrices (fF, ground first).""" + return self._prior("coarse_physics_prior", design_ids, value) + + def optimized_physics_prior(self, design_ids, value: str = "C_R_fF") -> dict[str, pd.DataFrame]: + """C^R = R(1.5, 3) on the corrected stack as N x N Maxwell matrices (``value="mutual_1p5_fF"`` / ``"mutual_3_fF"`` + for the two solves, diagonal from closure).""" + return self._prior("optimized_physics_prior", design_ids, value) + + def model_input(self, design_ids) -> pd.DataFrame: + return self.read("model_input", design_ids=design_ids) + + def embedding(self, design_ids) -> dict[str, dict]: + """``planar-capacitance-graph-v1`` per design: ``nodes`` (one row per conductor, ground = node 0), ``edges`` (pairs + i < j) and ``globals`` (dict).""" + nodes = self.read("geometric_embedding_nodes", design_ids=design_ids) + edges = self.read("geometric_embedding_edges", design_ids=design_ids) + glob = self.read("geometric_embedding_globals", design_ids=design_ids) + out = {} + for d, g in glob.groupby("design_id", sort=False): + out[d] = { + "nodes": nodes[nodes.design_id == d].sort_values("node_idx").reset_index(drop=True), + "edges": edges[edges.design_id == d].sort_values(["i", "j"]).reset_index(drop=True), + "globals": g.iloc[0].to_dict(), + } + return out + + # ------------------------------------------------------------------------------------------------ nearest neighbours + def pooled_embedding(self, design_ids=None, family=None, split=None) -> pd.DataFrame: + """One vector per design (index design_id): the 4 global features, log N, and the mean and the max of each of the + 61 node features over the signal conductors (ground node excluded); 127 values, not standardized.""" + if design_ids is None and (family is not None or split is not None): + design_ids = self.designs( + family=family, split=split, columns=["design_id", "family", "paper_family", "model_family", "split"] + ).design_id + cols = ["design_id", "node_idx", *NODE_FEATURES] + nodes = self.read("geometric_embedding_nodes", columns=cols, design_ids=design_ids) + glob = ( + self.read( + "geometric_embedding_globals", + columns=["design_id", "n_conductors", *GLOBAL_FEATURES], + design_ids=design_ids, + ) + .drop_duplicates("design_id") + .set_index("design_id") + ) + sig = nodes[nodes.node_idx > 0].drop(columns="node_idx").groupby("design_id") + mean = sig.mean().add_prefix("mean_") + mx = sig.max().add_prefix("max_") + g = glob[list(GLOBAL_FEATURES)].astype(float) + g["log_n_conductors"] = np.log(glob["n_conductors"].astype(float)) + out = g.join(mean, how="inner").join(mx, how="inner") + return out[NEAREST_FEATURES] + + def nearest(self, query, k: int = 5, family=None, split=None) -> pd.DataFrame: + """The k designs closest to ``query`` (a design_id, or a 127-value vector in ``pooled_embedding`` order) in the + pooled embedding space, standardized per feature over the candidate set (Euclidean distance). + + Candidates: designs of ``family`` (default: the query design's ``model_family``; all designs when the query is a + vector and no family is given) and ``split``. This is a simple geometric similarity, not a capacitance distance. + """ + qvec = None + if isinstance(query, str): + if family is None: + d = self.designs(design_ids=[query], columns=["design_id", "model_family"]) + if d.empty: + raise KeyError(f"unknown design_id {query!r}") + family = d.model_family.iloc[0] + else: + qvec = np.asarray(query, float).ravel() + if qvec.size != len(NEAREST_FEATURES): + raise ValueError(f"query vector must have {len(NEAREST_FEATURES)} values (pooled_embedding order)") + key = (repr(family), repr(split)) + if key not in self._nearest_cache: + self._nearest_cache[key] = self.pooled_embedding(family=family, split=split) + P = self._nearest_cache[key] + if isinstance(query, str): + if query not in P.index: + P = pd.concat([P, self.pooled_embedding(design_ids=[query])]) + qvec = P.loc[query].to_numpy(float) + X = P.to_numpy(float) + mu, sd = np.nanmean(X, 0), np.nanstd(X, 0) + sd[~(sd > 0)] = 1.0 + dist = np.sqrt(np.nansum(((X - mu) / sd - (qvec - mu) / sd) ** 2, 1)) + res = pd.DataFrame({"design_id": P.index, "distance": dist}) + if isinstance(query, str): + res = res[res.design_id != query] + res = res.nsmallest(k, "distance").reset_index(drop=True) + meta = self.designs(design_ids=res.design_id, columns=["design_id", "collection", "model_family", "split"]) + return res.merge(meta, on="design_id", how="left") diff --git a/src/squadds/ml/capacitance/manifest.json b/src/squadds/ml/capacitance/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..61ac54df5408cd68c6bc4a9a8261d00fce990808 --- /dev/null +++ b/src/squadds/ml/capacitance/manifest.json @@ -0,0 +1,292 @@ +{ + "manifest_version": 2, + "source": "tl-squadds deploy/registry.yaml (version 2), flagship_tiers accurate/fast (served as models flagship/fast), paper_arms model, paper_hub.prior_stacks corrected", + "registry_version": 2, + "training_stack": { + "substrate": "Si (cryogenic)", + "eps_r": 11.45, + "thickness_um": 350.0, + "layers": { + "ground": [ + 1, + 0 + ], + "conductor": [ + 1, + 10 + ] + } + }, + "prior_stacks": { + "corrected": { + "title": "corrected prior with substrate far field", + "version": "v2m_sf_fc_dipfill_margin_slabfar", + "patches": [ + "priorv2m_sf" + ], + "mode": "exact_compiled", + "module_sha256": "1a0bdcb71500c7f11e63238afe531c18caabd5c9f6f7aaa73d9b7dcd0ad61f8c", + "farfield_sha256": "6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836", + "speed_package_sha256": "956f2b62c308ec1561bbc033716b52c24dc63a916b9373cc44090eb6514e5dde", + "value_changing_approved": "user 2026-10-17 (v2m, gnn_models.GNN); user 2026-10-20: adopted arm (b) of agents/farfield (substrate dipole for far pairs in different ground pockets; pre-declared rule met, agents/farfield/RESULTS.md; adoption agents/farfield/ADOPTION.md)", + "speed_approved": "user 2026-10-17 (gnn_models.GNN)", + "previous": "corrected_halfspace" + } + }, + "alpha": 0.49685219816506904, + "models": { + "flagship": { + "repo_id": "SQuADDS/PlanarCapacitance-flagship", + "revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc", + "training_layouts": 45771, + "title": "Flagship (~1 s): extrapolated physics R(1.5, 3) on the corrected prior + residual networks, compiled solver", + "paper_name": "Accurate", + "route": "Accurate", + "kind": "gnn", + "arm": "full_gnn", + "embedding": { + "far_k": 64, + "d_far_um": 100.0 + }, + "stack": "corrected", + "ppg": [ + 1.5, + 3.0 + ], + "summary": "Two thin-film method-of-moments solves (corrected prior with substrate far field, 1.5 and 3 panels per gap), Richardson-extrapolated, corrected by a 3-seed ensemble of the paper model's networks (89,858 parameters per seed, bounded residual) with a learned row-sum closure: the complete Maxwell matrix, self terms included. Networks retrained on all 45,771 on-stack Q3D layouts (2026-10-20, on the corrected prior with substrate far field).", + "reference": { + "recipe": "the paper's version of this model (same architecture and prior stack at inference; its networks were trained on the 35,354 TRAIN layouts only, on the uncorrected prior; retrained on the corrected prior, as here, they score validation 0.218 % (0.0774 / 0.0888 fF)). These held-out numbers belong to the paper's version, not to this release, whose networks were retrained on every labelled design, the paper's test split included", + "val": { + "median_pct": 0.229, + "mae_ff": 0.0674, + "rmse_ff": 0.0792 + }, + "test_infamily": { + "median_pct": 0.177, + "mae_ff": 0.0203, + "rmse_ff": 0.025 + }, + "test_zeroshot": { + "median_pct": 0.587, + "mae_ff": 1.092, + "rmse_ff": 1.152 + }, + "heldout_family": { + "median_pct": 0.408, + "mae_ff": 0.049, + "rmse_ff": 0.059 + } + }, + "own": { + "insample": { + "set": "in-sample, all 45,771 training layouts (TRAIN + VAL + the paper's test split; it was trained on them)", + "median_pct": 0.207, + "mae_ff": 0.0679, + "rmse_ff": 0.077 + } + }, + "b5": { + "median_pct": 1.05, + "mae_ff": 0.132, + "rmse_ff": 0.188 + }, + "b5_physics": { + "name": "physics alone C^R = R(1.5, 3)", + "median_pct": 1.765, + "mae_ff": 0.275, + "rmse_ff": 0.376 + }, + "time_space": "interdigital 0.47 s, xmon 0.91 s, 1-qubit lattice (N 15) 19.0 s, 16-conductor layout 9.9 s, 9-qubit lattice (N 67) 154 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s)", + "time_x86": "0.845 / 5.96 s in family, 1.75 / 18.1 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.99 s median (1.14 s on the 2026-10-20 re-run, Xeon E5-2640 v4)", + "checkpoints": [ + { + "name": "acc_v2m_sf_s0", + "path": "accurate/acc_v2m_sf_s0.pt", + "sha256": "cc69c5818f5028c26177159b88239116520abbb290743d6a6c091657e8dbf1c5", + "source": "data_local/flagship_v4/hpc/runs/acc_v2m_sf_s0/model.pt" + }, + { + "name": "acc_v2m_sf_s1", + "path": "accurate/acc_v2m_sf_s1.pt", + "sha256": "2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57", + "source": "data_local/flagship_v4/hpc/runs/acc_v2m_sf_s1/model.pt" + }, + { + "name": "acc_v2m_sf_s2", + "path": "accurate/acc_v2m_sf_s2.pt", + "sha256": "d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed", + "source": "data_local/flagship_v4/hpc/runs/acc_v2m_sf_s2/model.pt" + } + ] + }, + "fast": { + "repo_id": "SQuADDS/PlanarCapacitance-flagship", + "revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc", + "training_layouts": 45771, + "title": "Fast (~0.1 s): learned prior surrogate + residual networks, no field solve (trained component families only)", + "paper_name": "Fast", + "route": "Fast", + "kind": "gnn", + "arm": "full_gnn", + "embedding": { + "far_k": 64, + "d_far_um": 100.0 + }, + "stack": null, + "summary": "An improved release of the paper's fast model, same architecture: a learned surrogate (1.02M parameters) predicts the two uncorrected-prior solves at 1.5 and 3 panels per gap and residual networks correct them. The surrogate is trained on more generated layouts (the prior of every on-stack layout plus 432,697 generated layouts labelled by the prior alone, against 385,593 for the paper's) and the networks are retrained on every labelled design (all 45,771 on-stack layouts, the paper's test split included). No field solve: the time is the geometric embedding.", + "warning": "Use the fast model only for quick screening of the component families it was trained on (interdigital, paddle, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated and synthetic campaign layouts). On new designs of a trained family (B5) it was worse than the physics alone, 3.175 % (MAE 0.583 / RMSE 0.824 fF) against 1.765 % (0.275 / 0.376 fF), and the paper's version of it was worse than the physics alone on a held-out family too, 3.11 % (0.533 / 0.633 fF) against 1.55 % (0.166 / 0.205 fF). Use the flagship model for anything that matters.", + "reference": { + "recipe": "the paper's version of the fast model (surrogate t100_norm trained on 385,593 generated layouts + the TRAIN geometry; networks trained on the 35,354 TRAIN layouts only). These held-out numbers belong to the paper's version, not to this release, which was trained on the paper's test split too", + "val": { + "median_pct": 0.846, + "mae_ff": 0.491, + "rmse_ff": 0.549 + }, + "test_infamily": { + "median_pct": 0.63, + "mae_ff": 0.113, + "rmse_ff": 0.1414 + }, + "test_zeroshot": { + "median_pct": 3.576, + "mae_ff": 4.608, + "rmse_ff": 5.058 + }, + "heldout_family": { + "median_pct": 3.113, + "mae_ff": 0.533, + "rmse_ff": 0.633 + }, + "heldout_family_physics": { + "median_pct": 1.554, + "mae_ff": 0.166, + "rmse_ff": 0.205 + }, + "val_same_surrogate": { + "median_pct": 0.722, + "mae_ff": 0.387, + "rmse_ff": 0.436, + "note": "this release's surrogate recipe trained without the validation layouts (P6 SUR-ALL) + the paper's TRAIN-only networks, held out (agents/surcov_p6/RESULTS_P6.md)" + } + }, + "own": { + "insample": { + "set": "in-sample, all 45,771 training layouts (TRAIN + VAL + the paper's test split; it was trained on them)", + "median_pct": 0.671, + "mae_ff": 0.353, + "rmse_ff": 0.395 + } + }, + "b5": { + "median_pct": 3.175, + "mae_ff": 0.583, + "rmse_ff": 0.824 + }, + "b5_physics": { + "name": "physics alone C^R = R(1.5, 3) (worse than the physics: Fast is behind it here)", + "median_pct": 1.765, + "mae_ff": 0.275, + "rmse_ff": 0.376 + }, + "time_space": "interdigital 0.036 s, xmon 0.11 s, 1-qubit lattice (N 15) 0.82 s, 16-conductor layout 0.49 s, 9-qubit lattice (N 67) 3.9 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s)", + "time_x86": "0.091 / 0.274 s in family, 0.30 / 2.45 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.24 s median", + "checkpoints": [ + { + "name": "acc_v1_s0", + "path": "fast/acc_v1_s0.pt", + "sha256": "9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba", + "source": "data_local/flagship_v4/hpc/runs/acc_v1_s0/model.pt" + }, + { + "name": "acc_v1_s1", + "path": "fast/acc_v1_s1.pt", + "sha256": "f1ad2ca065dd650ccabcad73a3c6ad2ac1042f4f68bb828893bbdecc47411ffe", + "source": "data_local/flagship_v4/hpc/runs/acc_v1_s1/model.pt" + }, + { + "name": "acc_v1_s2", + "path": "fast/acc_v1_s2.pt", + "sha256": "8cbada211724df5cc05a7b4fdd232607de047b248a43993d3844bd68ff8060c4", + "source": "data_local/flagship_v4/hpc/runs/acc_v1_s2/model.pt" + } + ], + "learned_prior": { + "name": "sall_all_s0", + "checkpoint": { + "name": "sall_all_s0", + "path": "fast/sall_all_s0.pt", + "sha256": "132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac", + "source": "data_local/flagship_v4/hpc/sur/sall_all_s0/model.pt" + } + } + }, + "paper": { + "repo_id": "SQuADDS/PlanarCapacitance-paper", + "revision": "5d4e09487617f27c969e607dad04d902bf4134f5", + "training_layouts": 35354, + "title": "The model: extrapolated physics on the corrected prior + residual networks + closure, compiled solver", + "paper_name": "model (corrected prior, compiled solver)", + "route": "(d) good physics", + "kind": "gnn", + "arm": "full_gnn", + "stack": "corrected", + "ppg": [ + 1.5, + 3.0 + ], + "summary": "C^R = R(1.5, 3) of the corrected prior (two thin-film solves) corrected by the 3-seed network ensemble (89,858 parameters per seed, bounded residual +-0.2 in log) with a learned row-sum closure: the complete Maxwell matrix. Trained on 35,354 Q3D layouts of 13 families.", + "paper": { + "tables": [ + "tab:ladder-test", + "tab:routes (d)", + "tab:sota", + "tab:cohorts", + "tab:grid", + "tab:circuit" + ], + "val": { + "median_pct": 0.229, + "mae_ff": 0.0674, + "rmse_ff": 0.0792 + }, + "test_infamily": { + "median_pct": 0.177, + "mae_ff": 0.0203, + "rmse_ff": 0.025 + }, + "test_zeroshot": { + "median_pct": 0.587, + "mae_ff": 1.092, + "rmse_ff": 1.152 + }, + "heldout_family": { + "median_pct": 0.408, + "mae_ff": 0.049, + "rmse_ff": 0.059 + }, + "time": "0.845 / 5.96 s in family, 1.76 / 18.1 s zero-shot (test, x86, 2 CPUs); 1.16 / 6.3 s (GH200)" + }, + "checkpoints": [ + { + "name": "p2d_full_gnn_s0", + "path": "model/p2d_full_gnn_s0.pt", + "sha256": "fcb5db5d8237436d546aca0e7463a2f1d4f2e1b18757b2a35eff646c03f3bc5c", + "source": "data_local/geomfast/runs/p2d_full_gnn_s0/model.pt" + }, + { + "name": "p2d_full_gnn_s1", + "path": "model/p2d_full_gnn_s1.pt", + "sha256": "9aef64adfaf99cad35da891a2329d43eac46b2768cd133b5313085891a4fed92", + "source": "data_local/geomfast/runs/p2d_full_gnn_s1/model.pt" + }, + { + "name": "p2d_full_gnn_s2", + "path": "model/p2d_full_gnn_s2.pt", + "sha256": "357c16539967404b0a7eea514ef3ff3dc763c764da192b219d919cb01f697669", + "source": "data_local/geomfast/runs/p2d_full_gnn_s2/model.pt" + } + ] + } + }, + "default_model": "flagship" +} diff --git a/src/squadds/ml/capacitance/models.py b/src/squadds/ml/capacitance/models.py new file mode 100644 index 0000000000000000000000000000000000000000..8f1c83be09c4a275d1a16aec458a9a93a6bb51e2 --- /dev/null +++ b/src/squadds/ml/capacitance/models.py @@ -0,0 +1,210 @@ +"""Released planar-capacitance models: manifest, download (Hugging Face, pinned revision) and sha256 verification. + +Sources, in order: ``path=`` (a local bundle: the repository layout, e.g. ``/accurate/acc_v2m_sf_s0.pt``), the +environment variable ``SQUADDS_CAPML_MODELS`` (a directory holding one bundle per repository, named after it, e.g. +``$SQUADDS_CAPML_MODELS/PlanarCapacitance-flagship``), else ``huggingface_hub.hf_hub_download`` from the manifest's repository +at its pinned revision. Every file is checked against the sha256 in the package manifest; a mismatch is refused. +""" + +from __future__ import annotations + +import hashlib +import json +import os +from dataclasses import dataclass, field +from pathlib import Path + +from ._runtime import TRAIN_EPS_R + +ENV_MODELS = "SQUADDS_CAPML_MODELS" +MANIFEST = json.loads((Path(__file__).with_name("manifest.json")).read_text()) +_SHA_MEMO: dict = {} + + +class ModelIntegrityError(RuntimeError): + """A model file is missing or its sha256 differs from the package manifest.""" + + +class _Registry: + """The registry view the frozen stage (``_core.paper``) reads: one model as a ``paper_arms`` entry.""" + + def __init__(self, data: dict, root: Path, key: str): + self.data, self.root, self.path = data, Path(root), key + + def __getitem__(self, k): + return self.data[k] + + def eps_of(self, substrate) -> float: + if isinstance(substrate, (int, float)): + return float(substrate) + if str(substrate).lower().startswith("si"): + return TRAIN_EPS_R + return float(substrate) + + +def registry_view(arms: dict, root, key: str) -> _Registry: + data = { + "version": MANIFEST["registry_version"], + "paper_arms": arms, + "paper_hub": {"prior_stacks": MANIFEST["prior_stacks"], "default_arm": next(iter(arms), None)}, + } + return _Registry(data, root, key) + + +def sha256_file(p) -> str: + p = Path(p) + st = p.stat() + k = (str(p.resolve()), st.st_size, st.st_mtime_ns) + if k not in _SHA_MEMO: + h = hashlib.sha256() + with open(p, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + _SHA_MEMO[k] = h.hexdigest() + return _SHA_MEMO[k] + + +def model_files(entry: dict) -> list[tuple[str, str]]: + """(relative path, sha256) of every file a model needs.""" + out = [(c["path"], c["sha256"]) for c in entry.get("checkpoints") or []] + if entry.get("learned_prior"): + c = entry["learned_prior"]["checkpoint"] + out.append((c["path"], c["sha256"])) + return out + + +def list_models() -> list[dict]: + """Served models (``flagship``, ``fast``, ``paper``) with their numbers (median % with MAE / RMSE in fF) and warnings. + ``reference`` = the held-out numbers of the paper's version of the flagship / fast model (trained on the TRAIN split only), + not of the served model; ``own`` = the served model's in-sample fit; ``b5`` = its one never-seen check.""" + return [ + { + "model": name, + "default": name == MANIFEST["default_model"], + "title": e.get("title"), + "repo_id": e["repo_id"], + "revision": e["revision"], + "warning": e.get("warning"), + "reference": e.get("reference") or e.get("paper") or {}, + "own": e.get("own") or {}, + "b5": e.get("b5"), + "time_x86": e.get("time_x86") or (e.get("paper") or {}).get("time"), + } + for name, e in MANIFEST["models"].items() + ] + + +@dataclass +class CapacitanceModel: + """A verified local copy of one model.""" + + name: str + entry: dict + root: Path + repo_id: str + revision: str | None + sha256: list[str] = field(default_factory=list) + + @property + def key(self) -> str: + return self.name + + @property + def title(self) -> str: + return self.entry.get("title", self.key) + + @property + def warning(self) -> str | None: + return self.entry.get("warning") + + @property + def weights_sha256(self) -> list[str]: + return [c["sha256"] for c in self.entry["checkpoints"]] + + @property + def learned_prior_sha256(self) -> str | None: + lp = self.entry.get("learned_prior") + return lp["checkpoint"]["sha256"] if lp else None + + def registry(self) -> _Registry: + return registry_view({self.name: self.entry}, self.root, f"{self.repo_id}@{self.revision}:{self.root}") + + def __repr__(self) -> str: + return f"CapacitanceModel({self.key!r}, root={str(self.root)!r})" + + +def _spec(name: str) -> dict: + if name not in MANIFEST["models"]: + raise KeyError(f"unknown model {name!r}; available: {sorted(MANIFEST['models'])}") + return MANIFEST["models"][name] + + +def no_tier(tier) -> None: + """Models are named directly since tiers were removed: refuse ``tier=`` with the call to use instead.""" + if tier is not None: + new = "fast" if str(tier).lower() == "fast" else "flagship" + names = ", ".join(MANIFEST["models"]) + raise TypeError(f"tier= was removed: the models are named directly, e.g. load_model({new!r}) (models: {names})") + + +def verify(root, entry: dict) -> list[str]: + """Check every file of a model under root against the manifest sha256 (ModelIntegrityError otherwise).""" + out = [] + for rel, h in model_files(entry): + p = Path(root) / rel + if not p.exists(): + raise ModelIntegrityError(f"model file missing: {p}") + got = sha256_file(p) + if got != h: + raise ModelIntegrityError( + f"{p}: sha256 {got[:12]} differs from the manifest ({h[:12]}); refusing to load it" + ) + out.append(got) + return out + + +def _download(entry: dict, revision: str, cache_dir=None, local_files_only: bool = False) -> Path: + from huggingface_hub import hf_hub_download + + root = None + for rel, _ in model_files(entry): + p = Path( + hf_hub_download( + repo_id=entry["repo_id"], + filename=rel, + revision=revision, + cache_dir=cache_dir, + local_files_only=local_files_only, + ) + ) + r = p + for _ in Path(rel).parts: + r = r.parent + if root is not None and r != root: + raise ModelIntegrityError(f"files of {entry['repo_id']} resolved to different snapshots ({root}, {r})") + root = r + return root + + +def load_model( + name: str = "flagship", + revision: str | None = None, + path=None, + cache_dir=None, + local_files_only: bool = False, + tier=None, +) -> CapacitanceModel: + """A released model: ``load_model("flagship")`` (the default), ``load_model("fast")``, ``load_model("paper")``.""" + no_tier(tier) + entry = _spec(name) + rev = revision or entry["revision"] + repo_dir = entry["repo_id"].split("/")[-1] + if path is not None: + root = Path(path) + elif os.environ.get(ENV_MODELS): + base = Path(os.environ[ENV_MODELS]) + root = base / repo_dir if (base / repo_dir).exists() else base + else: + root = _download(entry, rev, cache_dir, local_files_only) + sha = verify(root, entry) + return CapacitanceModel(name, entry, root, entry["repo_id"], rev, sha) diff --git a/src/squadds/ml/capacitance/network.py b/src/squadds/ml/capacitance/network.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb85014c5981bcd31000b9482ab4724b67311be --- /dev/null +++ b/src/squadds/ml/capacitance/network.py @@ -0,0 +1,47 @@ +# ruff: noqa +# fmt: off +"""Networks of the planar-capacitance models (inference and training share these definitions). + +``build_model``: the residual message-passing network of the paper, flagship and fast models (``full_gnn``; also +``direct_gnn`` / ``full_mlp`` / ``pair_mlp`` checkpoints), verbatim from tl-squadds ``scripts/geomfast/pilot_p2.py`` +(sha256 in ``_core/SOURCES.json`` under ``network.py``). ``build_surrogate``: the learned prior surrogate of the fast model +(``_core/lp_surrogate.py`` ``TriGNN``). +""" + + +def build_model(dx,de,dg,rounds,width=64): + import torch + from torch import nn + def mlp(i,o):return nn.Sequential(nn.Linear(i,width),nn.SiLU(),nn.Linear(width,o)) + class Net(nn.Module): + def __init__(self): + super().__init__(); self.node=mlp(dx+dg,width); self.edge=mlp(de,width) + self.msg=nn.ModuleList([mlp(3*width,width) for _ in range(rounds)]) + self.up=nn.ModuleList([mlp(2*width,width) for _ in range(rounds)]) + self.head=mlp(3*width,1); self.closure=mlp(width,1) + nn.init.zeros_(self.head[-1].weight); nn.init.zeros_(self.head[-1].bias) + nn.init.zeros_(self.closure[-1].weight); nn.init.zeros_(self.closure[-1].bias) + def forward(self,X,E,G,M,PM,pairs,base,bbase,direct=False): + B,N,_=X.shape; i,j=pairs[:,0],pairs[:,1] + h=self.node(torch.cat([X,G[:,None].expand(-1,N,-1)],-1))*M[:,:,None]; e=self.edge(E) + for msg,up in zip(self.msg,self.up): + v=msg(torch.cat([h[:,i]+h[:,j],abs(h[:,i]-h[:,j]),e],-1))*PM[:,:,None] + agg=torch.zeros_like(h); agg.index_add_(1,i,v); agg.index_add_(1,j,v) + degree=torch.zeros_like(M,dtype=X.dtype); degree.index_add_(1,i,PM.float()); degree.index_add_(1,j,PM.float()) + h=(h+up(torch.cat([h,agg/degree.clamp_min(1)[:,:,None]],-1)))*M[:,:,None] + raw=self.head(torch.cat([h[:,i]+h[:,j],abs(h[:,i]-h[:,j]),e],-1)).squeeze(-1) + logc=(base+(raw if direct else .2*torch.tanh(raw))).clamp(-25,20) + mutual=logc.exp()*PM; b=(bbase+self.closure(h).squeeze(-1)).clamp(-20,20).exp()*M + C=torch.zeros((B,N,N),device=X.device); C[:,i,j]=-mutual; C[:,j,i]=-mutual + diag=-C.sum(-1)+b; C=C+torch.diag_embed(diag) + return C,logc + return Net() + + +# fmt: on + + +def build_surrogate(dx, de, dg, w=128, rounds=4): + from ._core.lp_surrogate import build + + return build(dx, de, dg, w, rounds) diff --git a/src/squadds/ml/capacitance/predictor.py b/src/squadds/ml/capacitance/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..55b128bd11c1e53dbc9372d50838c3bd3fe7b942 --- /dev/null +++ b/src/squadds/ml/capacitance/predictor.py @@ -0,0 +1,335 @@ +"""GDS -> full N x N Maxwell capacitance matrix with a released model. + +The steps are those of the tl-squadds Spaces (``geomgnn.paper.predict`` / ``geomgnn.flagship.predict``), statement for +statement: scene from the prepared layout -> geometric embedding (the model's far-sample setting) -> thin-film priors under the +model's prior stack (or the learned prior surrogate) -> networks. The embedding and the priors are cached in memory by the +layout's geometry hash, so a repeated layout (or the paper and flagship models, which share the prior) skips them. +""" + +from __future__ import annotations + +import atexit +import contextlib +import os +import time +import warnings +from collections import OrderedDict +from concurrent.futures import ProcessPoolExecutor +from multiprocessing import get_context + +import numpy as np + +from . import _runtime as RT +from .models import CapacitanceModel, load_model, no_tier +from .result import CapacitanceResult, physical_checks, physical_warning + +_EMB: OrderedDict = OrderedDict() +_PRI: OrderedDict = OrderedDict() +_CACHE_SIZE = [int(os.environ.get("SQUADDS_CAPML_CACHE", "32"))] + + +@contextlib.contextmanager +def quiet(): + """Silence numba's performance hints of the compiled solver (no effect on values).""" + with warnings.catch_warnings(): + try: + from numba.core.errors import NumbaPerformanceWarning + + warnings.simplefilter("ignore", NumbaPerformanceWarning) + except ImportError: + pass + yield + + +@atexit.register +def _teardown() -> None: + """Undo the process-wide prior stack before interpreter shutdown (its patches hold module references).""" + import sys + + A = sys.modules.get("squadds.ml.capacitance._core.api") + if A is not None and A._STATE.get("stack") is not None: + with contextlib.suppress(Exception): + A._teardown() + + +def _warn(msg: str) -> None: + warnings.warn(msg, UserWarning, stacklevel=4) + + +def clear_cache() -> None: + _EMB.clear() + _PRI.clear() + + +def _get(c: OrderedDict, k): + if k in c: + c.move_to_end(k) + return c[k] + return None + + +def _put(c: OrderedDict, k, v) -> None: + if _CACHE_SIZE[0] <= 0: + return + c[k] = v + c.move_to_end(k) + while len(c) > _CACHE_SIZE[0]: + c.popitem(last=False) + + +def _stack_record(a: dict) -> tuple[dict | None, str | None]: + from ._core import api as A + from ._core import paper as PA + from .models import MANIFEST + + if a.get("stack") is None: + return None, None + st = MANIFEST["prior_stacks"][a["stack"]] + return ( + { + "name": a["stack"], + "version": st.get("version"), + "patches": A._STATE.get("patches", []), + "mode": A._STATE.get("mode") or "frozen", + "alpha": PA.ALPHA, + "method": "local_gap micro-MoM (slab)", + }, + st.get("version"), + ) + + +def run_scene(reg, name: str, sc, lhash: str, threads: int, stack: tuple | None = None) -> dict: + """geomgnn.paper.predict_scene with the embedding row and the priors taken from / put into the in-memory caches. stack: + (eps_r, thickness_um) the prior is solved at (None: the training stack); the embedding always uses the training stack.""" + from ._core import overlap as OV + from ._core import paper as PA + from ._core._tlsq.uge import blocks as B + from ._core._tlsq.uge.graph import scene_graph + + a = PA.arms(reg)[name] + obj = PA.load(name, reg, "", threads) + PA.apply_stack(reg, a, threads) + emb = {} if os.environ.get("TLSQ_EMBEDDING_EXACT") == "1" else (a.get("embedding") or {}) + old = dict(B.FAR_DECIMATION) + B.FAR_DECIMATION.update(k=int(emb.get("far_k", 0)), d_far=float(emb.get("d_far_um", 100.0))) + try: + from ._core import api as A + + need = [] if (a["kind"] == "gnn" and (obj.direct or obj.surrogate is not None)) else PA.levels_of(a) + ekey = ( + lhash, + B.FAR_DECIMATION["k"], + B.FAR_DECIMATION["d_far"], + B.EMBED_MODE["mode"], + B.EDGE_TABLE["on"], + threads, + ) + pkey = (lhash, tuple(need), repr(A._STATE.get("stack")), threads, stack) + row = _get(_EMB, ekey) + P = _get(_PRI, pkey) if need else {} + hits = dict(embedding=row is not None, prior=bool(need) and P is not None) + t0 = time.perf_counter() + fut = OV.start(sc, threads) if (row is None and P is None and need and OV.enabled(sc, threads)) else None + if row is None and fut is None: + row = PA.lt.add_tokens(sc, scene_graph(sc)) + t1 = time.perf_counter() + tl = {} + if P is None: + P, tl = PA.solve_levels(sc, need, threads, stack) + t2 = time.perf_counter() + extra = {} + if fut is not None: + row, embed_s = fut.result() + extra = dict(overlap=True, geometry_worker=embed_s, geometry_wait_after_prior=time.perf_counter() - t2) + t2 = time.perf_counter() + _put(_EMB, ekey, row) + if need: + _put(_PRI, pkey, P) + C = np.asarray(PA.combine(a, obj, row, P), float) + t3 = time.perf_counter() + finally: + B.FAR_DECIMATION.clear() + B.FAR_DECIMATION.update(old) + return dict( + C=C, + names=row["names"], + row=row, + priors=P, + cache_hits=hits, + timing=dict(geometry=t1 - t0, prior=t2 - t1, prior_levels=tl, network=t3 - t2, total=t3 - t0, **extra), + ) + + +def _substrate(eps_r, thickness_um, learned_prior: bool) -> tuple[tuple | None, dict, list]: + """(stack the prior is solved at or None for the training stack, substrate record, warnings). Tiers that solve a prior solve it + at (eps_r, thickness_um) (the calibrated route); the fast model's learned prior only knows the training stack, so off the stack + its training-stack prediction is rescaled by (1 + eps_r) / (1 + 11.45) and a warning is raised.""" + from ._core import api as A + + sub, w = A.substrate_route(eps_r, thickness_um, solves_prior=not learned_prior) + return (None if A.on_training_stack(eps_r, thickness_um) else (sub["eps_r"], sub["thickness_um"])), sub, w + + +class CapacitancePredictor: + """``CapacitancePredictor(load_model("flagship")).predict("chip.gds")`` -> CapacitanceResult. + + threads: CPU threads per prediction (default 2; results are deterministic for a given thread count and machine). + embed_cache_dir: optional on-disk cache of per-body embedding blocks (bit-identical on the same machine). + """ + + def __init__( + self, + model: CapacitanceModel | str | None = None, + threads: int = 2, + embed_cache_dir=None, + tier=None, + **load_kwargs, + ): + no_tier(tier) + if model is None or isinstance(model, str): + model = load_model(model or "flagship", **load_kwargs) + self.model = model + self.threads = int(threads) + self.reg = model.registry() + if embed_cache_dir is not None: + from ._core._tlsq.uge import blocks as B + + B.EMBED_CACHE["dir"] = str(embed_cache_dir) + + def __repr__(self) -> str: + return f"CapacitancePredictor({self.model.key!r}, threads={self.threads})" + + def predict( + self, + layout, + threads: int | None = None, + eps_r: float = RT.TRAIN_EPS_R, + thickness_um: float = RT.TRAIN_THICKNESS_UM, + workers: int | None = None, + **prepare_kwargs, + ): + """layout: GDS path, gdstk Library / Cell, PreparedLayout, or a list of these (a list returns a list; ``workers`` > 1 + predicts it on that many processes, each with ``threads`` threads). Extra keyword arguments go to the layout + preparation (ground_layers, conductor_layers, margin_gaps, select, ...). + + eps_r, thickness_um: the substrate. Off the training stack (Si, 11.45, 350 µm) the flagship and paper models + solve the physics prior at this stack and correct it with the unchanged networks (the calibrated route, recorded in + ``result.substrate``); the fast model rescales its training-stack prediction by (1 + eps_r) / (1 + 11.45) and warns. + Combinations outside the tested range (Si at 10-1000 µm, or eps_r 3.8-24 at 350 µm) warn.""" + threads = int(threads or self.threads) + _substrate(eps_r, thickness_um, self._learned_prior()) + if isinstance(layout, (list, tuple)): + return self._batch(list(layout), threads, eps_r, thickness_um, workers, prepare_kwargs) + return self._one(layout, threads, eps_r, thickness_um, prepare_kwargs) + + def _learned_prior(self) -> bool: + from ._core import paper as PA + + return bool(PA.arms(self.reg)[self.model.name].get("learned_prior")) + + def _one(self, layout, threads, eps_r, thickness_um, prepare_kwargs) -> CapacitanceResult: + from ._core import api as A + from ._core import paper as PA + + at, sub, sub_w = _substrate(eps_r, thickness_um, self._learned_prior()) + t = time.perf_counter() + lay = RT.prepare_layout(layout, **prepare_kwargs) + prep_s = time.perf_counter() - t + lhash = RT.layout_hash(lay) + name = self.model.name + a = PA.arms(self.reg)[name] + with RT.LOCK, quiet(): + RT.configure(threads) + t = time.perf_counter() + PA.load(name, self.reg, "", threads) + load_s = time.perf_counter() - t + sc = A.scene_from_prepared(lay) + try: + r = run_scene(self.reg, name, sc, lhash, threads, None if sub["eps_rescale_factor"] is not None else at) + except AssertionError as e: + raise ValueError( + f"{self.model.key}: the prior or the features of this layout are not finite (no matrix returned): {e}" + ) from e + stack, version = _stack_record(a) + C = r["C"] if at is None or sub["eps_rescale_factor"] is None else r["C"] * sub["eps_rescale_factor"] + names = ["G"] + list(lay.names) + if list(r["names"]) != names: + raise RuntimeError(f"scene names {r['names']} differ from the prepared layout {names}") + warnings = [w for w in lay.warnings if "beyond the validated range" not in w] + if a.get("warning"): + warnings.insert(0, a["warning"]) + chk = physical_checks(C) + pw = physical_warning(chk) + if pw: + warnings.insert(0, pw) + _warn(pw) + warnings += sub_w + gd = lay.info.get("ground_detection") + for w in sub_w + [ + w + for w in lay.warnings + if gd and gd["method"] == "automatic" and w.startswith("ground and conductors share") + ]: + _warn(w) + tm = r["timing"] + timing = { + "prepare_s": prep_s, + "load_s": load_s, + "geometry_s": tm["geometry"], + "prior_s": tm["prior"], + "prior_levels_s": tm["prior_levels"], + "network_s": tm["network"], + "total_s": tm["total"], + "cache_hits": r["cache_hits"], + "threads": threads, + } + if tm.get("overlap"): + timing["overlap"] = True + from . import _core + + return CapacitanceResult( + names=names, + matrix_fF=C, + model=self.model.name, + title=self.model.title, + prior_version=version or ("learned prior surrogate" if a.get("learned_prior") else None), + prior_stack=stack, + weights_sha256=self.model.weights_sha256, + learned_prior_sha256=self.model.learned_prior_sha256, + timing_s=timing, + threads=threads, + machine=RT.machine(), + warnings=warnings, + substrate=sub, + ground_detection=gd, + checks=chk, + source=str(lay.source), + layout_hash=lhash, + cached=r["cache_hits"]["embedding"] and (r["cache_hits"]["prior"] or not tm["prior_levels"]), + package=f"squadds.ml.capacitance (_core = geomgnn {_core.__version__})", + ) + + def _batch(self, items, threads, eps_r, thickness_um, workers, prepare_kwargs) -> list[CapacitanceResult]: + workers = min(int(workers or 1), len(items)) if items else 1 + if workers <= 1: + return [self._one(x, threads, eps_r, thickness_um, prepare_kwargs) for x in items] + lays = [RT.prepare_layout(x, **prepare_kwargs) for x in items] + m = self.model + from ._core._spawn import boot + + ini, args = boot(_worker_init, m, threads) + with ProcessPoolExecutor(workers, mp_context=get_context("spawn"), initializer=ini, initargs=args) as ex: + return list(ex.map(_worker_predict, lays, [(eps_r, thickness_um)] * len(lays))) + + +_WORKER: dict = {} + + +def _worker_init(model, threads): + RT._USER_ENV.update(TLSQ_WINDOW_PROCS="0", TLSQ_LEVEL_PROCS="0") # one process per layout: no nested worker pools + os.environ.update(RT._USER_ENV) + _WORKER["p"] = CapacitancePredictor(model, threads=threads) + + +def _worker_predict(lay, sub): + return _WORKER["p"].predict(lay, eps_r=sub[0], thickness_um=sub[1]) diff --git a/src/squadds/ml/capacitance/priors.py b/src/squadds/ml/capacitance/priors.py new file mode 100644 index 0000000000000000000000000000000000000000..0c87f9443e1e827e788f40e89a863cd6ab171f4a --- /dev/null +++ b/src/squadds/ml/capacitance/priors.py @@ -0,0 +1,188 @@ +"""Physics priors: thin-film method-of-moments capacitance matrices of a layout (no learned parameter). + +- ``coarse_physics_prior``: one solve at p = 0.375 panels per gap (the paper's cheap-physics comparator). +- ``optimized_physics_prior``: C^R = R(1.5, 3) = exp(2 log C(3) - log C(1.5)), entry by entry, the physics prior of the paper + model and of the flagship model. + +Both run on the "corrected" prior stack (prior v2m + substrate far field, compiled exact solver; gap share alpha fitted once on +TRAIN), exactly as the models compute them, on a substrate of ``eps_r`` and ``thickness_um`` (default the training stack, Si 11.45, +350 µm; the thin-film kernel is a dielectric slab of that thickness with vacuum below). Priors computed on macOS are not bit-identical to the released ones (HPC x86; up +to ~2.4e-3 relative on some layouts): never mix them into released data. + +TODO (other priors of the paper, not served yet): +- uncorrected prior (v1, frozen solver + value-preserving rejection-tail fix; stack ``uncorrected``) +- version 2 (no window-margin widening; stack ``version2``) +- corrected prior with the half-space far field (v2m before 2026-10-20; stack ``corrected_halfspace``) +- single solves at 0.75 / 1.5 / 3 panels per gap +- Richardson pair R(0.75, 1.5) (the paper's balanced variant) +""" + +from __future__ import annotations + +import time +import warnings +from dataclasses import dataclass, field + +import numpy as np + +from . import _runtime as RT + +STACK = "corrected" + + +@dataclass +class PriorResult: + names: list[str] + C_fF: np.ndarray + solves_fF: dict = field(default_factory=dict) + levels_ppg: list[float] = field(default_factory=list) + kind: str = "" + prior_version: str = "" + stack: dict = field(default_factory=dict) + alpha: float = 0.0 + timing_s: dict = field(default_factory=dict) + threads: int = 2 + machine: str = "" + layout_hash: str = "" + units: str = "fF" + + def to_dataframe(self): + import pandas as pd + + return pd.DataFrame(self.C_fF, index=self.names, columns=self.names) + + def to_dict(self) -> dict: + return { + "names": self.names, + "C_fF": self.C_fF.tolist(), + "solves_fF": {f"{k:g}": v.tolist() for k, v in self.solves_fF.items()}, + "levels_ppg": self.levels_ppg, + "kind": self.kind, + "prior_version": self.prior_version, + "stack": self.stack, + "alpha": self.alpha, + "timing_s": self.timing_s, + "threads": self.threads, + "machine": self.machine, + "layout_hash": self.layout_hash, + "units": self.units, + } + + +def _registry(): + from .models import registry_view + + return registry_view({}, ".", "squadds-priors") + + +def solve( + layout, + levels, + threads: int = 2, + eps_r: float = RT.TRAIN_EPS_R, + thickness_um: float = RT.TRAIN_THICKNESS_UM, + **prepare_kwargs, +) -> tuple: + """(prepared layout, {ppg: positive-mutual matrix P = -C}, {ppg: seconds}, stack record, hash) under the corrected stack, solved + on a substrate of eps_r and thickness_um.""" + from ._core import api as A + from ._core import paper as PA + from .models import MANIFEST + from .predictor import _PRI, _get, _put, quiet + + sub, w = A.substrate_route(eps_r, thickness_um) + stack = None if A.on_training_stack(eps_r, thickness_um) else (sub["eps_r"], sub["thickness_um"]) + lay = RT.prepare_layout(layout, **prepare_kwargs) + lhash = RT.layout_hash(lay) + reg = _registry() + with RT.LOCK, quiet(): + threads = RT.configure(threads) + PA.apply_stack(reg, {"stack": STACK}, threads) + key = (lhash, tuple(float(p) for p in levels), repr(A._STATE.get("stack")), threads, stack) + P, tl = _get(_PRI, key), {} + if P is None: + sc = A.scene_from_prepared(lay) + P, tl = PA.solve_levels(sc, [float(p) for p in levels], threads, stack) + _put(_PRI, key, P) + st = MANIFEST["prior_stacks"][STACK] + rec = { + "name": STACK, + "version": st["version"], + "patches": list(A._STATE.get("patches", [])), + "mode": A._STATE.get("mode"), + "substrate": {"eps_r": sub["eps_r"], "thickness_um": sub["thickness_um"], "tested": sub["tested"]}, + } + for m in w: + warnings.warn( + m.replace("of the calibrated route", "of the calibrated substrate study"), UserWarning, stacklevel=4 + ) + return lay, P, tl, rec, lhash + + +def _result(kind, layout, levels, combine, threads, eps_r, thickness_um, prepare_kwargs) -> PriorResult: + from ._core import paper as PA + from ._core import x1_core as X + + t = time.perf_counter() + lay, P, tl, rec, lhash = solve(layout, levels, threads, eps_r, thickness_um, **prepare_kwargs) + C = np.asarray(combine(P), float) + return PriorResult( + names=["G"] + list(lay.names), + C_fF=C, + solves_fF={p: X.to_maxwell(P[p]) for p in levels}, + levels_ppg=list(levels), + kind=kind, + prior_version=rec["version"], + stack=rec, + alpha=PA.ALPHA, + timing_s={"total_s": time.perf_counter() - t, "levels_s": tl, "cached": not tl}, + threads=int(threads), + machine=RT.machine(), + layout_hash=lhash, + ) + + +def coarse_physics_prior( + layout, + threads: int = 2, + eps_r: float = RT.TRAIN_EPS_R, + thickness_um: float = RT.TRAIN_THICKNESS_UM, + **prepare_kwargs, +) -> PriorResult: + """One thin-film solve at 0.375 panels per gap (corrected stack) on a substrate of eps_r and thickness_um: Maxwell matrix in + fF, ground first.""" + from ._core import x1_core as X + + return _result( + "coarse_physics_prior p=0.375", + layout, + [0.375], + lambda P: X.to_maxwell(P[0.375]), + threads, + eps_r, + thickness_um, + prepare_kwargs, + ) + + +def optimized_physics_prior( + layout, + threads: int = 2, + eps_r: float = RT.TRAIN_EPS_R, + thickness_um: float = RT.TRAIN_THICKNESS_UM, + **prepare_kwargs, +) -> PriorResult: + """C^R = R(1.5, 3) of the corrected stack (two solves, Richardson-extrapolated in log, every entry) on a substrate of eps_r + and thickness_um: Maxwell matrix in fF, ground first; both solves are returned in ``solves_fF``.""" + from ._core import x1_core as X + + return _result( + "optimized_physics_prior R(1.5,3)", + layout, + [1.5, 3.0], + lambda P: X.c0(P, 1.5, 3.0), + threads, + eps_r, + thickness_um, + prepare_kwargs, + ) diff --git a/src/squadds/ml/capacitance/qc.py b/src/squadds/ml/capacitance/qc.py new file mode 100644 index 0000000000000000000000000000000000000000..98a98c9a34e55ae98552bd2a79012926beb8b242 --- /dev/null +++ b/src/squadds/ml/capacitance/qc.py @@ -0,0 +1,668 @@ +"""Label and layout QC for planar capacitance data: one set of rules for contributions, dataset builds and training shards. + +Every check reports instead of raising; ``QCReport.ok`` is False when any check failed (an error). The rules are those of the +dataset (``PLAN_DATASET_HF.md`` §4.2): + +- reject: matrix not square over ``net_order``, missing / duplicate / misplaced net names, non-finite entries, asymmetry + (rel > 1e-3; Q3D exports are exactly symmetric, other solvers such as Palace are not; > 1e-6 warns, the matrix is then + symmetrized), diagonal <= 0, off-diagonal >= 0 (a zero only when flagged), signal block not positive definite, a conductor + count from the GDS that differs from the matrix size (nets are never merged), unreadable GDS, a duplicate of a held-out + test design (it would leak the test label); +- warn: signal-row closure ``|sum_j C_ij| / C_ii`` > 5 %, not converged, non-monotone pass history, unusual stack, duplicates + of non-test designs, label entries far from ``optimized_physics_prior`` (physics sanity; never a rejection). + +Only numpy is imported at module level; gdstk / shapely are imported by the GDS checks, the physics prior by +``prior_sanity`` (needs ``pip install 'squadds[ml]'``). +""" + +from __future__ import annotations + +import csv +import hashlib +import math +import re +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np + +GROUND = "G" +TO_FF = {"F": 1e15, "nF": 1e6, "pF": 1e3, "fF": 1.0, "aF": 1e-3} +SYM_RTOL = 1e-3 +SYM_WARN = 1e-6 +CLOSURE_WARN = 0.05 +PRIOR_FLOOR_FF = 0.1 +PRIOR_RATIO_BAND = (0.5, 2.0) +TRAINING_STACK = {"eps_r": 11.45, "substrate_um": 350.0} +STACK_RANGES = {"eps_r": (1.0, 30.0), "substrate_um": (5.0, 2000.0), "freq_GHz": (0.1, 50.0)} +GDS_UNITS_M = (1e-6, 1e-9) +DEFAULT_LAYERS = {"ground": [(1, 0)], "conductor": [(1, 10)]} +_HEADER = re.compile(r"\s*C\(([^,]+),([^)]+)\)(\*1e15)?\s*\[(\w+)\]") + + +@dataclass +class QCReport: + """Result of a QC run: ``ok`` (no error), ``errors``, ``warnings``, ``fixes`` (applied automatically) and the measured + values in ``info``. ``to_markdown()`` renders it for a validation report.""" + + subject: str = "" + errors: list[str] = field(default_factory=list) + warnings: list[str] = field(default_factory=list) + fixes: list[str] = field(default_factory=list) + info: dict = field(default_factory=dict) + children: list = field(default_factory=list) + + @property + def ok(self) -> bool: + return not self.errors and all(c.ok for c in self.children) + + def error(self, msg: str) -> None: + self.errors.append(msg) + + def warn(self, msg: str) -> None: + self.warnings.append(msg) + + def extend(self, other: QCReport, prefix: str = "") -> QCReport: + """Fold another report's errors / warnings / fixes / info into this one (messages prefixed).""" + p = f"{prefix}: " if prefix else "" + self.errors += [p + m for m in other.errors] + self.warnings += [p + m for m in other.warnings] + self.fixes += [p + m for m in other.fixes] + self.info.update(other.info) + return self + + def all_errors(self) -> list[str]: + return self.errors + [f"{c.subject}: {m}" for c in self.children for m in c.all_errors()] + + def all_warnings(self) -> list[str]: + return self.warnings + [f"{c.subject}: {m}" for c in self.children for m in c.all_warnings()] + + def to_dict(self) -> dict: + return { + "subject": self.subject, + "ok": self.ok, + "errors": self.errors, + "warnings": self.warnings, + "fixes": self.fixes, + "info": _jsonable(self.info), + "children": [c.to_dict() for c in self.children], + } + + def to_markdown(self, title: str | None = None) -> str: + n_err, n_warn = len(self.all_errors()), len(self.all_warnings()) + out = [f"# {title or 'QC report: ' + (self.subject or '')}".rstrip(), ""] + out.append(f"**Result: {'PASS' if self.ok else 'FAIL'}** ({n_err} errors, {n_warn} warnings)") + out.append("") + out += _md_block(self, level=2) + for c in self.children: + out.append(f"## {c.subject}: {'pass' if c.ok else 'FAIL'}") + out.append("") + out += _md_block(c, level=3) + return "\n".join(out).rstrip() + "\n" + + def __repr__(self) -> str: + return ( + f"QCReport({self.subject!r}, ok={self.ok}, errors={len(self.all_errors())}, " + f"warnings={len(self.all_warnings())})" + ) + + +def _md_block(r: QCReport, level: int) -> list[str]: + out = [] + for name, items in (("Errors", r.errors), ("Warnings", r.warnings), ("Fixed automatically", r.fixes)): + if items: + out.append(f"{'#' * level} {name}") + out += [f"- {m}" for m in items] + out.append("") + if r.info: + out.append(f"{'#' * level} Measured") + out += [f"- `{k}`: {_fmt(v)}" for k, v in r.info.items()] + out.append("") + return out + + +def _fmt(v) -> str: + if isinstance(v, float): + return f"{v:.6g}" + return str(_jsonable(v)) + + +def _jsonable(o): + if isinstance(o, dict): + return {str(k): _jsonable(v) for k, v in o.items()} + if isinstance(o, (list, tuple)): + return [_jsonable(v) for v in o] + if isinstance(o, np.ndarray): + return o.tolist() + if isinstance(o, np.generic): + return o.item() + if isinstance(o, float) and not math.isfinite(o): + return None + return o + + +# ---------------------------------------------------------------------------------------------------------------- units +def to_fF(values, unit: str) -> np.ndarray: + """Values in ``unit`` (F, nF, pF, fF, aF; ``"pF*1e15"`` = the exp12 re-export header ``C(a,b)*1e15 [pF]``, whose values + are pF x 1e15) converted to fF.""" + u = str(unit).strip() + x15 = u.endswith("*1e15") + u = u.replace("*1e15", "").strip("[] ") + if u not in TO_FF: + raise ValueError(f"unknown capacitance unit {unit!r}; use one of {sorted(TO_FF)}") + return np.asarray(values, float) * TO_FF[u] * (1e-15 if x15 else 1.0) + + +def unit_plausibility(C_fF, declared: str) -> str | None: + """A warning when a matrix in fF looks like it was given in another unit (entries of ~1e-15 or ~1e3 x the usual size).""" + a = np.abs(np.asarray(C_fF, float)) + a = a[np.isfinite(a) & (a > 0)] + if not a.size: + return None + m = float(np.median(a)) + if m < 1e-9: + return f"median |C| = {m:.3g} fF after conversion from {declared}: the values look like farads" + if m > 1e5: + return f"median |C| = {m:.3g} fF after conversion from {declared}: implausibly large for a planar component" + return None + + +# ---------------------------------------------------------------------------------------------------------------- readers +def read_cap_matrix(path) -> dict: + """Q3D ``cap_matrix.csv`` (one row per adaptive pass; ``C(a,b) [unit]`` columns in any unit, also the ``*1e15`` header) + -> ``{"names" (G first, then first appearance), "passes" [(pass index, N x N fF)], "units", "freq_GHz"}``. Incomplete rows + (pre-allocated passes) are kept as NaN matrices and skipped by the QC.""" + rows = [r for r in csv.reader(open(path)) if r] + if not rows: + raise ValueError(f"{path}: empty file") + hdr, data = rows[0], rows[1:] + cols, order, units = {}, [], set() + i_pass = i_freq = None + for j, h in enumerate(hdr): + hs = h.strip().strip('"') + if hs.lower().startswith("pass"): + i_pass = j + elif hs.lower().startswith("freq"): + i_freq = j + m = _HEADER.match(hs) + if not m: + continue + a, b = m.group(1).strip(), m.group(2).strip() + unit = m.group(4) + ("*1e15" if m.group(3) else "") + units.add(unit) + cols[(a, b)] = (j, float(to_fF(1.0, unit))) + for x in (a, b): + if x not in order: + order.append(x) + if not cols: + raise ValueError(f"{path}: no C(a,b) [unit] columns") + names = ([GROUND] if GROUND in order else []) + [x for x in order if x != GROUND] + passes, freq = [], None + for k, r in enumerate(data): + C = np.full((len(names), len(names)), np.nan) + for ia, a in enumerate(names): + for ib, b in enumerate(names): + jj = cols.get((a, b)) or cols.get((b, a)) + if jj is None: + continue + try: + C[ia, ib] = float(r[jj[0]]) * jj[1] + except (ValueError, IndexError): + pass + try: + p = int(float(r[i_pass])) if i_pass is not None else k + 1 + except (ValueError, IndexError): + p = k + 1 + if i_freq is not None: + try: + freq = float(r[i_freq]) + except (ValueError, IndexError): + pass + passes.append((p, C)) + return {"names": names, "passes": passes, "units": sorted(units), "freq_GHz": freq} + + +def read_conv(path) -> dict: + """Q3D ``.conv`` convergence file -> pass history, passes completed, delta target and final delta (%).""" + t = Path(path).read_text() + + def g(k, f=float): + m = re.search(rf"{k}\s*:\s*(\S+)", t) + try: + return f(m.group(1)) if m else None + except ValueError: + return None + + hist = [] + for m in re.finditer(r"^\s*(\d+)\|\s*(\d+)\|\s*([^|]+)\|", t, re.M): + d = m.group(3).strip() + hist.append( + {"pass": int(m.group(1)), "n_triangles": int(m.group(2)), "delta_pct": None if d == "N/A" else float(d)} + ) + return { + "pass_history": hist, + "passes_completed": g("Completed", int), + "delta_target_pct": g("Target"), + "delta_pct_final": g("Current"), + } + + +# ---------------------------------------------------------------------------------------------------------------- labels +def label_qc( + C, + names, + net_order=None, + unit: str = "fF", + passes=None, + convergence: dict | None = None, + flagged_zero=(), + sym_rtol: float = SYM_RTOL, + closure_warn: float = CLOSURE_WARN, + subject: str = "", +) -> QCReport: + """QC of one Maxwell matrix ``C`` (``names`` = its row order; any unit, converted to fF). + + net_order: the declared net order (G first); the matrix must be square over exactly these names. passes: optional + ``[(pass index, matrix in the same names / unit)]``, the last complete pass must equal ``C``. convergence: optional + ``{"delta_pct_final", "delta_target_pct", "passes_completed"}``. flagged_zero: pairs ``(a, b)`` whose exact zero is + explained (e.g. a lattice entry below the solver floor). ``info["matrix_fF"]`` holds the matrix in ``net_order``.""" + r = QCReport(subject) + names = [str(x) for x in names] + try: + C = to_fF(C, unit) + except ValueError as e: + r.error(str(e)) + return r + if C.ndim != 2 or C.shape[0] != C.shape[1]: + r.error(f"matrix is not square: shape {C.shape}") + return r + if C.shape[0] != len(names): + r.error(f"matrix size {C.shape[0]} does not match {len(names)} net names {names}") + return r + if len(set(names)) != len(names): + r.error(f"duplicate net names {names}") + return r + order = [str(x) for x in (net_order if net_order is not None else names)] + if GROUND not in order: + r.error(f"ground net {GROUND!r} missing from the net order {order}") + return r + if order[0] != GROUND: + r.error(f"ground net {GROUND!r} must be first in the net order (got {order})") + if set(order) != set(names) or len(order) != len(names): + r.error(f"matrix nets {sorted(names)} differ from the declared net order {order}") + return r + ix = [names.index(n) for n in order] + C = C[np.ix_(ix, ix)] + names = order + n = len(names) + r.info["n_conductors"] = n + r.info["net_order"] = names + if not np.isfinite(C).all(): + r.error("non-finite entries in the matrix") + return r + w = unit_plausibility(C, unit) + if w: + r.warn(w) + scale = float(np.abs(C).max()) or 1.0 + sym = float(np.abs(C - C.T).max() / scale) + r.info["symmetry_rel"] = sym + if sym > sym_rtol: + r.error(f"asymmetric: max |C - C^T| / max |C| = {sym:.3g} > {sym_rtol:g}") + elif sym > SYM_WARN: + r.warn(f"slightly asymmetric (max |C - C^T| / max |C| = {sym:.3g}); symmetrized as (C + C^T) / 2") + Cs = 0.5 * (C + C.T) + d = np.diag(Cs) + if not np.all(d > 0): + r.error(f"non-positive diagonal entries on {[names[i] for i in np.flatnonzero(d <= 0)]}") + flagged = {frozenset((str(a), str(b))) for a, b in flagged_zero} + pos, zero = [], [] + for i in range(n): + for j in range(i + 1, n): + if Cs[i, j] > 0: + pos.append(f"{names[i]}-{names[j]} ({Cs[i, j]:.4g} fF)") + elif Cs[i, j] == 0 and frozenset((names[i], names[j])) not in flagged: + zero.append(f"{names[i]}-{names[j]}") + if pos: + r.error(f"positive off-diagonal entries (Maxwell signs need C_ij < 0): {pos[:5]}") + if zero: + r.error(f"exactly-zero off-diagonal entries not flagged as explained: {zero[:5]}") + sig = np.array([x != GROUND for x in names]) + if sig.any() and np.all(d[sig] > 0): + clo = np.abs(Cs.sum(1)[sig]) / d[sig] + r.info["closure_max_rel"] = float(clo.max()) + if clo.max() > closure_warn: + worst = names[int(np.flatnonzero(sig)[int(np.argmax(clo))])] + r.warn(f"signal-row closure |sum_j C_ij| / C_ii = {clo.max():.3g} on {worst} (> {closure_warn:.0%})") + eig = float(np.linalg.eigvalsh(Cs[np.ix_(sig, sig)]).min()) + r.info["signal_block_min_eig_fF"] = eig + if eig <= 0: + r.error(f"signal block not positive definite (min eigenvalue {eig:.4g} fF)") + if passes is not None: + _pass_history(r, passes, C, unit, names, ix) + if convergence: + _convergence(r, convergence) + r.info["matrix_fF"] = Cs + return r + + +def _pass_history(r: QCReport, passes, C, unit, order, ix) -> None: + idx = [int(p) for p, _ in passes] + r.info["passes"] = len(idx) + if idx != sorted(idx) or len(set(idx)) != len(idx): + r.warn(f"pass indices are not strictly increasing: {idx}") + complete = [(p, to_fF(M, unit)) for p, M in passes if np.isfinite(np.asarray(M, float)).all()] + if not complete: + r.error("no complete adaptive pass in the pass history") + return + last = complete[-1][1][np.ix_(ix, ix)] + if not np.allclose(last, C, rtol=1e-9, atol=1e-12): + r.error("the label is not the last complete pass of the pass history") + if len(complete) >= 2: + prev = complete[-2][1][np.ix_(ix, ix)] + big = np.abs(last) >= 0.1 + if big.any(): + r.info["last_pass_change_max_pct"] = float(np.max(np.abs(last - prev)[big] / np.abs(last)[big]) * 100) + + +def _convergence(r: QCReport, conv: dict) -> None: + fin, tgt = conv.get("delta_pct_final"), conv.get("delta_target_pct") + r.info["delta_pct_final"], r.info["delta_target_pct"] = fin, tgt + if conv.get("passes_completed") is not None: + r.info["passes_completed"] = conv["passes_completed"] + if fin is None or tgt is None: + r.warn("convergence not recorded (final delta or target missing)") + elif fin > tgt: + r.warn(f"not converged: final delta {fin:g} % > target {tgt:g} %") + r.info["converged"] = None if fin is None or tgt is None else bool(fin <= tgt) + + +# ---------------------------------------------------------------------------------------------------------------- layouts +def geom_hash(path) -> str: + """``"sha256:"`` of the canonical polygon multiset of a GDS (layer, datatype, vertices rounded to 1 nm, sorted): the + dataset's duplicate key, identical to the ``geom_hash`` column of ``SQuADDS/SQuADDS_PlanarCapacitance``.""" + import gdstk + + lib = gdstk.read_gds(str(path)) + s = lib.unit / 1e-9 + polys = [p for c in lib.top_level() for p in c.polygons] + key = sorted((p.layer, p.datatype, np.round(p.points * s).astype(np.int64).tobytes()) for p in polys) + h = hashlib.sha256() + for la, dt, b in key: + h.update(f"{la}/{dt}:".encode()) + h.update(b) + return "sha256:" + h.hexdigest() + + +def _components(polys) -> list[list[int]]: + import shapely + + n = len(polys) + parent = list(range(n)) + + def find(a): + while parent[a] != a: + parent[a] = parent[parent[a]] + a = parent[a] + return a + + if n > 1: + ii, jj = shapely.STRtree(polys).query(polys, predicate="intersects") + for a, b in zip(ii, jj): + ra, rb = find(int(a)), find(int(b)) + if ra != rb: + parent[max(ra, rb)] = min(ra, rb) + groups: dict = {} + for i in range(n): + groups.setdefault(find(i), []).append(i) + return sorted(groups.values(), key=lambda g: g[0]) + + +def _layers(x) -> list[tuple[int, int]]: + return [tuple(int(v) for v in la) for la in x] + + +def gds_qc(path, layer_map: dict | None = None, nets: dict | None = None, subject: str = "") -> QCReport: + """GDS readback: readable by gdstk, one top cell, unit 1 um or 1 nm, declared layers present, every polygon valid, and the + conductor count (``info["n_conductors"]``, ground included) inferred from the layout. + + Conductors: the connected bodies of the conductor-layer polygons (touching polygons are one metal body, hence one net), in + file order, unless ``nets`` = ``{net name: [conductor-layer polygon indices in file order]}`` assigns polygons explicitly. + Bodies touching the ground metal are at ground potential (warned). ``info["geom_hash"]`` is the dataset duplicate key.""" + r = QCReport(subject or str(path)) + try: + import gdstk + import shapely + from shapely.geometry import Polygon + except ImportError as e: + r.error(f"GDS checks need gdstk and shapely ({e}); install them with pip install 'squadds[ml]'") + return r + lm = layer_map or DEFAULT_LAYERS + gl, cl = set(_layers(lm.get("ground", []))), set(_layers(lm.get("conductor", []))) + try: + lib = gdstk.read_gds(str(path)) + except Exception as e: # noqa: BLE001 + r.error(f"gdstk cannot read the file: {e}") + return r + tops = lib.top_level() + r.info["top_cells"] = [c.name for c in tops] + if len(tops) != 1: + r.error(f"{len(tops)} top cells ({[c.name for c in tops][:5]}); exactly one is required") + if not tops: + return r + r.info["unit_m"], r.info["precision_m"] = lib.unit, lib.precision + if not any(math.isclose(lib.unit, u, rel_tol=1e-9) for u in GDS_UNITS_M): + r.error(f"GDS user unit {lib.unit:g} m: use 1 um or 1 nm") + if not (1e-12 <= lib.precision <= 1e-9): + r.warn(f"GDS precision {lib.precision:g} m (expected 1 nm or finer)") + top = tops[0] + raw = ( + top.get_polygons(apply_repetitions=True, include_paths=True) if (top.references or top.paths) else top.polygons + ) + u = lib.unit / 1e-6 + present = sorted({(p.layer, p.datatype) for p in raw}) + r.info["layers"] = present + missing = sorted((gl | cl) - set(present)) + if missing: + r.error(f"declared layers {missing} have no polygons (layers present: {present})") + gpolys, cpolys, invalid = [], [], 0 + for p in raw: + key = (p.layer, p.datatype) + if key not in gl and key not in cl: + continue + if len(p.points) < 3: + invalid += 1 + continue + g = Polygon(p.points * u) + if g.area <= 0 or (not g.is_valid and abs(shapely.make_valid(g).area - g.area) > 1e-6 * g.area): + invalid += 1 # keyhole polygons (ground planes with holes) touch themselves without changing area: accepted + (gpolys if key in gl else cpolys).append(g) + if invalid: + r.error( + f"{invalid} invalid polygon(s) on the ground / conductor layers (self-intersecting, degenerate or < 3 vertices)" + ) + r.info["n_polygons"] = len(gpolys) + len(cpolys) + if not gpolys or not cpolys: + if not gpolys: + r.error("no ground polygons") + if not cpolys: + r.error("no conductor polygons") + r.info["n_conductors"] = 1 if gpolys else 0 + return r + cvalid = [shapely.make_valid(g) if not g.is_valid else g for g in cpolys] + if nets: + idx = sorted(i for v in nets.values() for i in v) + if idx != list(range(len(cvalid))): + r.error(f"nets map must assign every conductor-layer polygon exactly once (0..{len(cvalid) - 1})") + bodies = [shapely.union_all([cvalid[i] for i in v if 0 <= i < len(cvalid)]) for v in nets.values()] + r.info["conductor_names"] = list(nets) + else: + bodies = [shapely.union_all([cvalid[i] for i in comp]) for comp in _components(cvalid)] + if len(bodies) < len(cvalid): + r.info["touching_polygons_joined"] = len(cvalid) - len(bodies) + G = shapely.union_all([shapely.make_valid(g) if not g.is_valid else g for g in gpolys]) + shorted = [i for i, b in enumerate(bodies) if shapely.intersects(b, G)] + if shorted: + r.warn( + f"{len(shorted)} conductor body(ies) touch the ground metal (bodies {shorted}): they are at ground potential" + ) + r.info["n_conductors"] = 1 + len(bodies) - len(shorted) + r.info["n_conductors_raw"] = 1 + len(bodies) + metals = [G] + [b for i, b in enumerate(bodies) if i not in set(shorted)] + if len(metals) > 1: + gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) + r.info["min_gap_um"] = float(gap) + try: + r.info["geom_hash"] = geom_hash(path) + except Exception as e: # noqa: BLE001 + r.warn(f"geom_hash not computed: {e}") + return r + + +def conductor_count_qc(n_layout: int, net_order, subject: str = "") -> QCReport: + """The matrix must cover every conductor of the layout: N from the GDS (ground included) == len(net_order).""" + r = QCReport(subject) + if int(n_layout) != len(net_order): + r.error( + f"the layout has {n_layout} conductors (ground included) but the matrix has {len(net_order)} nets {list(net_order)}: " + "every conductor must be its own net (nets are never merged)" + ) + return r + + +# ---------------------------------------------------------------------------------------------------------------- dataset +def reference_hashes(db=None, local_dir=None, revision: str | None = None): + """``design_id`` / ``geom_hash`` / ``split`` of every design of the dataset (``PlanarCapacitanceDB``; HF or a local copy).""" + if db is None: + from .dataset import PlanarCapacitanceDB + + db = PlanarCapacitanceDB(revision=revision, local_dir=local_dir) + return db.read("designs", columns=["design_id", "geom_hash", "split"]) + + +def duplicate_qc(hashes: dict, reference=None, subject: str = "duplicates") -> QCReport: + """hashes: ``{design: geom_hash}`` of a batch; reference: a DataFrame with ``design_id``, ``geom_hash``, ``split`` (the + dataset), or None (only duplicates inside the batch are checked; warned). A duplicate of a ``test`` design is an error.""" + r = QCReport(subject) + seen: dict = {} + for d, h in hashes.items(): + if h is None: + continue + if h in seen: + r.warn(f"{d} has the same geometry as {seen[h]} in this batch") + else: + seen[h] = d + if reference is None: + r.warn("no dataset reference given: duplicates against SQuADDS_PlanarCapacitance were not checked") + return r + ref = reference[reference["geom_hash"].isin(set(seen))] + test_dups, other_dups = [], [] + for h, sub in ref.groupby("geom_hash"): + d = seen[h] + ids = sorted(map(str, sub["design_id"])) + if (sub["split"] == "test").any(): + test_dups.append(f"{d} = {ids[:3]}") + else: + other_dups.append(f"{d} = {ids[:3]} ({', '.join(sorted(set(map(str, sub['split']))))})") + if test_dups: + r.error(f"duplicate of a held-out test design (would leak its label): {test_dups}") + if other_dups: + r.warn(f"exact duplicates of dataset designs (kept, same group): {other_dups}") + r.info["dataset_duplicates"] = len(test_dups) + len(other_dups) + return r + + +def stack_qc(stack: dict, freq_GHz: float | None = None, subject: str = "stack") -> QCReport: + """eps_r in [1, 30], substrate in [5, 2000] um, frequency in [0.1, 50] GHz; a stack other than the training stack + (Si 11.45, 350 um) is accepted and recorded (warned: the released models are served for the training stack).""" + r = QCReport(subject) + vals = {"eps_r": stack.get("eps_r"), "substrate_um": stack.get("substrate_um"), "freq_GHz": freq_GHz} + for k, (lo, hi) in STACK_RANGES.items(): + v = vals.get(k) + if v is None: + if k != "freq_GHz": + r.error(f"stack field {k!r} missing") + continue + try: + v = float(v) + except (TypeError, ValueError): + r.error(f"stack field {k!r} is not a number: {v!r}") + continue + r.info[k] = v + if not lo <= v <= hi: + r.warn(f"{k} = {v:g} outside the usual range [{lo:g}, {hi:g}]") + eps, t = r.info.get("eps_r"), r.info.get("substrate_um") + if eps is not None and t is not None: + on = math.isclose(eps, TRAINING_STACK["eps_r"], rel_tol=1e-3) and math.isclose( + t, TRAINING_STACK["substrate_um"], rel_tol=1e-3 + ) + r.info["training_stack"] = on + if not on: + r.warn( + f"stack eps_r {eps:g}, {t:g} um differs from the training stack (Si 11.45, 350 um): recorded as off-stack" + ) + return r + + +def prior_sanity( + C_fF, + net_order, + gds, + layer_map: dict | None = None, + band=PRIOR_RATIO_BAND, + floor_fF: float = PRIOR_FLOOR_FF, + threads: int = 2, + prior=None, + subject: str = "physics sanity", +) -> QCReport: + """Ratio of each label entry to ``optimized_physics_prior`` of the layout (report only, never an error). + + The label's conductors (``net_order[1:]``) are matched to the layout's in GDS file order. Entries with ``|C| >= floor_fF`` + whose ratio falls outside ``band`` are warned. prior: a precomputed ``PriorResult`` (else computed here, needs [ml]).""" + r = QCReport(subject) + C = np.asarray(C_fF, float) + if prior is None: + try: + from . import priors + + lm = layer_map or DEFAULT_LAYERS + prior = priors.optimized_physics_prior( + str(gds), + threads=threads, + ground_layers=_layers(lm.get("ground", [])), + conductor_layers=_layers(lm.get("conductor", [])), + ) + except ImportError as e: + r.warn(f"physics sanity skipped (needs pip install 'squadds[ml]'): {e}") + return r + except Exception as e: # noqa: BLE001 + r.warn(f"physics sanity skipped: the prior could not be computed ({e})") + return r + P = np.asarray(prior.C_fF, float) + if P.shape != C.shape: + r.warn(f"physics sanity skipped: prior is {P.shape[0]} x {P.shape[0]}, label {C.shape[0]} x {C.shape[0]}") + return r + names = list(net_order) + with np.errstate(divide="ignore", invalid="ignore"): + ratio = C / P + iu = np.triu_indices(len(C)) + far = [] + for i, j in zip(*iu): + if abs(C[i, j]) < floor_fF or not np.isfinite(ratio[i, j]): + continue + if not band[0] <= ratio[i, j] <= band[1]: + far.append(f"{names[i]}-{names[j]}: label {C[i, j]:.4g} fF, prior {P[i, j]:.4g} fF (x{ratio[i, j]:.3g})") + mut = [(i, j) for i, j in zip(*iu) if i != j and abs(C[i, j]) >= floor_fF and np.isfinite(ratio[i, j])] + if mut: + rel = np.array([abs(ratio[i, j] - 1) for i, j in mut]) * 100 + r.info["prior_median_rel_diff_pct"] = float(np.median(rel)) + r.info["prior_mae_fF"] = float(np.mean([abs(C[i, j] - P[i, j]) for i, j in mut])) + r.info["prior_rmse_fF"] = float(np.sqrt(np.mean([(C[i, j] - P[i, j]) ** 2 for i, j in mut]))) + r.info["prior_version"] = getattr(prior, "prior_version", "") + r.info["prior_s"] = (getattr(prior, "timing_s", {}) or {}).get("total_s") + r.info["prior_machine"] = getattr(prior, "machine", "") + r.info["prior_threads"] = getattr(prior, "threads", None) + if far: + r.warn( + f"{len(far)} label entries outside x{band[0]:g}..x{band[1]:g} of the physics prior (check nets / units): {far[:5]}" + ) + return r diff --git a/src/squadds/ml/capacitance/result.py b/src/squadds/ml/capacitance/result.py new file mode 100644 index 0000000000000000000000000000000000000000..5616109aa720dca9fddda8ba4bafde42588e4a0f --- /dev/null +++ b/src/squadds/ml/capacitance/result.py @@ -0,0 +1,124 @@ +"""Prediction result: the full Maxwell capacitance matrix (fF, ground first) with checks, timing and provenance.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, field + +import numpy as np + +CONVENTION = "Maxwell matrix: diagonal = self, off-diagonal = -mutual (negative); row/column 0 = ground (G)" + + +def physical_checks(C) -> dict: + """Symmetry, Maxwell signs, closure (row sums of the signal rows >= 0) and positive definiteness of the signal block.""" + C = np.asarray(C, float) + n = len(C) + off = ~np.eye(n, dtype=bool) + scale = max(1.0, float(np.abs(C).max())) + sym = float(np.max(np.abs(C - C.T))) + rows = C.sum(1)[1:] + eig = float(np.linalg.eigvalsh(C[1:, 1:]).min()) if n > 1 else None + chk = { + "symmetric_max_abs": sym, + "symmetric": sym <= 1e-6 * scale, + "diagonal_positive": bool(np.all(np.diag(C) > 0)), + "offdiag_all_negative": bool(np.all(C[off] < 0)), + "closure_min_row_sum": float(rows.min()) if n > 1 else None, + "closure": bool(n == 1 or rows.min() >= -1e-9 * scale), + "signal_block_min_eig": eig, + "positive_definite": eig is None or eig > 0, + } + chk["passed"] = all( + chk[k] for k in ("symmetric", "diagonal_positive", "offdiag_all_negative", "closure", "positive_definite") + ) + return chk + + +def physical_warning(chk: dict) -> str | None: + """Readable warning when a check of ``physical_checks`` fails (None when the matrix passes).""" + if chk["passed"]: + return None + bad = [ + k.replace("_", " ") + for k in ("symmetric", "diagonal_positive", "offdiag_all_negative", "closure", "positive_definite") + if not chk[k] + ] + return ( + f"physical check failed: {', '.join(bad)} (smallest eigenvalue of the signal block {chk['signal_block_min_eig']:.4g} fF, " + f"smallest signal row sum {chk['closure_min_row_sum']:.4g} fF). This matrix is not physical: do not use it. A model that " + "solves the physics (flagship, or paper) is the safer choice, especially outside the trained component families." + ) + + +@dataclass +class CapacitanceResult: + names: list[str] + matrix_fF: np.ndarray + model: str + title: str = "" + prior_version: str | None = None + prior_stack: dict | None = None + weights_sha256: list[str] = field(default_factory=list) + learned_prior_sha256: str | None = None + timing_s: dict = field(default_factory=dict) + threads: int = 2 + machine: str = "" + checks: dict = field(default_factory=dict) + warnings: list[str] = field(default_factory=list) + substrate: dict = field(default_factory=dict) + ground_detection: dict | None = ( + None # pieces and roles when ground and conductors share a layer (see inspect_layout) + ) + source: str = "" + layout_hash: str = "" + cached: bool = False + package: str = "" + units: str = "fF" + convention: str = CONVENTION + + def __post_init__(self): + self.matrix_fF = np.asarray(self.matrix_fF, float) + if not self.checks: + self.checks = physical_checks(self.matrix_fF) + + @property + def n_conductors(self) -> int: + return len(self.names) + + def to_dataframe(self): + import pandas as pd + + return pd.DataFrame(self.matrix_fF, index=list(self.names), columns=list(self.names)) + + def to_dict(self) -> dict: + d = asdict(self) + d["matrix_fF"] = self.matrix_fF.tolist() + return d + + def to_sim_results(self, names: dict | None = None) -> dict: + """The SQuADDS_DB ``sim_results`` shape: pairwise positive magnitudes ``_to_`` (self terms on the diagonal, + ground named ``ground``), the signed ``maxwell_matrix`` as ``C__`` (ground ``G``) and ``units``. ``names`` renames + conductors (e.g. ``{"C1": "north", "C2": "south"}``).""" + names = names or {} + lab = [names.get(n, n) for n in self.names] + C = self.matrix_fF + sig = list(range(1, len(lab))) + out: dict = {} + for a in sig: + out[f"{lab[a]}_to_{lab[a]}"] = float(C[a, a]) + for b in sig: + if b > a: + out[f"{lab[a]}_to_{lab[b]}"] = float(abs(C[a, b])) + out[f"{lab[a]}_to_ground"] = float(abs(C[a, 0])) + out["ground_to_ground"] = float(C[0, 0]) + out["maxwell_matrix"] = { + f"C_{lab[i]}_{lab[j]}": float(C[i, j]) for i in range(len(lab)) for j in range(len(lab)) + } + out["units"] = "fF" + return out + + def __repr__(self) -> str: + return ( + f"CapacitanceResult({self.model}, N={self.n_conductors}, names={self.names}, " + f"total {self.timing_s.get('total_s', float('nan')):.3g} s, checks {'passed' if self.checks.get('passed') else 'FAILED'})" + ) diff --git a/src/squadds/ml/capacitance/serving.py b/src/squadds/ml/capacitance/serving.py new file mode 100644 index 0000000000000000000000000000000000000000..76e3533024a0c9edbe54191f24838cc6e2f5d7e9 --- /dev/null +++ b/src/squadds/ml/capacitance/serving.py @@ -0,0 +1,138 @@ +"""Serving adapter of the planar capacitance models for the SQuADDS ML API (registry family ``planar_capacitance``). + +The API Space imports ``squadds.ml.capacitance.serving:Adapter`` by its dotted path; nothing else imports this module. +``root`` is a verified local copy of the model repository (the repository layout, e.g. ``/accurate/acc_v2m_sf_s0.pt``). +""" + +from __future__ import annotations + +import tempfile +import time +from pathlib import Path + +from pydantic import BaseModel, ConfigDict, Field + +from . import _runtime as RT +from .models import load_model +from .predictor import CapacitancePredictor + +CONVENTION = "Maxwell matrix, ground first (row and column 0), nets never merged" + + +class TooLarge(ValueError): + too_large = True + + +class CapacitanceInputs(BaseModel): + model_config = ConfigDict(extra="forbid") + + ground_layer: str = Field("1/0", description="GDS layer/datatype of the ground plane") + conductor_layer: str = Field("1/10", description="GDS layer/datatype of the conductors") + eps_r: float = Field(RT.TRAIN_EPS_R, gt=0, description="Substrate relative permittivity") + thickness_um: float = Field(RT.TRAIN_THICKNESS_UM, gt=0, description="Substrate thickness in µm") + ground_pieces: str = Field( + "", + description="Only when ground and conductors share a layer and the automatic ground pick is wrong: the ground's " + "piece numbers, e.g. '1' or '1,4'", + ) + file_base64: str | None = Field( + None, description="The GDS file, base64 encoded (JSON requests; multipart requests send it as the field 'file')" + ) + + +def _layer(text: str) -> tuple[int, int]: + try: + layer, dtype = (int(x) for x in text.strip().split("/")) + except ValueError as exc: + raise ValueError(f"layer must look like '1/0', got {text!r}") from exc + return layer, dtype + + +class Adapter: + input_kind = "file" + InputModel = CapacitanceInputs + + def __init__(self, model_id: str, root: Path, config: dict, limits: dict): + self.model_id = model_id + self.model = load_model(config.get("model", "flagship"), path=root) + self.threads = int(config.get("threads", 2)) + self.predictor = CapacitancePredictor(self.model, threads=self.threads) + self.max_conductors = int(limits.get("max_conductors", 70)) + + def describe(self) -> dict: + e = self.model.entry + return { + "input": "a GDS file (multipart field 'file', or inputs.file_base64 in a JSON request) and the layer and " + "substrate fields", + "output": "names (G first, then C1..Cn in file order), matrix_fF (N x N), sim_results (the SQuADDS_DB shape)", + "units": "fF", + "convention": CONVENTION, + "model": { + "name": self.model.name, + "paper_name": e.get("paper_name"), + "title": e.get("title"), + "summary": e.get("summary"), + "warning": e.get("warning"), + "repo_id": self.model.repo_id, + "revision": self.model.revision, + "weights_sha256": self.model.weights_sha256, + }, + "training_stack": "350 µm silicon substrate (eps_r 11.45), zero-thickness metal", + "tested_substrates": "Si at 10-1000 µm, or eps_r 3.8-24 at 350 µm (other combinations warn)", + "threads": self.threads, + } + + def predict(self, inputs, file: bytes | None = None, options: dict | None = None) -> dict: + p = CapacitanceInputs.model_validate(inputs or {}) + if not file: + raise ValueError("no GDS file: send it as the multipart field 'file' or as inputs.file_base64") + kwargs = {"ground_layers": (_layer(p.ground_layer),), "conductor_layers": (_layer(p.conductor_layer),)} + if p.ground_pieces.strip(): + try: + kwargs["ground_pieces"] = [int(x) for x in p.ground_pieces.split(",")] + except ValueError as exc: + raise ValueError(f"ground_pieces must look like '1' or '1,4', got {p.ground_pieces!r}") from exc + t = time.perf_counter() + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "layout.gds" + path.write_bytes(file) + try: + lay = RT.prepare_layout(str(path), max_conductors=10**9, **kwargs) + except (ValueError, OSError, RuntimeError) as exc: + raise ValueError(f"could not read this layout: {exc}") from exc + prepare_s = time.perf_counter() - t + if len(lay.names) > self.max_conductors: + raise TooLarge(f"{len(lay.names)} conductors found; this server takes at most {self.max_conductors} plus ground") + res = self.predictor.predict(lay, eps_r=p.eps_r, thickness_um=p.thickness_um) + tm = res.timing_s + meta = { + "n_conductors": res.n_conductors, + "checks": res.checks, + "warnings": list(res.warnings), + "substrate": res.substrate, + "ground_detection": res.ground_detection, + "threads": res.threads, + "prior_version": res.prior_version, + "weights_sha256": list(res.weights_sha256), + } + if res.learned_prior_sha256: + meta["learned_prior_sha256"] = res.learned_prior_sha256 + return { + "outputs": { + "names": list(res.names), + "matrix_fF": res.matrix_fF.tolist(), + "units": "fF", + "convention": CONVENTION, + "sim_results": res.to_sim_results(), + }, + "metadata": meta, + "timing_s": { + "prepare": prepare_s, + "geometry": tm["geometry_s"], + "prior": tm["prior_s"], + "networks": tm["network_s"], + }, + } + + def warm(self, example: Path) -> None: + self.predict({}, file=Path(example).read_bytes()) diff --git a/src/squadds/ml/capacitance/slurm.py b/src/squadds/ml/capacitance/slurm.py new file mode 100644 index 0000000000000000000000000000000000000000..0beb9adfcaa34e120d55ee0cd717879275079b4c --- /dev/null +++ b/src/squadds/ml/capacitance/slurm.py @@ -0,0 +1,83 @@ +"""A generic SLURM array script for retraining (one seed per array task). No site-specific accounts, partitions or tooling: +pass your own, or leave them out and let your cluster's defaults apply.""" + +from __future__ import annotations + +import shlex +import sys +from pathlib import Path + + +def write_slurm_array( + out_path, + shard_dir, + seeds=(0, 1, 2), + out_dir=None, + partition: str | None = None, + account: str | None = None, + cpus: int = 2, + time: str = "01:00:00", + mem: str = "6G", + python: str = sys.executable, + arm: str = "full_gnn", + steps: int = 18000, + device: str = "cpu", + gpus: int = 0, + job_name: str = "squadds-ml-train", + extra_sbatch: tuple = (), + setup: str = "", +) -> Path: + """Write ``out_path``: ``sbatch out_path`` trains ``seeds`` (array task k -> seeds[k]) on ``shard_dir`` into + ``out_dir/s`` with ``cpus`` threads each. ``setup``: shell lines run before training (e.g. ``module load ...``, + ``source venv/bin/activate``). Returns the path.""" + seeds = [int(s) for s in seeds] + if not seeds: + raise ValueError("no seeds") + shard_dir = Path(shard_dir).resolve() + out_dir = Path(out_dir).resolve() if out_dir else shard_dir.parent / "runs" + out_path = Path(out_path) + log_dir = out_dir / "logs" + lines = [ + "#!/bin/bash", + f"#SBATCH --job-name={job_name}", + f"#SBATCH --array=0-{len(seeds) - 1}", + "#SBATCH --ntasks=1", + f"#SBATCH --cpus-per-task={int(cpus)}", + f"#SBATCH --mem={mem}", + f"#SBATCH --time={time}", + f"#SBATCH --output={log_dir}/%x_%A_%a.out", + ] + if partition: + lines.append(f"#SBATCH --partition={partition}") + if account: + lines.append(f"#SBATCH --account={account}") + if gpus: + lines.append(f"#SBATCH --gpus={int(gpus)}") + lines += [f"#SBATCH {x}" for x in extra_sbatch] + lines += [ + "set -euo pipefail", + *([setup] if setup else []), + f"export OMP_NUM_THREADS={int(cpus)} MKL_NUM_THREADS={int(cpus)} OPENBLAS_NUM_THREADS={int(cpus)}", + f"SEEDS=({' '.join(map(str, seeds))})", + "SEED=${SEEDS[$SLURM_ARRAY_TASK_ID]}", + f"mkdir -p {shlex.quote(str(out_dir))}", + " ".join( + [ + shlex.quote(python), + "-m squadds.ml.capacitance.train", + f"--data {shlex.quote(str(shard_dir))}", + f"--out {shlex.quote(str(out_dir))}", + f"--arm {arm}", + '--seeds "$SEED"', + f"--steps {int(steps)}", + f"--threads {int(cpus)}", + f"--device {device}", + ] + ), + "", + ] + out_path.parent.mkdir(parents=True, exist_ok=True) + log_dir.mkdir(parents=True, exist_ok=True) + out_path.write_text("\n".join(lines)) + out_path.chmod(0o755) + return out_path diff --git a/src/squadds/ml/capacitance/train.py b/src/squadds/ml/capacitance/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2132065eb02e47a9edf2bbbffcbed547904fc6aa --- /dev/null +++ b/src/squadds/ml/capacitance/train.py @@ -0,0 +1,721 @@ +"""Retraining the planar-capacitance networks on your own compute (laptop CPU, GPU box or cluster). + +- ``fit``: the paper recipe (P2d ``full_gnn``) on a shard dir, one seed. Every hyperparameter is in ``TrainConfig``. +- ``fit_seeds``: several seeds, in parallel processes (or SLURM array tasks: ``squadds.ml.capacitance.slurm``). +- ``fit_in_family``: from scratch on k of your designs, cross-validated against the zero-shot released model; zero-shot is + always a candidate and wins ties. +- ``retrain_collective``: your designs added to the all-data training set, 3 seeds (the flagship recipe). +- ``trained_model``: a trained run (or several seeds) as a ``CapacitanceModel`` for ``CapacitancePredictor``. + +The fit loop is the tl-squadds reference (``scripts/geomfast/ragged.py fit`` + the flagship's NaN-label masking, +``scripts/flagship_v4/ragged_fv4.py``) statement for statement. The released fits ran in ``RELEASE_ENVIRONMENT`` (Linux +aarch64 on the GH200 node, CPU, 2 threads, its torch and numpy); a run is expected to reproduce them bit for bit only in +that environment. Other machines, thread counts, devices or library versions drift slightly (gate iii: numpy alone moves +the trajectory). The checkpoint records ``environment``, ``release_environment_match`` and the differences +(``release_environment_diff``); ``bit_identical_to_release`` is kept as an alias of ``release_environment_match``. +""" + +from __future__ import annotations + +import argparse +import dataclasses +import hashlib +import json +import os +import platform +import sys +import time +from dataclasses import asdict, dataclass, field +from pathlib import Path + +import numpy as np + +ARMS = ("full_gnn", "direct_gnn", "full_mlp", "pair_mlp") + + +@dataclass(frozen=True) +class TrainConfig: + """The paper recipe (paper_v4 Sec. 2.3-2.4). Defaults = the released models; change them knowingly.""" + + steps: int = 18000 + lr: float = 1e-3 + weight_decay: float = 1e-4 + lr_min: float = 1e-5 + grad_clip: float = 5.0 + huber_delta: float = 0.05 + w_signal_self: float = 0.1 + w_ground_self: float = 0.02 + max_batch: int = 64 + pair_budget: int = 8192 + width: int = 64 + standardise_clip: float = 10.0 + log_every: int = 500 + # fixed in the network (squadds.ml.capacitance.network): residual bound +-0.2 in log, message-passing rounds 2 (gnn arms) + + +def _digest(p) -> str: + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +def _rounds(arm: str) -> int: + return 2 if arm.endswith("gnn") else 0 + + +# Environment of the released fits (paper seed-0 and flagship runs: host c02-13, Endeavour GH200, env tlsq-arm; versions +# from /project2/shaas_31/shanto/envs/tlsq-arm.freeze.txt, 2026-10-14). torch is compared without its local build tag. +RELEASE_ENVIRONMENT = { + "machine": "aarch64", + "system": "Linux", + "device": "cpu", + "threads": 2, + "torch": "2.6.0+cu126", + "numpy": "2.5.3", + "host": "c02-13 (Endeavour GH200)", + "env": "tlsq-arm", +} + + +def training_environment(device: str, threads: int) -> dict: + import torch + + return { + "machine": platform.machine().lower(), + "system": platform.system(), + "device": device, + "threads": int(threads), + "torch": torch.__version__, + "numpy": np.__version__, + } + + +def release_environment_diff(device: str, threads: int, config: TrainConfig, env: dict | None = None) -> list[str]: + """What differs from the released fits' environment and recipe (empty = same environment).""" + env = env or training_environment(device, threads) + rel = RELEASE_ENVIRONMENT + diff = [ + f"{k}: {env.get(k)!r} (release {rel[k]!r})" + for k in ("machine", "system", "device", "threads", "numpy") + if env.get(k) != rel[k] + ] + if str(env.get("torch")).split("+")[0] != rel["torch"].split("+")[0]: + diff.append(f"torch: {env.get('torch')!r} (release {rel['torch']!r})") + if config != TrainConfig(): + diff.append("config: not the default recipe") + return diff + + +def release_eligible(device: str, threads: int, config: TrainConfig, env: dict | None = None) -> bool: + """True when the run matches the released fits' environment (``RELEASE_ENVIRONMENT``) and the default recipe: the only + setting in which a bit-for-bit reproduction of the released checkpoints is expected.""" + return not release_environment_diff(device, threads, config, env) + + +def _resolve_device(device: str) -> str: + import torch + + if device == "cuda" and not torch.cuda.is_available(): + raise RuntimeError("device='cuda' requested but torch.cuda is not available") + if device == "mps" and not torch.backends.mps.is_available(): + raise RuntimeError("device='mps' requested but the MPS backend is not available") + if device not in ("cpu", "cuda", "mps") and not device.startswith("cuda:"): + raise ValueError(f"device {device!r}: use 'cpu', 'cuda', 'cuda:' or 'mps'") + return device + + +def fit( + shard_dir, + out_dir, + arm: str = "full_gnn", + seed: int = 0, + config: TrainConfig = TrainConfig(), + device: str = "cpu", + threads: int = 2, + validate: bool = True, + verbose: bool = True, +) -> dict: + """Train one network from scratch on the ``split == "train"`` rows of a shard dir; writes ``out_dir/model.pt`` (loadable by + ``trained_model`` / ``CapacitancePredictor``), ``run.json`` and, with ``validate``, ``metrics.csv`` / ``val_score.json`` on + the ``val`` rows. Returns the run record.""" + import torch + from torch.nn import functional as F + + from . import _runtime as RT + from .network import build_model + + if arm not in ARMS: + raise ValueError(f"arm {arm!r} not in {ARMS}") + device = _resolve_device(device) + threads = RT.configure(threads) + cfg = config + torch.manual_seed(seed) + rng = np.random.default_rng(seed) + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=False) + root = Path(shard_dir) + schema = json.loads((root / "schema.json").read_text()) + ds = [dict(np.load(p, allow_pickle=False)) for p in sorted(root.glob("n*.npz"))] + if not ds: + raise FileNotFoundError(f"no n*.npz shards in {root}") + direct = arm == "direct_gnn" + full = arm != "pair_mlp" + rounds = _rounds(arm) + ni = schema["nodekeys"].index("role_ground") + ei = schema["edgekeys"].index("is_ground_pair") + scales, centers, closure = {}, {}, {} + train_keys = [str(k) for d in ds for k in d["key"][d["split"] == "train"]] + if not train_keys: + raise ValueError(f"no split == 'train' rows in {root}") + if len(train_keys) != len(set(train_keys)): + raise ValueError("duplicate training keys") + for flag in [0, 1]: + vals, bs = [], [] + for d in ds: + tr = d["split"] == "train" + i, j = d["pairs"].T + mask = (d["E"][:, :, ei] == flag) & tr[:, None] + cv = np.log((-d["C"][:, i, j][mask]).clip(1e-12)) + vals.extend(cv[np.isfinite(cv)].tolist()) + bmask = (d["sig"] == bool(flag)) & tr[:, None] + bv = np.log(d["C"].sum(-1).clip(1e-8)[bmask]) + bs.extend(bv[np.isfinite(bv)].tolist()) + centers[str(flag)] = float(np.median(vals)) if vals else 0.0 + closure[str(flag)] = float(np.median(bs)) if bs else 0.0 + for d in ds: + d["kind"] = d["E"][:, :, ei].copy() + d["base"] = 2 * np.log(d["pri"][:, :, 1]) - np.log(d["pri"][:, :, 0]) + if direct: + d["base"] = np.where(d["kind"] == 0, centers["0"], centers["1"]).astype(np.float32) + else: + d["E"] = np.concatenate([d["E"], np.log(d["pri"][:, :, 1:] / d["pri"][:, :, :1])], -1) + if not full: + d["X"] = d["X"][:, :, [ni]] + d["G"] = np.zeros((len(d["G"]), 1), np.float32) + d["bbase"] = np.where(d["sig"], closure["1"], closure["0"]).astype(np.float32) + for name in ["X", "E", "G"]: + v = np.concatenate([d[name][d["split"] == "train"].reshape(-1, d[name].shape[-1]) for d in ds]) + med = np.nanmedian(v, 0) + iq = np.nanpercentile(v, 75, 0) - np.nanpercentile(v, 25, 0) + iq = np.where(iq > 1e-6, iq, 1) + scales[name] = dict(median=med.tolist(), iqr=iq.tolist()) + if not (np.isfinite(med).all() and np.isfinite(iq).all()): + raise ValueError(f"non-finite standardisation of {name}") + c = cfg.standardise_clip + for d in ds: + d[name] = np.clip((np.where(np.isfinite(d[name]), d[name], med) - med) / iq, -c, c).astype(np.float32) + tensors, groups = [], {} + for k, d in enumerate(ds): + z = {n: torch.from_numpy(d[n]).to(device) for n in ["X", "E", "G", "C", "sig", "pairs", "base", "bbase"]} + z["M"] = torch.ones(d["sig"].shape, dtype=torch.bool, device=device) + z["PM"] = torch.ones(d["base"].shape, dtype=torch.bool, device=device) + tensors.append(z) + for fam in set(d["family"]): + idx = np.flatnonzero((d["family"] == fam) & (d["split"] == "train")) + if len(idx): + groups.setdefault(fam, []).append((k, idx)) + families = sorted(groups) + model = build_model(ds[0]["X"].shape[-1], ds[0]["E"].shape[-1], ds[0]["G"].shape[-1], rounds, width=cfg.width).to( + device + ) + opt = torch.optim.AdamW(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay) + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, cfg.steps, eta_min=cfg.lr_min) + + def forward(k, b): + z = tensors[k] + return model( + z["X"][b], z["E"][b], z["G"][b], z["M"][b], z["PM"][b], z["pairs"], z["base"][b], z["bbase"][b], direct + ) + + hist = [] + start = time.perf_counter() + for step in range(cfg.steps): + fam = families[rng.integers(len(families))] + gs = groups[fam] + w = np.array([len(v) for k, v in gs]) + k, idx = gs[rng.choice(len(gs), p=w / w.sum())] + z = tensors[k] + pairs = z["pairs"] + i, j = pairs.T + batch = max(1, min(cfg.max_batch, cfg.pair_budget // len(pairs))) + b = rng.choice(idx, batch) + pred, logc = forward(k, b) + C = z["C"][b] + tm = (-C[:, i, j]).clamp_min(1e-12).log() + fm = torch.isfinite(tm) + if bool(fm.all()): + pl = F.huber_loss(logc, tm, delta=cfg.huber_delta) + else: + pl = F.huber_loss(logc[fm], tm[fm], delta=cfg.huber_delta) if bool(fm.any()) else logc.new_zeros(()) + dl = F.huber_loss( + pred.diagonal(dim1=-2, dim2=-1).log(), + C.diagonal(dim1=-2, dim2=-1).log(), + delta=cfg.huber_delta, + reduction="none", + ) + sig = z["sig"][b] + fin = torch.isfinite(C.diagonal(dim1=-2, dim2=-1)) + if bool(fin.all()): + loss = pl + cfg.w_signal_self * dl[sig].mean() + cfg.w_ground_self * dl[~sig].mean() + else: + # unknown self labels: finite placeholder targets (masked below) so no NaN reaches the gradient + cd = C.diagonal(dim1=-2, dim2=-1) + dl = F.huber_loss( + pred.diagonal(dim1=-2, dim2=-1).log(), + torch.where(fin, cd, torch.ones_like(cd)).log(), + delta=cfg.huber_delta, + reduction="none", + ) + ms, mg = sig & fin, ~sig & fin + ls = dl[ms].mean() if bool(ms.any()) else dl.new_zeros(()) + lg = dl[mg].mean() if bool(mg.any()) else dl.new_zeros(()) + loss = pl + cfg.w_signal_self * ls + cfg.w_ground_self * lg + if not torch.isfinite(loss): + raise FloatingPointError(f"non-finite loss at step {step} (family {fam})") + opt.zero_grad() + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip) + opt.step() + sched.step() + if step % cfg.log_every == 0: + hist.append(dict(step=step, loss=float(loss.detach()), seconds=time.perf_counter() - start)) + if verbose: + print(hist[-1], flush=True) + train_s = time.perf_counter() - start + from squadds import __version__ + + model = model.to("cpu") + ck = dict( + state=model.state_dict(), + arm=arm, + rounds=rounds, + scales=scales, + schema=schema, + closure_intercepts=closure, + direct_intercepts=centers, + train_keys=train_keys, + seed=seed, + data_sha={p.name: _digest(p) for p in root.glob("*.npz")}, + code_sha=_digest(__file__), + steps=cfg.steps, + config=asdict(cfg), + machine=RT.machine(), + device=device, + threads=threads, + torch_version=torch.__version__, + package_version=f"squadds {__version__}", + environment=training_environment(device, threads), + release_environment=dict(RELEASE_ENVIRONMENT), + release_environment_diff=release_environment_diff(device, threads, cfg), + train_seconds=train_s, + ) + ck["release_environment_match"] = not ck["release_environment_diff"] + ck["bit_identical_to_release"] = ck["release_environment_match"] + torch.save(ck, out / "model.pt") + run = dict( + arm=arm, + seed=seed, + steps=cfg.steps, + data=str(root), + host=platform.node(), + machine=RT.machine(), + device=device, + threads=threads, + train_seconds=train_s, + environment=ck["environment"], + release_environment_match=ck["release_environment_match"], + release_environment_diff=ck["release_environment_diff"], + bit_identical_to_release=ck["bit_identical_to_release"], + config=asdict(cfg), + history=hist, + ) + if validate and any((d["split"] == "val").any() for d in ds): + from .benchmark import score + + rep = score(ck, root, split="val", threads=threads, name=f"{arm} seed {seed}") + rep.by_family.to_csv(out / "metrics.csv", index=False) + (out / "val_score.json").write_text(json.dumps(rep.to_dict(), indent=1)) + run["val"] = rep.headline() + (out / "run.json").write_text(json.dumps(run, indent=1)) + if verbose: + print("DONE", arm, seed, f"{train_s:.1f} s", run.get("val", ""), flush=True) + return run + + +def _fit_job(kw): + return fit(**kw) + + +def fit_seeds( + shard_dir, + out_dir, + seeds=(0, 1, 2), + processes: int = 1, + arm: str = "full_gnn", + config: TrainConfig = TrainConfig(), + device: str = "cpu", + threads: int = 2, + validate: bool = True, + verbose: bool = False, +) -> list[dict]: + """``fit`` for each seed into ``out_dir/s``; ``processes`` seeds at a time (spawned processes, ``threads`` each).""" + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=True) + jobs = [ + dict( + shard_dir=str(shard_dir), + out_dir=str(out / f"s{s}"), + arm=arm, + seed=int(s), + config=config, + device=device, + threads=threads, + validate=validate, + verbose=verbose, + ) + for s in seeds + ] + if processes <= 1 or len(jobs) == 1: + return [fit(**j) for j in jobs] + from concurrent.futures import ProcessPoolExecutor + from multiprocessing import get_context + + with ProcessPoolExecutor(min(processes, len(jobs)), mp_context=get_context("spawn")) as ex: + return list(ex.map(_fit_job, jobs)) + + +def trained_model(runs, name: str = "user", title: str | None = None): + """A ``CapacitanceModel`` (ensemble mean over the given runs) for ``CapacitancePredictor``: run dirs or ``model.pt`` paths. + Prior-based arms run on the corrected prior stack (the one the released models serve); the embedding is exact.""" + import torch + + from .benchmark import checkpoint_paths + from .models import CapacitanceModel, sha256_file + + paths = [p.resolve() for p in checkpoint_paths(list(runs) if isinstance(runs, (list, tuple)) else runs)] + cks = [torch.load(p, map_location="cpu", weights_only=False) for p in paths] + arms = {c["arm"] for c in cks} + if len(arms) != 1: + raise ValueError(f"runs mix arms {arms}") + arm = arms.pop() + root = Path(os.path.commonpath([str(p.parent) for p in paths])) + shas = [sha256_file(p) for p in paths] + key = f"{name}-{hashlib.sha256(''.join(shas).encode()).hexdigest()[:8]}" + entry = { + "title": title or f"{name}: {arm} x{len(paths)} (user-trained)", + "kind": "gnn", + "arm": arm, + "stack": None if arm == "direct_gnn" else "corrected", + "checkpoints": [ + {"name": p.parent.name, "path": str(p.relative_to(root)), "sha256": h} for p, h in zip(paths, shas) + ], + "trained": [ + { + k: c.get(k) + for k in ( + "seed", + "steps", + "machine", + "device", + "threads", + "release_environment_match", + "bit_identical_to_release", + ) + } + for c in cks + ], + } + if arm != "direct_gnn": + entry["ppg"] = [1.5, 3.0] + return CapacitanceModel(key, entry, root, "local", None, shas) + + +# ---------------------------------------------------------------------------------------------------------------- in family +def _base_model(base): + from .models import CapacitanceModel, load_model + + if isinstance(base, CapacitanceModel): + return base + if isinstance(base, str) and base in ("flagship", "paper"): + return load_model(base) + return trained_model(base, name="base") + + +def _folds(keys: list[str], k_folds: int, seed: int) -> list[list[str]]: + keys = sorted(keys) + perm = np.random.default_rng(seed).permutation(len(keys)) + k = max(2, min(int(k_folds), len(keys))) + return [[keys[i] for i in perm[f::k]] for f in range(k)] + + +@dataclass +class InFamilyResult: + chosen: str + model: object + report: object + decision: dict + out_dir: str + timing: dict = field(default_factory=dict) + + def __str__(self) -> str: + return f"in-family CV ({self.decision['layouts']} designs): chosen = {self.chosen}; {self.decision['rule']}" + + +def fit_in_family( + designs, + out_dir, + k_folds: int = 5, + base="flagship", + seed: int = 0, + config: TrainConfig = TrainConfig(), + device: str = "cpu", + threads: int = 2, + processes: int = 1, + final_seeds=(0,), + margin_pp: float = 0.25, + margin_fF: float = 0.05, + n_boot: int = 2000, + family: str = "user", + build_kwargs: dict | None = None, +) -> InFamilyResult: + """From-scratch training on your k designs, cross-validated against the zero-shot ``base`` model. + + designs: Design objects / dicts (built here with ``build_shards``) or an existing shard dir (every row used). k-fold CV + (deterministic folds from ``seed``): each fold is predicted by a network trained from scratch on the other folds, and by + the zero-shot base on the same stored embedding and priors. The from-scratch recipe is chosen only if it is materially + better (paired layout-bootstrap 95% interval of the layout-mean difference excludes zero AND the gain exceeds ``margin_pp`` + percentage points of median error or ``margin_fF`` of MAE: the paper's equivalence rule); otherwise the zero-shot model + is kept (it wins ties). The chosen from-scratch model is then trained on all k designs (``final_seeds``). + Reported per entry kind: layout-mean median %, MAE and RMSE (fF), with time, machine and threads.""" + import pandas as pd + + from .benchmark import layout_rows, load_checkpoints, paired_difference, predict_arrays, summarize + from .training_data import build_shards, read_schema, read_shards, subset_shards + + t0 = time.perf_counter() + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=False) + if isinstance(designs, (str, Path)) and Path(designs).is_dir(): + data = subset_shards(designs, out / "data", keep=lambda d: np.ones(len(d["key"]), bool)) + else: + from .training_data import as_design + + ds = [dataclasses.replace(as_design(x), family=family, split="train") for x in designs] + build_shards(ds, out / "data", threads=threads, **(build_kwargs or {})) + data = out / "data" + t_build = time.perf_counter() - t0 + schema = read_schema(data) + shards = read_shards(data) + keys = [str(k) for d in shards for k in d["key"]] + if len(keys) < 2: + raise ValueError("in-family CV needs at least 2 designs") + folds = _folds(keys, k_folds, seed) + jobs = [] + for f, val in enumerate(folds): + sub = subset_shards( + data, out / "folds" / f"f{f}" / "data", train_keys=[k for k in keys if k not in set(val)], val_keys=val + ) + jobs.append( + dict( + shard_dir=str(sub), + out_dir=str(out / "folds" / f"f{f}" / "run"), + arm="full_gnn", + seed=seed, + config=config, + device=device, + threads=threads, + validate=False, + verbose=False, + ) + ) + t1 = time.perf_counter() + if processes > 1: + from concurrent.futures import ProcessPoolExecutor + from multiprocessing import get_context + + with ProcessPoolExecutor(min(processes, len(jobs)), mp_context=get_context("spawn")) as ex: + runs = list(ex.map(_fit_job, jobs)) + else: + runs = [fit(**j) for j in jobs] + t_cv = time.perf_counter() - t1 + bm = _base_model(base) + zs = load_checkpoints(bm, threads) + rows = {"zero-shot": [], "from-scratch": []} + for f, val in enumerate(folds): + fm = load_checkpoints(Path(jobs[f]["out_dir"]), threads) + for d in shards: + ix = np.flatnonzero(np.isin(d["key"].astype(str), val)) + if not len(ix): + continue + for arm, mods in (("zero-shot", zs), ("from-scratch", fm)): + P = predict_arrays(mods, d, schema, ix) + for b, p in zip(ix, P): + rows[arm] += layout_rows( + d["C"][b].astype(float), p, d["sig"][b], d["pairs"], str(d["key"][b]), family + ) + L = {a: pd.DataFrame(r) for a, r in rows.items()} + tabs = [] + for a, frame in L.items(): + _, tot = summarize(frame) + tot.insert(0, "candidate", a) + tabs.append(tot) + report = pd.concat(tabs, ignore_index=True) + diff = paired_difference(L["from-scratch"], L["zero-shot"], n_boot=n_boot, seed=seed) + dm, dmae = diff["median_pct"], diff["mae_fF"] + better = (dm["hi"] < 0 and -dm["diff"] > margin_pp) or (dmae["hi"] < 0 and -dmae["diff"] > margin_fF) + chosen = "from-scratch" if better else "zero-shot" + decision = dict( + layouts=len(keys), + folds=len(folds), + paired_from_scratch_minus_zero_shot=diff, + margin_pp=margin_pp, + margin_fF=margin_fF, + rule="from-scratch only if materially better (95% interval excludes zero and the gain exceeds the margin); " + "zero-shot wins ties", + chosen=chosen, + base=bm.key, + ) + t2 = time.perf_counter() + if chosen == "from-scratch": + fit_seeds( + data, + out / "final", + seeds=final_seeds, + processes=processes, + config=config, + device=device, + threads=threads, + validate=False, + ) + model = trained_model([out / "final" / f"s{s}" for s in final_seeds], name=f"{family}-in-family") + else: + model = bm + from ._runtime import machine + + timing = dict( + build_s=t_build, + cv_fits_s=t_cv, + per_fit_s=[r["train_seconds"] for r in runs], + final_s=time.perf_counter() - t2, + total_s=time.perf_counter() - t0, + threads=threads, + processes=processes, + device=device, + machine=machine(), + ) + report.to_csv(out / "cv_report.csv", index=False) + pd.concat([f.assign(candidate=a) for a, f in L.items()]).to_csv(out / "cv_layouts.csv", index=False) + (out / "decision.json").write_text(json.dumps(dict(decision=decision, timing=timing), indent=1, default=str)) + return InFamilyResult(chosen, model, report, decision, str(out), timing) + + +def retrain_collective( + user_shards, + base_shards, + out_dir, + seeds=(0, 1, 2), + processes: int = 1, + config: TrainConfig = TrainConfig(), + device: str = "cpu", + threads: int = 2, +): + """Your shards added to the all-data training set (``base_shards``: the flagship shard dir, i.e. the dataset's + ``model_input`` on the corrected prior), every row trained on, ``seeds`` networks from scratch (flagship recipe). + Returns (CapacitanceModel of the ensemble, run records).""" + from .training_data import merge_shards + + if base_shards is None: + raise NotImplementedError( + "base_shards=None: download the dataset's model_input table and convert it with " + "training_data.shards_from_model_input (the release download is not wired yet)" + ) + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=False) + data = merge_shards(base_shards, user_shards, out / "data", all_split="train") + runs = fit_seeds( + data, + out / "runs", + seeds=seeds, + processes=processes, + config=config, + device=device, + threads=threads, + validate=False, + ) + return trained_model([out / "runs" / f"s{s}" for s in seeds], name="collective"), runs + + +# ---------------------------------------------------------------------------------------------------------------- CLI +def add_train_subcommand(sub) -> None: + """Register ``squadds-ml train`` on an argparse subparsers object (for ``cli.py``).""" + p = sub.add_parser("train", help="retrain the capacitance networks on a shard dir (paper recipe)") + p.add_argument("--data", required=True, help="shard dir (n0NN.npz + schema.json)") + p.add_argument("--out", required=True, help="output dir (one sub-dir per seed)") + p.add_argument("--arm", default="full_gnn", choices=ARMS) + p.add_argument("--seeds", default="0", help="comma-separated seeds, e.g. 0,1,2") + p.add_argument("--steps", type=int, default=TrainConfig.steps) + p.add_argument("--threads", type=int, default=2) + p.add_argument("--processes", type=int, default=1) + p.add_argument("--device", default="cpu") + p.add_argument("--no-validate", action="store_true") + p.add_argument("--slurm", default=None, help="write a SLURM array script here instead of training") + p.add_argument("--partition", default=None) + p.add_argument("--account", default=None) + p.add_argument("--time", default="01:00:00") + p.add_argument("--seed-index", type=int, default=None, help="train only seeds[k] (SLURM array task)") + p.set_defaults(func=cmd_train) + + +def cmd_train(a) -> int: + seeds = [int(s) for s in str(a.seeds).split(",") if s != ""] + if a.slurm: + from .slurm import write_slurm_array + + path = write_slurm_array( + a.slurm, + a.data, + seeds, + out_dir=a.out, + partition=a.partition, + account=a.account, + cpus=a.threads, + time=a.time, + arm=a.arm, + steps=a.steps, + device=a.device, + ) + print(f"wrote {path}: sbatch {path}") + return 0 + if a.seed_index is not None: + seeds = [seeds[a.seed_index]] + cfg = TrainConfig(steps=a.steps) + runs = fit_seeds( + a.data, + a.out, + seeds=seeds, + processes=a.processes, + arm=a.arm, + config=cfg, + device=a.device, + threads=a.threads, + validate=not a.no_validate, + verbose=a.processes <= 1, + ) + for r in runs: + print( + json.dumps( + {k: r[k] for k in ("arm", "seed", "steps", "train_seconds", "machine", "threads", "device") if k in r} + | ({"val": r["val"]} if "val" in r else {}) + ) + ) + return 0 + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(prog="python -m squadds.ml.capacitance.train") + sub = ap.add_subparsers(dest="cmd", required=True) + add_train_subcommand(sub) + a = ap.parse_args(["train", *(argv if argv is not None else sys.argv[1:])]) + return a.func(a) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/squadds/ml/capacitance/training_data.py b/src/squadds/ml/capacitance/training_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c5445a5915376caff110dd2ccaabfa85120c84 --- /dev/null +++ b/src/squadds/ml/capacitance/training_data.py @@ -0,0 +1,741 @@ +"""Training data of the planar-capacitance networks: the P2d shard layout, label reading and QC, and shard builders. + +A shard directory holds one ``n0NN.npz`` per conductor count N (ground included) and ``schema.json``. Arrays per file +(L layouts, P = N(N-1)/2 pairs ``i < j``): + + key (L,) str split (L,) str family (L,) str + X (L, N, 61) f32 node vector (60 features + missing_log_min_halfwidth), node 0 = ground G + E (L, P, 42) f32 pair vector G (L, 4) f32 global vector + C (L, N, N) f32 Maxwell matrix in fF, ground first (NaN = unknown entry, masked in training) + sig (L, N) bool signal mask pri (L, P, 2) f32 positive prior mutuals (fF) at 1.5 and 3 panels per gap + pairs (P, 2) int + +``build_shards`` turns layouts (GDS) and their labels (a Maxwell matrix with net names, or a Q3D ``cap_matrix.csv``) into +shards with the same embedding and the ``optimized_physics_prior`` solves the released models read. Net names are matched by +name and never merged; every label passes QC (symmetry, signs, closure, positive definiteness) or is refused. +""" + +from __future__ import annotations + +import csv +import hashlib +import json +import os +import platform +import re +import time +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np + +GROUND = "G" +PRIOR_LEVELS = (1.5, 3.0) +TO_FF = {"F": 1e15, "nF": 1e6, "pF": 1e3, "fF": 1.0, "aF": 1e-3} +ARRAYS = ("key", "split", "family", "X", "E", "G", "C", "sig", "pri", "pairs") + + +class LabelQCError(ValueError): + """A label matrix failed QC (symmetry, Maxwell signs, closure, positive definiteness, net names).""" + + +def base_schema() -> dict: + """Feature names and order of the networks' input (nodekeys 61, edgekeys 42, globkeys 4) and the prior's physics.""" + from ._core import paper as PA + from .models import MANIFEST + + s = json.loads((Path(__file__).with_name("_core") / "schema_p2d.json").read_text()) + st = MANIFEST["prior_stacks"]["corrected"] + return { + "nodekeys": list(s["nodekeys"]), + "edgekeys": list(s["edgekeys"]), + "globkeys": list(s["globkeys"]), + "physics": { + "prior_method": "local_gap", + "alpha": PA.ALPHA, + "ensemble": "arithmetic mean of complete predicted Maxwell matrices", + "prior_version": st["version"], + "prior_stack": "corrected", + "levels_ppg": list(PRIOR_LEVELS), + }, + } + + +def pairs_of(n: int) -> np.ndarray: + return np.array([(i, j) for i in range(n) for j in range(i + 1, n)], dtype=np.int64).reshape(-1, 2) + + +def sha256_file(p) -> str: + h = hashlib.sha256() + with open(p, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +# ---------------------------------------------------------------------------------------------------------------- shards +def read_schema(shard_dir) -> dict: + return json.loads((Path(shard_dir) / "schema.json").read_text()) + + +def shard_files(shard_dir) -> list[Path]: + files = sorted(Path(shard_dir).glob("n*.npz")) + if not files: + raise FileNotFoundError(f"no n*.npz shards in {shard_dir}") + return files + + +def read_shards(shard_dir) -> list[dict]: + """Every shard file as a dict of arrays (sorted by N), plus ``n`` and ``file``.""" + out = [] + for p in shard_files(shard_dir): + with np.load(p, allow_pickle=False) as z: + d = {k: z[k] for k in z.files} + d["n"], d["file"] = int(d["sig"].shape[1]), p.name + out.append(d) + return out + + +def read_names(shard_dir) -> dict: + """{key: net names (G first)} of a shard dir built here (``names.json``); {} for shards without it.""" + p = Path(shard_dir) / "names.json" + return json.loads(p.read_text()) if p.exists() else {} + + +def shard_summary(shard_dir) -> dict: + """Layout counts per split and family, conductor-count range and the prior version of a shard dir.""" + from collections import Counter + + c, ns = Counter(), set() + for d in read_shards(shard_dir): + c.update(zip(d["split"].tolist(), d["family"].tolist())) + ns.add(d["n"]) + s = read_schema(shard_dir) + return { + "layouts": sum(c.values()), + "by_split": {sp: sum(v for (a, _), v in c.items() if a == sp) for sp in sorted({a for a, _ in c})}, + "by_family": {f"{a}/{b}": v for (a, b), v in sorted(c.items())}, + "n_range": [min(ns), max(ns)], + "prior_version": s.get("physics", {}).get("prior_version"), + } + + +def write_shards(rows: list[dict], out_dir, schema: dict, extra: dict | None = None) -> Path: + """Write per-layout rows (keys of ARRAYS minus pairs, plus ``names``) as a shard dir; refuses duplicate keys.""" + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=False) + keys = [r["key"] for r in rows] + dup = sorted({k for k in keys if keys.count(k) > 1}) + if dup: + raise ValueError(f"duplicate layout keys: {dup[:5]}") + by_n: dict[int, list[dict]] = {} + for r in rows: + by_n.setdefault(len(r["sig"]), []).append(r) + for n, rs in sorted(by_n.items()): + z = { + "key": np.array([r["key"] for r in rs]), + "split": np.array([r["split"] for r in rs]), + "family": np.array([r["family"] for r in rs]), + "X": np.stack([r["X"] for r in rs]).astype(np.float32), + "E": np.stack([r["E"] for r in rs]).astype(np.float32), + "G": np.stack([r["G"] for r in rs]).astype(np.float32), + "C": np.stack([r["C"] for r in rs]).astype(np.float32), + "sig": np.stack([r["sig"] for r in rs]).astype(bool), + "pri": np.stack([r["pri"] for r in rs]).astype(np.float32), + "pairs": pairs_of(n), + } + np.savez_compressed(out / f"n{n:03d}.npz", **z) + names = {r["key"]: list(r["names"]) for r in rows if r.get("names") is not None} + if names: + (out / "names.json").write_text(json.dumps(names)) + s = dict(schema) + s["shard_sha256"] = {p.name: sha256_file(p) for p in sorted(out.glob("n*.npz"))} + if extra: + s.update(extra) + (out / "schema.json").write_text(json.dumps(s, indent=1)) + return out + + +def subset_shards(src, out_dir, train_keys=None, val_keys=None, keep=None) -> Path: + """Copy of a shard dir restricted to ``train_keys`` (split set to train) and ``val_keys`` (split set to val), or to rows for + which ``keep(shard_dict) -> bool mask`` is True (splits unchanged).""" + src, out = Path(src), Path(out_dir) + out.mkdir(parents=True, exist_ok=False) + tr, va = set(map(str, train_keys or ())), set(map(str, val_keys or ())) + if tr & va: + raise ValueError(f"keys both train and val: {sorted(tr & va)[:5]}") + found = set() + for d in read_shards(src): + k = d["key"].astype(str) + if keep is not None: + m = np.asarray(keep(d), bool) + split = d["split"] + else: + t, v = np.isin(k, list(tr)), np.isin(k, list(va)) + m = t | v + split = np.where(t, "train", "val") + found.update(k[m].tolist()) + if m.any(): + z = {a: (d[a] if a == "pairs" else d[a][m]) for a in d if a not in ("n", "file")} + if keep is None: + z["split"] = split[m] + np.savez_compressed(out / d["file"], **z) + if keep is None and found != tr | va: + raise KeyError(f"keys not found in {src}: {sorted((tr | va) - found)[:5]}") + s = read_schema(src) + s["shard_sha256"] = {p.name: sha256_file(p) for p in sorted(out.glob("n*.npz"))} + s["subset_of"] = str(src) + (out / "schema.json").write_text(json.dumps(s, indent=1)) + names = read_names(src) + if names: + (out / "names.json").write_text(json.dumps({k: v for k, v in names.items() if k in found})) + return out + + +def merge_shards( + base_dir, + user_dir, + out_dir, + user_split: str | None = None, + all_split: str | None = None, + allow_prior_mismatch: bool = False, +) -> Path: + """Base shards + user shards -> one shard dir for collective retraining. Feature schemas and the prior version must agree + (a user prior computed under another stack is refused); duplicate keys are refused. Base arrays the user rows lack (e.g. + the flagship's ``origin`` / ``group``) are filled with ``user`` / the row's family. ``user_split`` overrides the user rows' + split, ``all_split`` every row's (``"train"`` for collective training).""" + bs, us = read_schema(base_dir), read_schema(user_dir) + for k in ("nodekeys", "edgekeys", "globkeys"): + if list(bs[k]) != list(us[k]): + raise ValueError(f"feature schema {k} differs between {base_dir} and {user_dir}") + bp, up = bs.get("physics", {}), us.get("physics", {}) + if float(bp.get("alpha", np.nan)) != float(up.get("alpha", np.nan)): + raise ValueError(f"prior alpha differs: base {bp.get('alpha')}, user {up.get('alpha')}") + if bp.get("prior_version") != up.get("prior_version") and not allow_prior_mismatch: + raise ValueError( + f"prior version differs: base {bp.get('prior_version')!r}, user {up.get('prior_version')!r}. Build the user " + "shards under the base's prior stack (or pass allow_prior_mismatch=True knowingly)" + ) + base = {d["n"]: d for d in read_shards(base_dir)} + user = {d["n"]: d for d in read_shards(user_dir)} + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=False) + seen: set = set() + for n in sorted(set(base) | set(user)): + b, u = base.get(n), user.get(n) + if u is not None: + u = dict(u) + if user_split is not None: + u["split"] = np.full(len(u["key"]), user_split) + if b is not None and u is not None: + for k in set(b) - set(u) - {"n", "file"}: + if b[k].dtype.kind != "U": + raise ValueError(f"base array {k!r} has no user counterpart and is not a string array") + u[k] = u["family"].copy() if k == "group" else np.full(len(u["key"]), "user") + extra = set(u) - set(b) - {"n", "file"} + if extra: + raise ValueError(f"user arrays {sorted(extra)} are not in the base shards") + z = {k: (b[k] if k == "pairs" else np.concatenate([b[k], u[k]])) for k in b if k not in ("n", "file")} + else: + z = {k: v for k, v in (b or u).items() if k not in ("n", "file")} + if all_split is not None: + z["split"] = np.full(len(z["key"]), all_split) + for k in z["key"].astype(str): + if k in seen: + raise ValueError(f"duplicate layout key {k!r} (base and user shards overlap)") + seen.add(k) + np.savez_compressed(out / f"n{n:03d}.npz", **z) + s = dict(bs) + s["shard_sha256"] = {p.name: sha256_file(p) for p in sorted(out.glob("n*.npz"))} + s["merged"] = { + "base": str(base_dir), + "user": str(user_dir), + "base_schema_sha256": sha256_file(Path(base_dir) / "schema.json"), + "user_schema_sha256": sha256_file(Path(user_dir) / "schema.json"), + "user_split": user_split, + "all_split": all_split, + } + (out / "schema.json").write_text(json.dumps(s, indent=1)) + names = {**read_names(base_dir), **read_names(user_dir)} + if names: + (out / "names.json").write_text(json.dumps(names)) + return out + + +# ---------------------------------------------------------------------------------------------------------------- labels +def read_q3d_csv(path) -> tuple[list[str], np.ndarray, dict]: + """Q3D ``cap_matrix.csv`` (one row per adaptive pass, columns ``C(a,b) [unit]``, also the ``C(a,b)*1e15 [pF]`` re-export) + -> (net names, Maxwell matrix in fF of the last complete pass, info). Names: G first, then the file's order of first + appearance.""" + rows = [r for r in csv.reader(open(path)) if r] + hdr, data = rows[0], rows[1:] + cols, order = {}, [] + for j, h in enumerate(hdr): + m = re.match(r"\s*C\(([^,]+),([^)]+)\)(\*1e15)?\s*\[(\w+)\]", h) + if not m: + continue + a, b = m.group(1).strip(), m.group(2).strip() + if m.group(4) not in TO_FF: + raise ValueError(f"{path}: unknown unit {m.group(4)!r} in column {h!r}") + cols[(a, b)] = (j, TO_FF[m.group(4)] * (1e-15 if m.group(3) else 1.0)) + for x in (a, b): + if x not in order: + order.append(x) + if not cols: + raise ValueError(f"{path}: no C(a,b) columns") + names = ([GROUND] if GROUND in order else []) + [x for x in order if x != GROUND] + n = len(names) + missing = [(a, b) for a in names for b in names if (a, b) not in cols and (b, a) not in cols] + if missing: + raise ValueError(f"{path}: matrix entries missing from the export: {missing[:5]}") + passes = [] + for r in data: + C = np.full((n, n), np.nan) + for ia, a in enumerate(names): + for ib, b in enumerate(names): + j, s = cols.get((a, b)) or cols[(b, a)] + try: + C[ia, ib] = float(r[j]) * s + except (ValueError, IndexError): + pass + passes.append(C) + complete = [k for k, C in enumerate(passes) if np.isfinite(C).all()] + if not complete: + raise LabelQCError(f"{path}: no complete adaptive pass") + last = complete[-1] + info = {"passes": len(passes), "label_pass_index": last, "complete_passes": len(complete)} + if len(complete) >= 2: + a, b = passes[complete[-2]], passes[last] + big = np.abs(b) >= 0.1 + info["last_pass_change_max_pct"] = ( + float(np.max(np.abs(b - a)[big] / np.abs(b)[big]) * 100) if big.any() else 0.0 + ) + return names, passes[last], info + + +def label_qc(C, names, sym_rtol: float | None = None, sign_atol: float = 1e-6, closure_rtol: float = 1e-4) -> dict: + """Label QC of a Maxwell matrix (fF, names G first). Returns the checks; raises LabelQCError on any failure.""" + from .qc import SYM_RTOL + + sym_rtol = SYM_RTOL if sym_rtol is None else sym_rtol + C = np.asarray(C, float) + n = len(names) + fail = [] + if C.shape != (n, n): + raise LabelQCError(f"matrix shape {C.shape} does not match {n} net names") + if len(set(names)) != n: + raise LabelQCError(f"duplicate net names {names}") + if names[0] != GROUND: + raise LabelQCError(f"ground net {GROUND!r} must be first (names {names})") + if not np.isfinite(C).all(): + raise LabelQCError("non-finite entries in the label matrix") + scale = float(np.abs(C).max()) + off = ~np.eye(n, dtype=bool) + sym = float(np.abs(C - C.T).max() / max(scale, 1e-30)) + chk = {"symmetry_rel": sym} + if sym > sym_rtol: + fail.append(f"asymmetric (max |C - C^T| / max |C| = {sym:.3g} > {sym_rtol:g})") + C = (C + C.T) / 2 + if not np.all(np.diag(C) > 0): + fail.append("non-positive diagonal entries") + chk["offdiag_max_fF"] = float(C[off].max()) if n > 1 else None + if n > 1 and C[off].max() > sign_atol: + fail.append(f"positive off-diagonal entry ({C[off].max():.3g} fF): not Maxwell signs") + sig = np.array([x != GROUND for x in names]) + rows = C.sum(1) + chk["closure_min_rel"] = float(np.min(rows[sig] / np.diag(C)[sig])) if sig.any() else None + if sig.any() and np.min(rows[sig] / np.diag(C)[sig]) < -closure_rtol: + fail.append(f"closure: a signal row sums below zero (min row sum / self = {chk['closure_min_rel']:.3g})") + eig = float(np.linalg.eigvalsh(C[np.ix_(sig, sig)]).min()) if sig.any() else None + chk["signal_block_min_eig_fF"] = eig + if eig is not None and eig <= 0: + fail.append(f"signal block not positive definite (min eigenvalue {eig:.3g} fF)") + if fail: + raise LabelQCError("; ".join(fail)) + chk["passed"] = True + return chk + + +# ---------------------------------------------------------------------------------------------------------------- designs +@dataclass +class Design: + """One layout and its label. + + gds: GDS path. labels: a ``cap_matrix.csv`` path (last complete pass), or a Maxwell matrix in fF with ``label_names`` + (any net order; ground ``G``), or None (inference-only rows are not allowed in training shards). + names: how the layout's conductors are named, matched to the label names: ``"auto"`` (port-stub layouts, i.e. a (2, 0) + marker: N / S fixed by the stubs and the pads named by the sibling design JSON's Q3D polygon map, the angle-slot or the + file-order convention, whichever matches the label (``resolve_dataset_names``); else C1..Cn in file order), + ``"dataset"`` (angle slots P), ``"dataset_file_order"`` (N, S, P1, ... in file order), ``"design_json"``, + ``"file_order"`` (C1..Cn), or an explicit list of signal names in file order. + """ + + gds: str + labels: object = None + label_names: list | None = None + key: str | None = None + family: str = "user" + split: str = "train" + names: object = "auto" + ground_layers: tuple = ((1, 0),) + conductor_layers: tuple = ((1, 10),) + meta: dict = field(default_factory=dict) + + def resolved_key(self) -> str: + if self.key: + return str(self.key) + p = Path(self.gds) + return f"{p.parent.name}/{p.stem}" + + +def as_design(x) -> Design: + if isinstance(x, Design): + return x + if isinstance(x, dict): + return Design(**x) + raise TypeError(f"cannot read a design from {type(x).__name__}: pass a Design or a dict of its fields") + + +def _has_marker(path, layer=(2, 0)) -> bool: + import gdstk + + lib = gdstk.read_gds(str(path)) + cell = lib.top_level()[0] + return any((p.layer, p.datatype) == layer for p in cell.polygons) + + +def design_json_names(gds) -> list[str] | None: + """Signal net names in GDS file order from the design's sibling ``.json`` (the Q3D polygon map + ``ansys_gds.q3d_signal.mapping_polygons`` + ``nets``), or None when there is no such map.""" + p = Path(gds).with_suffix(".json") + if not p.is_file(): + return None + try: + q = json.loads(p.read_text())["ansys_gds"]["q3d_signal"] + a2n = {v["assignment"]: k for k, v in q["nets"].items()} + order = sorted(q["mapping_polygons"], key=lambda k: int(k.rsplit("_", 1)[-1])) + names = [a2n[q["mapping_polygons"][k]] for k in order] + except (KeyError, ValueError, TypeError, AttributeError): + return None + return [x for x in names if x != GROUND] + + +def resolve_dataset_names(signals, markers, label_names, json_names=None) -> tuple[list[str], str]: + """Signal names of a port-stub layout (dataset convention) that match the label nets, and which naming gave them. + + N and S are fixed geometrically (N = body at the north stub (2, 0), S = body at the south stub (3, 0) or the origin). + Candidates, each kept only if its names are unique, equal the label's signal nets and put N and S on those bodies: + ``design_json`` (the Q3D polygon map of the sibling design JSON: exp13-15, quantum-metal exports), ``dataset`` (pads + P by angle slot: the multi-pad star, exp12) and ``dataset_file_order`` (N, S, P1, P2, ... in file order). The design + JSON wins when valid; otherwise one valid candidate (or two that agree) is used, and anything else is refused.""" + from ._core._tlsq.uge.scene import tlsq_namer + + want = sorted(x for x in label_names if x != GROUND) + geo = tlsq_namer(signals, markers) + n_i, s_i = geo.index("N"), geo.index("S") + cands = {} + if json_names is not None: + cands["design_json"] = list(json_names) + cands["dataset"] = geo + cands["dataset_file_order"] = ["N", "S"] + [f"P{k}" for k in range(1, len(signals) - 1)] + + def ok(c): + return ( + len(c) == len(signals) + and sorted(c) == want + and len(set(c)) == len(c) + and "N" in c + and "S" in c + and c.index("N") == n_i + and c.index("S") == s_i + ) + + valid = {k: c for k, c in cands.items() if ok(c)} + if "design_json" in valid: + return valid["design_json"], "design_json" + if not valid: + raise LabelQCError( + f"no naming of the layout bodies matches the label nets {want} ({cands}); pass names= (a list in file order); " + "nets are never merged" + ) + if len(valid) == 2 and valid["dataset"] != valid["dataset_file_order"]: + raise LabelQCError( + f"ambiguous naming: {valid} both match the label nets {want}; pass names='dataset', 'dataset_file_order' " + "or a list in file order" + ) + k = "dataset" if "dataset" in valid else "dataset_file_order" + return valid[k], k + + +def scene_of(d: Design, label_names=None): + """(Scene, naming used) for a design: the training geometry (no crop), ground = net 0. ``label_names`` lets + ``names="auto"`` pick the dataset naming that matches the label (see ``resolve_dataset_names``).""" + from ._core._tlsq.uge.scene import scene_from_gds, tlsq_namer + + mode = d.names + if mode == "auto": + mode = "dataset" if _has_marker(d.gds) else "file_order" + if mode == "dataset" and label_names is not None: + used = {} + jn = design_json_names(d.gds) + + def auto_namer(S, m): + names, used["k"] = resolve_dataset_names(S, m, label_names, jn) + return names + + sc = scene_from_gds(d.gds, namer=auto_namer) + return sc, f"auto:{used['k']}" + if mode == "dataset": + return scene_from_gds(d.gds, namer=tlsq_namer), "dataset" + if mode in ("dataset_file_order", "design_json"): + if mode == "design_json": + sig = design_json_names(d.gds) + if sig is None: + raise LabelQCError(f"{d.gds}: no design JSON with a Q3D polygon map next to the GDS") + else: + sig = None + + def ordered(S, m): + ns = sig if sig is not None else ["N", "S"] + [f"P{k}" for k in range(1, len(S) - 1)] + if len(S) != len(ns): + raise LabelQCError(f"{d.gds}: {len(S)} signal polygons but {len(ns)} names ({mode})") + return list(ns) + + return scene_from_gds(d.gds, namer=ordered), mode + if isinstance(mode, (list, tuple)): + sig = [str(x) for x in mode if x != GROUND] + + def namer(S, m): + if len(S) != len(sig): + raise LabelQCError(f"{d.gds}: {len(S)} signal polygons but {len(sig)} names given") + return sig + + return scene_from_gds(d.gds, namer=namer), "explicit" + if mode != "file_order": + raise ValueError( + f"names={mode!r}: use 'auto', 'dataset', 'dataset_file_order', 'design_json', 'file_order' or a list of names" + ) + from ._core import api as A + from ._runtime import prepare_layout + + lay = prepare_layout(d.gds, ground_layers=d.ground_layers, conductor_layers=d.conductor_layers) + return A.scene_from_prepared(lay), "file_order" + + +def labels_of(d: Design) -> tuple[list[str], np.ndarray, dict]: + if d.labels is None: + raise LabelQCError(f"{d.resolved_key()}: no labels (training rows need a Maxwell matrix)") + if isinstance(d.labels, (str, os.PathLike)): + names, C, info = read_q3d_csv(d.labels) + return names, C, {"source": str(d.labels), **info} + if d.label_names is None: + raise LabelQCError(f"{d.resolved_key()}: a label matrix needs label_names") + return [str(x) for x in d.label_names], np.asarray(d.labels, float), {"source": "matrix"} + + +def _stack_registry(): + from .models import registry_view + + return registry_view({}, ".", "squadds-training-data") + + +def embed_design(d: Design, threads: int = 2, prior: str = "optimized", schema: dict | None = None) -> dict: + """Shard row of one design: embedding (exact, no far-sample decimation), prior solves at 1.5 and 3 panels per gap under + the corrected stack, and the QC-checked label reordered to the scene's net order (G first).""" + from . import _runtime as RT + from ._core import api as A + from ._core import paper as PA + from ._core._tlsq.uge import blocks as B + from .predictor import quiet + + if prior != "optimized": + raise NotImplementedError( + f"prior={prior!r}: training shards carry the optimized_physics_prior solves (1.5, 3); other priors are TODO" + ) + schema = schema or base_schema() + key = d.resolved_key() + lnames, Cl, linfo = labels_of(d) + if GROUND not in lnames: + raise LabelQCError(f"{key}: the label has no ground net {GROUND!r} (names {lnames})") + lnames_g = [GROUND] + [x for x in lnames if x != GROUND] + perm = [lnames.index(x) for x in lnames_g] + try: + qc = label_qc(Cl[np.ix_(perm, perm)], lnames_g) + except LabelQCError as e: + raise LabelQCError(f"{key}: label QC failed: {e}") from e + t0 = time.perf_counter() + sc, naming = scene_of(d, lnames) + names = list(sc.names()) if callable(getattr(sc, "names", None)) else [c.name for c in sc.conductors] + if sorted(names) != sorted(lnames): + raise LabelQCError( + f"{key}: layout nets {names} do not match the label nets {lnames} (naming {naming!r}); nets are never merged" + ) + old = dict(B.FAR_DECIMATION) + B.FAR_DECIMATION.update(k=0, d_far=100.0) + try: + from ._core._tlsq.uge.graph import scene_graph + + row = PA.lt.add_tokens(sc, scene_graph(sc)) + finally: + B.FAR_DECIMATION.clear() + B.FAR_DECIMATION.update(old) + t1 = time.perf_counter() + if list(row["names"]) != names: + raise RuntimeError(f"{key}: embedding names {row['names']} differ from the scene {names}") + with RT.LOCK, quiet(): + threads = RT.configure(threads) + PA.apply_stack(_stack_registry(), {"stack": "corrected"}, threads) + P, tl = PA.solve_levels(sc, list(PRIOR_LEVELS), threads) + stack = {"name": "corrected", "patches": list(A._STATE.get("patches", [])), "mode": A._STATE.get("mode")} + t2 = time.perf_counter() + n = len(names) + pr = pairs_of(n) + nk, ek, gk = schema["nodekeys"], schema["edgekeys"], schema["globkeys"] + assert nk[-1] == "missing_log_min_halfwidth" + wi = nk.index("log_min_halfwidth") + X = np.array([[row["nodes"][a][k] for k in nk[:-1]] for a in range(n)], np.float32) + X = np.concatenate([X, (~np.isfinite(X[:, wi])).astype(np.float32)[:, None]], -1) + E = np.array([[row["edges"][(int(i), int(j))][k] for k in ek] for i, j in pr], np.float32).reshape(len(pr), len(ek)) + G = np.array([row["global"][k] for k in gk], np.float32) + pri = np.stack([np.asarray(P[p], float)[pr[:, 0], pr[:, 1]] for p in PRIOR_LEVELS], -1).astype(np.float32) + if not (np.isfinite(E).all() and np.isfinite(G).all() and np.isfinite(np.delete(X, wi, axis=-1)).all()): + raise ValueError(f"{key}: non-finite embedding features") + if not (np.isfinite(pri).all() and (pri > 0).all()): + raise ValueError(f"{key}: prior mutuals not finite and positive") + idx = [lnames.index(x) for x in names] + C = np.asarray(Cl, float)[np.ix_(idx, idx)] + C = (C + C.T) / 2 + return { + "key": key, + "split": d.split, + "family": d.family, + "names": names, + "X": X, + "E": E, + "G": G, + "C": C.astype(np.float32), + "sig": np.array([x != GROUND for x in names]), + "pri": pri, + "info": { + "gds": str(d.gds), + "naming": naming, + "label": linfo, + "qc": qc, + "stack": stack, + "timing_s": {"embedding": t1 - t0, "prior": t2 - t1, "prior_levels": tl}, + **({"meta": d.meta} if d.meta else {}), + }, + } + + +def _embed_worker(args): + d, threads, prior, on_error = args + try: + return embed_design(d, threads=threads, prior=prior), None + except (LabelQCError, ValueError) as e: + if on_error == "raise": + raise + return None, {"key": d.resolved_key(), "gds": str(d.gds), "reason": str(e)} + + +def build_shards( + designs, out_dir, prior: str = "optimized", threads: int = 2, workers: int = 1, on_error: str = "raise" +) -> dict: + """User designs -> a P2d shard dir (``n0NN.npz`` + ``schema.json`` + ``names.json`` + ``build.json``). + + designs: Design objects or dicts of their fields. Labels are QC-checked and matched to the layout nets by name; a design + that fails is refused (``on_error="raise"``, default) or skipped and listed in ``build.json`` (``"skip"``). Priors are + computed on this machine (macOS is not bit-identical to the released x86 priors: ~2.4e-3 relative at most); ``threads`` + per design, ``workers`` designs at a time (spawned processes).""" + from . import _runtime as RT + + if on_error not in ("raise", "skip"): + raise ValueError("on_error must be 'raise' or 'skip'") + ds = [as_design(x) for x in designs] + if not ds: + raise ValueError("no designs") + schema = base_schema() + t = time.perf_counter() + jobs = [(d, threads, prior, on_error) for d in ds] + if workers > 1: + from concurrent.futures import ProcessPoolExecutor + from multiprocessing import get_context + + with ProcessPoolExecutor(min(workers, len(ds)), mp_context=get_context("spawn")) as ex: + res = list(ex.map(_embed_worker, jobs)) + else: + res = [_embed_worker(j) for j in jobs] + rows = [r for r, e in res if r is not None] + refused = [e for r, e in res if e is not None] + if not rows: + raise LabelQCError(f"every design was refused: {refused[:3]}") + from squadds import __version__ + + build = { + "created": time.strftime("%Y-%m-%dT%H:%M:%S%z"), + "machine": RT.machine(), + "platform": platform.platform(), + "threads": threads, + "workers": workers, + "package": f"squadds {__version__}", + "code_sha256": sha256_file(__file__), + "layouts": len(rows), + "refused": refused, + "seconds": time.perf_counter() - t, + "note": "priors computed on this machine; released shards use HPC x86 priors", + } + out = write_shards(rows, out_dir, schema, extra={"build": {k: v for k, v in build.items() if k != "refused"}}) + build["designs"] = {r["key"]: r["info"] for r in rows} + (out / "build.json").write_text(json.dumps(build, indent=1, default=str)) + return {"out_dir": str(out), "layouts": len(rows), "refused": refused, "seconds": build["seconds"]} + + +# ---------------------------------------------------------------------------------------------------------------- dataset +def shards_from_model_input(model_input, labels, out_dir, splits=("train", "val")) -> Path: + """HOOK: the dataset's ``model_input`` table (``squadds.datasets.planar_capacitance_schema``, one row per layout: flat + X / E / G / pri / sig with ``net_order``) and its ``labels`` table (long format, ``a_idx <= b_idx``) -> a shard dir. + Both arguments: pandas DataFrames or parquet paths. Test rows are never read (``splits`` may not contain ``test``).""" + import pandas as pd + + if "test" in splits: + raise PermissionError("test labels are not training data") + mi = pd.read_parquet(model_input) if isinstance(model_input, (str, os.PathLike)) else model_input + lab = pd.read_parquet(labels) if isinstance(labels, (str, os.PathLike)) else labels + mi = mi[mi["split"].isin(splits)] + schema = base_schema() + versions = set(mi["prior_version"].unique()) + if len(versions) > 1: + raise ValueError(f"model_input mixes prior versions {sorted(versions)}") + nx, ne, ng = len(schema["nodekeys"]), len(schema["edgekeys"]), len(schema["globkeys"]) + lab = lab[lab["design_id"].isin(set(mi["design_id"]))] + groups = {k: g for k, g in lab.groupby("design_id")} + rows = [] + for r in mi.itertuples(index=False): + n = int(r.n_conductors) + p = n * (n - 1) // 2 + g = groups.get(r.design_id) + if g is None: + raise KeyError(f"{r.design_id}: no labels") + C = np.full((n, n), np.nan) + C[g["a_idx"].to_numpy(), g["b_idx"].to_numpy()] = g["C_fF"].to_numpy() + C[g["b_idx"].to_numpy(), g["a_idx"].to_numpy()] = g["C_fF"].to_numpy() + names = list(r.net_order) + label_qc(C, names) + rows.append( + dict( + key=r.design_id, + split=r.split, + family=r.model_family, + names=names, + X=np.asarray(r.X, np.float32).reshape(n, nx), + E=np.asarray(r.E, np.float32).reshape(p, ne), + G=np.asarray(r.G, np.float32).reshape(ng), + C=C, + sig=np.asarray(r.sig, bool), + pri=np.asarray(r.pri, np.float32).reshape(p, 2), + ) + ) + v = next(iter(versions), None) + if v is not None and not str(v).startswith(schema["physics"]["prior_version"]): + schema["physics"]["prior_version"] = str(v) + return write_shards(rows, out_dir, schema, extra={"source": "dataset model_input table"}) diff --git a/src/squadds/ml/client.py b/src/squadds/ml/client.py new file mode 100644 index 0000000000000000000000000000000000000000..6244c1c72331e38b1a4709afb8565858d265b196 --- /dev/null +++ b/src/squadds/ml/client.py @@ -0,0 +1,66 @@ +"""Client of the SQuADDS ML API (the models hosted on the SQuADDS Hugging Face Space). + + from squadds.ml import client + client.list_models() + client.predict("transmon_cross_hamiltonian_inverse", inputs={"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0}) + client.predict("", file="chip.gds", inputs={"ground_layer": "1/0"}) + +The base URL is ``SQUADDS_ML_API_URL`` when set, else ``DEFAULT_URL``. Gated models need a Hugging Face token of a member +of the SQuADDS organization (``token=`` or ``HF_TOKEN``). +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path + +DEFAULT_URL = "https://squadds-squadds-ml-inference-api.hf.space" + + +def _url(base_url: str | None) -> str: + return (base_url or os.environ.get("SQUADDS_ML_API_URL") or DEFAULT_URL).rstrip("/") + + +def _headers(token: str | None) -> dict: + token = token or os.environ.get("HF_TOKEN") + return {"Authorization": f"Bearer {token}"} if token else {} + + +def _json(r) -> dict: + try: + body = r.json() + except ValueError: + body = {"error": {"message": r.text}} + if r.status_code >= 400: + err = body.get("error") or body + raise RuntimeError(f"SQuADDS ML API {r.status_code}: {err}") + return body + + +def list_models(base_url: str | None = None, token: str | None = None, timeout: float = 30) -> list[dict]: + import requests + + return _json(requests.get(f"{_url(base_url)}/v1/models", headers=_headers(token), timeout=timeout))["models"] + + +def predict( + model_id: str, + inputs: dict | list | None = None, + file=None, + options: dict | None = None, + base_url: str | None = None, + token: str | None = None, + timeout: float = 600, +) -> dict: + """The response envelope (``outputs``, ``metadata``, ``timing_s``, ``cached``). ``file``: a path or bytes (file models).""" + import requests + + url = f"{_url(base_url)}/v1/models/{model_id}/predict" + if file is None: + r = requests.post(url, json={"inputs": inputs or {}, "options": options or {}}, headers=_headers(token), timeout=timeout) + else: + data = Path(file).read_bytes() if isinstance(file, (str, os.PathLike)) else bytes(file) + form = {"inputs": json.dumps(inputs or {}), "options": json.dumps(options or {})} + r = requests.post(url, files={"file": ("layout.gds", data)}, data=form, headers=_headers(token), timeout=timeout) + return _json(r) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..c933be258527cea43d6068ecc8475d01a127136f --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,68 @@ +"""Run against a built bundle: SQUADDS_ML_API_ROOT (default: the folder above tests/). Each session uses a fresh +Hugging Face cache, so the tests can see which weights were downloaded.""" +import os +import sys +import tempfile +import time +from pathlib import Path + +import pytest +import yaml + +ROOT = Path(os.environ.get("SQUADDS_ML_API_ROOT", Path(__file__).resolve().parents[1])) +sys.path[:0] = [str(ROOT), str(ROOT / "src")] +TOKEN = None +try: + from huggingface_hub import get_token + + TOKEN = get_token() +except Exception: # noqa: BLE001 + pass +os.environ["HF_HUB_CACHE"] = tempfile.mkdtemp(prefix="squadds_ml_api_hub_") +os.environ.setdefault("KERAS_BACKEND", "torch") +os.environ.setdefault("SQUADDS_ML_API_RATE_PER_MIN", "0") +GDS_DIR = Path(os.environ.get("SQUADDS_ML_API_TEST_GDS", + "/Users/shanto/LFL/tl_squadds/deploy/build_flagship_docker/PlanarCapacitanceModel/examples")) +CAP = ("planar_capacitance_flagship", "planar_capacitance_fast") + + +def _client(registry_file=None): + from fastapi.testclient import TestClient + + from squadds_ml_api.api import create_app + + app = create_app(ROOT, registry_file) + c = TestClient(app) + c.__enter__() + reg = app.state.registry + t = time.time() + while any(m.state == "loading" for m in reg.models.values()) and time.time() - t < 600: + time.sleep(0.2) + return c + + +@pytest.fixture(scope="session") +def client(): + c = _client() + c.hub_listing = sorted(os.listdir(os.environ["HF_HUB_CACHE"])) + yield c + c.__exit__(None, None, None) + + +@pytest.fixture(scope="session") +def gated_client(tmp_path_factory): + if not TOKEN: + pytest.skip("no Hugging Face token") + reg = yaml.safe_load((ROOT / "registry.yaml").read_text()) + for k in CAP: + reg["models"][k]["visibility"] = "gated" + p = tmp_path_factory.mktemp("reg") / "registry.yaml" + p.write_text(yaml.safe_dump(reg, sort_keys=False)) + c = _client(p) + yield c + c.__exit__(None, None, None) + + +@pytest.fixture(scope="session") +def auth(): + return {"Authorization": f"Bearer {TOKEN}"} diff --git a/tests/legacy_oracle.json b/tests/legacy_oracle.json new file mode 100644 index 0000000000000000000000000000000000000000..e3171dad51755b2ae85b5e2fdd71f643a648407d --- /dev/null +++ b/tests/legacy_oracle.json @@ -0,0 +1,373 @@ +[ + { + "method": "GET", + "path": "/health", + "body": null, + "status": 200, + "response": { + "status": "ok", + "available_models": [ + "transmon_cross_hamiltonian_inverse" + ], + "bundle_root": "" + } + }, + { + "method": "GET", + "path": "/models", + "body": null, + "status": 200, + "response": { + "models": [ + { + "id": "transmon_cross_hamiltonian_inverse", + "display_name": "TransmonCross Hamiltonian to Geometry", + "description": "Inverse model that predicts TransmonCross geometry parameters from target Hamiltonian values.", + "status": "ready", + "status_detail": "", + "input_units": { + "qubit_frequency_GHz": "GHz", + "anharmonicity_MHz": "MHz" + }, + "output_units": { + "design_options.connection_pads.readout.claw_length": "m", + "design_options.connection_pads.readout.ground_spacing": "m", + "design_options.cross_length": "m" + }, + "tags": [ + "inverse-design", + "transmon", + "hamiltonian" + ] + }, + { + "id": "transmon_cross_cap_matrix_inverse", + "display_name": "TransmonCross Cap Matrix to Geometry", + "description": "Inverse model that predicts TransmonCross geometry parameters from cap matrix targets.", + "status": "missing_model_artifact", + "status_detail": "No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras", + "input_units": {}, + "output_units": {}, + "tags": [ + "inverse-design", + "transmon", + "cap-matrix" + ] + }, + { + "id": "coupler_ncap_cap_matrix_inverse", + "display_name": "NCap Coupler Cap Matrix to Geometry", + "description": "Inverse model that predicts NCap coupler geometry from cap matrix targets.", + "status": "missing_model_artifact", + "status_detail": "No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras", + "input_units": {}, + "output_units": {}, + "tags": [ + "inverse-design", + "coupler", + "cap-matrix" + ] + }, + { + "id": "cavity_claw_route_meander_inverse", + "display_name": "Cavity Claw RouteMeander Targets to Geometry", + "description": "Inverse model that predicts cavity claw RouteMeander geometry from target cavity frequency and kappa.", + "status": "missing_model_artifact", + "status_detail": "No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate.keras, model/best_keras_model_model2_surrogate.keras", + "input_units": {}, + "output_units": {}, + "tags": [ + "inverse-design", + "cavity", + "readout" + ] + } + ] + } + }, + { + "method": "POST", + "path": "/predict", + "body": { + "model_id": "transmon_cross_hamiltonian_inverse", + "inputs": { + "qubit_frequency_GHz": 4.85, + "anharmonicity_MHz": -205.0 + }, + "options": { + "include_scaled_outputs": false + } + }, + "status": 200, + "response": { + "model_id": "transmon_cross_hamiltonian_inverse", + "display_name": "TransmonCross Hamiltonian to Geometry", + "predictions": [ + { + "design_options.connection_pads.readout.claw_length": 0.00011072495544794947, + "design_options.connection_pads.readout.ground_spacing": 4.571595582092414e-06, + "design_options.cross_length": 0.0002005973074119538 + } + ], + "metadata": { + "input_order": [ + "qubit_frequency_GHz", + "anharmonicity_MHz" + ], + "output_order": [ + "design_options.connection_pads.readout.claw_length", + "design_options.connection_pads.readout.ground_spacing", + "design_options.cross_length" + ], + "input_units": { + "qubit_frequency_GHz": "GHz", + "anharmonicity_MHz": "MHz" + }, + "output_units": { + "design_options.connection_pads.readout.claw_length": "m", + "design_options.connection_pads.readout.ground_spacing": "m", + "design_options.cross_length": "m" + }, + "num_predictions": 1 + } + } + }, + { + "method": "POST", + "path": "/predict", + "body": { + "model_id": "transmon_cross_hamiltonian_inverse", + "inputs": [ + { + "qubit_frequency_GHz": 4.85, + "anharmonicity_MHz": -205.0 + }, + { + "qubit_frequency_GHz": 5.6, + "anharmonicity_MHz": -180.0 + } + ] + }, + "status": 200, + "response": { + "model_id": "transmon_cross_hamiltonian_inverse", + "display_name": "TransmonCross Hamiltonian to Geometry", + "predictions": [ + { + "design_options.connection_pads.readout.claw_length": 0.00011072495544794947, + "design_options.connection_pads.readout.ground_spacing": 4.571595582092414e-06, + "design_options.cross_length": 0.0002005973074119538 + }, + { + "design_options.connection_pads.readout.claw_length": 0.0001186570298159495, + "design_options.connection_pads.readout.ground_spacing": 4.966359483660199e-06, + "design_options.cross_length": 0.00018099475710187107 + } + ], + "metadata": { + "input_order": [ + "qubit_frequency_GHz", + "anharmonicity_MHz" + ], + "output_order": [ + "design_options.connection_pads.readout.claw_length", + "design_options.connection_pads.readout.ground_spacing", + "design_options.cross_length" + ], + "input_units": { + "qubit_frequency_GHz": "GHz", + "anharmonicity_MHz": "MHz" + }, + "output_units": { + "design_options.connection_pads.readout.claw_length": "m", + "design_options.connection_pads.readout.ground_spacing": "m", + "design_options.cross_length": "m" + }, + "num_predictions": 2 + } + } + }, + { + "method": "POST", + "path": "/predict", + "body": { + "model_id": "transmon_cross_hamiltonian_inverse", + "inputs": { + "qubit_frequency_GHz": 4.85, + "anharmonicity_MHz": -205.0 + }, + "options": { + "include_scaled_outputs": true + } + }, + "status": 200, + "response": { + "model_id": "transmon_cross_hamiltonian_inverse", + "display_name": "TransmonCross Hamiltonian to Geometry", + "predictions": [ + { + "design_options.connection_pads.readout.claw_length": 0.00011072495544794947, + "design_options.connection_pads.readout.ground_spacing": 4.571595582092414e-06, + "design_options.cross_length": 0.0002005973074119538 + } + ], + "metadata": { + "input_order": [ + "qubit_frequency_GHz", + "anharmonicity_MHz" + ], + "output_order": [ + "design_options.connection_pads.readout.claw_length", + "design_options.connection_pads.readout.ground_spacing", + "design_options.cross_length" + ], + "input_units": { + "qubit_frequency_GHz": "GHz", + "anharmonicity_MHz": "MHz" + }, + "output_units": { + "design_options.connection_pads.readout.claw_length": "m", + "design_options.connection_pads.readout.ground_spacing": "m", + "design_options.cross_length": "m" + }, + "num_predictions": 1 + }, + "scaled_predictions": [ + { + "design_options.connection_pads.readout.claw_length": 0.1234089583158493, + "design_options.connection_pads.readout.ground_spacing": 0.07993147522211075, + "design_options.cross_length": 0.3351433575153351 + } + ] + } + }, + { + "method": "POST", + "path": "/predict", + "body": { + "model_id": "transmon_cross_hamiltonian_inverse", + "inputs": { + "qubit_frequency_GHz": 4.85 + } + }, + "status": 400, + "response": { + "detail": "Model 'transmon_cross_hamiltonian_inverse' expects inputs ['qubit_frequency_GHz', 'anharmonicity_MHz']. Missing: ['anharmonicity_MHz']. Extra: none." + } + }, + { + "method": "POST", + "path": "/predict", + "body": { + "model_id": "transmon_cross_hamiltonian_inverse", + "inputs": { + "qubit_frequency_GHz": 4.85, + "anharmonicity_MHz": -205.0, + "foo": 1.0 + } + }, + "status": 400, + "response": { + "detail": "Model 'transmon_cross_hamiltonian_inverse' expects inputs ['qubit_frequency_GHz', 'anharmonicity_MHz']. Missing: none. Extra: ['foo']." + } + }, + { + "method": "POST", + "path": "/predict", + "body": { + "model_id": "nope", + "inputs": { + "qubit_frequency_GHz": 4.85, + "anharmonicity_MHz": -205.0 + } + }, + "status": 400, + "response": { + "detail": "Unknown model_id 'nope'. Available models: ['transmon_cross_hamiltonian_inverse']." + } + }, + { + "method": "POST", + "path": "/predict", + "body": { + "model_id": "transmon_cross_cap_matrix_inverse", + "inputs": { + "qubit_frequency_GHz": 4.85, + "anharmonicity_MHz": -205.0 + } + }, + "status": 400, + "response": { + "detail": "Model 'transmon_cross_cap_matrix_inverse' is not deployable in this bundle: No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras." + } + }, + { + "method": "POST", + "path": "/predict", + "body": { + "model_id": "transmon_cross_hamiltonian_inverse", + "inputs": { + "qubit_frequency_GHz": "abc", + "anharmonicity_MHz": 1 + } + }, + "status": 422, + "response": { + "detail": [ + { + "type": "float_parsing", + "loc": [ + "body", + "inputs", + "dict[str,float]", + "qubit_frequency_GHz" + ], + "msg": "Input should be a valid number, unable to parse string as a number", + "input": "abc" + }, + { + "type": "list_type", + "loc": [ + "body", + "inputs", + "list[dict[str,float]]" + ], + "msg": "Input should be a valid list", + "input": { + "qubit_frequency_GHz": "abc", + "anharmonicity_MHz": 1 + } + } + ] + } + }, + { + "method": "POST", + "path": "/predict", + "body": { + "inputs": { + "qubit_frequency_GHz": 4.85, + "anharmonicity_MHz": -205.0 + } + }, + "status": 422, + "response": { + "detail": [ + { + "type": "missing", + "loc": [ + "body", + "model_id" + ], + "msg": "Field required", + "input": { + "inputs": { + "qubit_frequency_GHz": 4.85, + "anharmonicity_MHz": -205.0 + } + } + } + ] + } + } +] diff --git a/tests/test_contract.py b/tests/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..8173d75a920bb12e2c72d588e73f132dc44265ae --- /dev/null +++ b/tests/test_contract.py @@ -0,0 +1,29 @@ +"""Every servable model with an example: example request -> example response within its rtol.""" +import base64 +import json + +import pytest +from conftest import CAP, ROOT +from test_legacy import close + + +def run(client, model_id, headers=None): + ex = json.loads((ROOT / f"examples/{model_id}.json").read_text()) + body = dict(ex["request"]) + if "file" in ex: + body["inputs"] = {**body["inputs"], "file_base64": base64.b64encode((ROOT / ex["file"]).read_bytes()).decode()} + r = client.post(f"/v1/models/{model_id}/predict", json=body, headers=headers or {}) + assert r.status_code == 200, r.text + got = r.json() + for k in ("model_id", "family", "revision", "outputs", "metadata"): + close(ex["response"][k], got[k], ex.get("rtol", 1e-5)) + assert set(got) == {"model_id", "family", "revision", "outputs", "metadata", "timing_s", "cached"} + + +def test_contract_public(client): + run(client, "transmon_cross_hamiltonian_inverse") + + +@pytest.mark.parametrize("model_id", CAP) +def test_contract_gated(gated_client, auth, model_id): + run(gated_client, model_id, auth) diff --git a/tests/test_legacy.py b/tests/test_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..168e4998c9fc8f419d754df161ffdd820e9cb21b --- /dev/null +++ b/tests/test_legacy.py @@ -0,0 +1,51 @@ +"""The original Space's routes against the oracle recorded from its own code (tests/legacy_oracle.json).""" +import json +from pathlib import Path + +import numpy as np +import pytest + +ORACLE = json.loads((Path(__file__).with_name("legacy_oracle.json")).read_text()) + + +def close(a, b, rtol=1e-5): + if isinstance(a, dict): + assert isinstance(b, dict) and list(a) == list(b), (a, b) + for k in a: + close(a[k], b[k], rtol) + elif isinstance(a, list): + assert isinstance(b, list) and len(a) == len(b) + for x, y in zip(a, b): + close(x, y, rtol) + elif isinstance(a, float) and not isinstance(b, bool): + assert np.isclose(a, b, rtol=rtol, atol=0), (a, b) + else: + assert a == b, (a, b) + + +@pytest.mark.parametrize("case", ORACLE, ids=[f"{c['path']}-{i}" for i, c in enumerate(ORACLE)]) +def test_legacy_matches_oracle(client, case): + r = client.request(case["method"], case["path"], json=case["body"]) + assert r.status_code == case["status"] + got = r.json() + if case["path"] == "/health": + got["bundle_root"] = "" + if case["status"] == 422: + assert [(e["type"], e["loc"]) for e in got["detail"]] == [(e["type"], e["loc"]) for e in case["response"]["detail"]] + else: + close(case["response"], got) + + +def test_legacy_hides_new_models(client): + r = client.post("/predict", json={"model_id": "planar_capacitance_flagship", "inputs": {"a": 1.0}}) + assert r.status_code == 400 and r.json()["detail"].startswith("Unknown model_id 'planar_capacitance_flagship'") + ids = [m["id"] for m in client.get("/models").json()["models"]] + assert ids == ["transmon_cross_hamiltonian_inverse", "transmon_cross_cap_matrix_inverse", + "coupler_ncap_cap_matrix_inverse", "cavity_claw_route_meander_inverse"] + + +def test_docs(client): + assert client.get("/docs").status_code == 200 + paths = client.get("/openapi.json").json()["paths"] + for p in ("/health", "/models", "/predict", "/v1/models/{model_id}/predict"): + assert p in paths diff --git a/tests/test_registry.py b/tests/test_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..c2e5e57ef9272f45a12e2f40e54c048cd6c9a7ae --- /dev/null +++ b/tests/test_registry.py @@ -0,0 +1,43 @@ +import copy +import json + +import pytest +import yaml +from conftest import ROOT + +from squadds_ml_api.registry import Registry, RegistryError, validate + + +def data(): + return yaml.safe_load((ROOT / "registry.yaml").read_text()) + + +def test_registry_valid_and_adapters_import(): + reg = Registry(ROOT) + for m in reg.models.values(): + if m.status == "ready": + assert m.adapter_cls is not None + for k in ("input_kind", "describe", "predict"): + assert hasattr(m.adapter_cls, k) + assert {m.id for m in reg.servable()} == {"transmon_cross_hamiltonian_inverse"} + + +@pytest.mark.parametrize("change, msg", [ + (lambda d: d["models"]["transmon_cross_hamiltonian_inverse"]["weights"].update(revision="main"), "40-character"), + (lambda d: d["models"]["transmon_cross_hamiltonian_inverse"]["weights"]["files"][0].pop("sha256"), "sha256"), + (lambda d: d["models"]["planar_capacitance_fast"].update(visibility="secret"), "visibility"), + (lambda d: d["models"]["planar_capacitance_fast"]["weights"].update(from_manifest="x#y"), "not expanded"), +]) +def test_registry_rules(change, msg): + d = copy.deepcopy(data()) + change(d) + with pytest.raises(RegistryError, match=msg): + validate(d, ROOT) + + +def test_lock_file(): + lock = json.loads((ROOT / "bundle.lock.json").read_text()) + assert len(lock["squadds"]["commit"]) == 40 and "dirty" in lock["squadds"] + assert lock["registry_sha256"] == Registry(ROOT).sha256 + for m in lock["models"].values(): + assert len(m["revision"]) == 40 and m["files"] diff --git a/tests/test_v1.py b/tests/test_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..5393bc90744a20457e070c3b374d7881c9309333 --- /dev/null +++ b/tests/test_v1.py @@ -0,0 +1,211 @@ +import base64 +import json +import os +import time + +import numpy as np +import pytest +from conftest import CAP, GDS_DIR, ROOT + +OLIVIA = "transmon_cross_hamiltonian_inverse" +S = {"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0} +LAYOUTS = ["interdigital", "xmon", "transmon_pocket", "lattice_1q"] + + +# ---------- hidden ---------- + +@pytest.mark.parametrize("model_id", CAP) +@pytest.mark.parametrize("with_token", [False, True]) +def test_hidden_everywhere(client, auth, model_id, with_token): + h = auth if with_token else {} + for path in (f"/v1/models/{model_id}", f"/v1/models/{model_id}/schema"): + r = client.get(path, headers=h) + assert r.status_code == 404 and r.json()["error"]["code"] == "unknown_model" + r = client.post(f"/v1/models/{model_id}/predict", json={"inputs": {}}, headers=h) + nope = client.post("/v1/models/nope/predict", json={"inputs": {}}, headers=h) + assert r.status_code == nope.status_code == 404 + assert r.json()["error"] == {"code": "unknown_model", "message": f"unknown model '{model_id}'", "model_id": model_id} + assert nope.json()["error"]["message"] == "unknown model 'nope'" + for path in ("/v1/models", "/models", "/v1/health", "/health"): + assert model_id not in client.get(path, headers=h).text + + +def test_hidden_weights_not_downloaded(client): + reg = client.app.state.registry + assert reg.fetched == ["SQuADDS/transmon-cross-hamiltonian-inverse"] + assert not any("PlanarCapacitance" in d for d in client.hub_listing), client.hub_listing + + +# ---------- gated ---------- + +@pytest.mark.parametrize("model_id", CAP) +def test_gated_needs_member_token(gated_client, auth, model_id): + c = gated_client + gds = (ROOT / "examples/interdigital.gds").read_bytes() + assert model_id not in json.dumps(c.get("/v1/models").json()) + assert model_id not in c.get("/v1/health").text + r = c.post(f"/v1/models/{model_id}/predict", files={"file": ("x.gds", gds)}) + assert r.status_code == 401 and r.json()["error"]["code"] == "auth_required" + assert c.get(f"/v1/models/{model_id}").status_code == 401 + bad = {"Authorization": "Bearer hf_not_a_real_token_0000000000000000"} + r = c.post(f"/v1/models/{model_id}/predict", files={"file": ("x.gds", gds)}, headers=bad) + assert r.status_code == 403 and r.json()["error"]["code"] == "forbidden" + assert model_id in [m["id"] for m in c.get("/v1/models", headers=auth).json()["models"]] + r = c.post(f"/v1/models/{model_id}/predict", files={"file": ("x.gds", gds)}, headers=auth) + assert r.status_code == 200 and r.json()["metadata"]["checks"]["passed"] + + +def test_public_without_token(gated_client): + r = gated_client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": S}) + assert r.status_code == 200 and r.json()["outputs"]["predictions"][0] + + +def test_whoami_is_org_member(): + from conftest import TOKEN + from huggingface_hub import whoami + + assert "SQuADDS" in [o["name"] for o in whoami(token=TOKEN)["orgs"]] + + +# ---------- capacitance: API == direct package call ---------- + +@pytest.fixture(scope="session") +def direct(): + if not GDS_DIR.exists(): + pytest.skip(f"no test layouts at {GDS_DIR}") + from squadds.ml.capacitance import CapacitancePredictor, load_model + from squadds.ml.capacitance.predictor import clear_cache + + out = {} + for name in ("flagship", "fast"): + p = CapacitancePredictor(load_model(name)) + for lay in LAYOUTS: + clear_cache() + r = p.predict(str(GDS_DIR / f"{lay}.gds")) + out[name, lay] = (r.names, r.matrix_fF) + clear_cache() + return out + + +@pytest.mark.parametrize("name", ["flagship", "fast"]) +@pytest.mark.parametrize("lay", LAYOUTS) +@pytest.mark.parametrize("how", ["multipart", "base64"]) +def test_capacitance_equals_direct(gated_client, auth, direct, name, lay, how): + gds = (GDS_DIR / f"{lay}.gds").read_bytes() + url = f"/v1/models/planar_capacitance_{name}/predict" + # eps_r 11.45 is the default; a distinct option string keeps the two routes from sharing a cache entry + inputs = {"eps_r": 11.45} if how == "base64" else {} + if how == "multipart": + r = gated_client.post(url, files={"file": ("chip.gds", gds)}, data={"inputs": json.dumps(inputs)}, headers=auth) + else: + inputs["file_base64"] = base64.b64encode(gds).decode() + r = gated_client.post(url, json={"inputs": inputs}, headers=auth) + assert r.status_code == 200, r.text + b = r.json() + names, C = direct[name, lay] + assert b["outputs"]["names"] == names + assert np.array_equal(np.array(b["outputs"]["matrix_fF"]), C), np.abs(np.array(b["outputs"]["matrix_fF"]) - C).max() + assert b["metadata"]["checks"]["passed"], b["metadata"]["checks"] + assert b["outputs"]["sim_results"]["units"] == "fF" and b["metadata"]["n_conductors"] == len(names) + + +# ---------- errors, limits, cache, schema ---------- + +def err(r, status, code): + assert r.status_code == status, r.text + e = r.json()["error"] + assert e["code"] == code and isinstance(e["message"], str) and "model_id" in e + return e + + +def test_error_envelope(client, gated_client, auth): + err(client.post("/v1/models/nope/predict", json={"inputs": S}), 404, "unknown_model") + err(client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": {"qubit_frequency_GHz": 1.0}}), 400, "invalid_input") + err(client.post(f"/v1/models/{OLIVIA}/predict", content=b"{not json", headers={"content-type": "application/json"}), + 400, "invalid_input") + err(client.post(f"/v1/models/{OLIVIA}/predict", json={"options": {}}), 422, "validation_error") + e = err(client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": S, "options": {"include_scaled_outputs": "x"}}), + 422, "validation_error") + assert e["details"] + cap = "/v1/models/planar_capacitance_flagship/predict" + gds = (ROOT / "examples/interdigital.gds").read_bytes() + err(gated_client.post(cap, files={"file": ("x.gds", gds)}, data={"inputs": '{"ground_layer": "a"}'}, headers=auth), + 400, "invalid_input") + err(gated_client.post(cap, json={"inputs": {"file_base64": "%%%"}}, headers=auth), 400, "invalid_input") + err(gated_client.post(cap, json={"inputs": {"eps_r": "high"}}, headers=auth), 422, "validation_error") + err(gated_client.post(cap, files={"file": ("x.gds", b"not a gds")}, headers=auth), 400, "invalid_input") + + +def test_batch_and_scaled(client): + b = client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": [S, S], "options": {"include_scaled_outputs": True}}) + assert b.status_code == 200 + o = b.json()["outputs"] + assert len(o["predictions"]) == 2 and len(o["scaled_predictions"]) == 2 + err(client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": [S] * 1001}), 413, "too_large") + + +def test_upload_limit(gated_client, auth): + big = b"\0" * (21 * 2**20) + err(gated_client.post("/v1/models/planar_capacitance_flagship/predict", files={"file": ("x.gds", big)}, headers=auth), + 413, "too_large") + err(gated_client.post("/v1/models/planar_capacitance_flagship/predict", + json={"inputs": {"file_base64": base64.b64encode(big).decode()}}, headers=auth), + 413, "too_large") + + +def test_conductor_limit(gated_client, auth, tmp_path): + import gdstk + + lib = gdstk.Library(unit=1e-6, precision=1e-9) + cell = lib.new_cell("TOP") + cell.add(gdstk.rectangle((-50, -50), (1500, 0), layer=1, datatype=0)) + for i in range(71): + x = 20 * i + cell.add(gdstk.rectangle((x, 20), (x + 10, 30), layer=1, datatype=10)) + p = tmp_path / "many.gds" + lib.write_gds(str(p)) + e = err(gated_client.post("/v1/models/planar_capacitance_fast/predict", files={"file": ("x.gds", p.read_bytes())}, + headers=auth), 413, "too_large") + assert "71 conductors" in e["message"] + + +def test_queue_full(client): + slots = client.app.state.runner.slots + n = 0 + while slots.acquire(blocking=False): + n += 1 + try: + r = client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": {**S, "qubit_frequency_GHz": 4.123}}) + err(r, 429, "busy") + assert r.headers["retry-after"] == "30" + finally: + for _ in range(n): + slots.release() + assert n == int(os.environ.get("SQUADDS_ML_API_QUEUE", "8")) + + +def test_cache_hit(gated_client, auth): + gds = (GDS_DIR / "xmon.gds").read_bytes() if GDS_DIR.exists() else (ROOT / "examples/interdigital.gds").read_bytes() + url = "/v1/models/planar_capacitance_flagship/predict" + data = {"inputs": json.dumps({"thickness_um": 349.0})} + a = gated_client.post(url, files={"file": ("x.gds", gds)}, data=data, headers=auth).json() + t = time.perf_counter() + b = gated_client.post(url, files={"file": ("x.gds", gds)}, data=data, headers=auth).json() + wall = time.perf_counter() - t + assert a["cached"] is False and b["cached"] is True and b["outputs"] == a["outputs"] + assert b["timing_s"]["total"] < 0.05 and wall < 0.5 + + +def test_schema_and_detail(client, gated_client, auth): + t = client.get(f"/v1/models/{OLIVIA}/schema?format=tool").json() + assert t["name"] == f"squadds_{OLIVIA}" and set(t["input_schema"]["properties"]) == {"inputs", "options"} + s = client.get(f"/v1/models/{OLIVIA}/schema").json() + assert {"request", "response"} <= set(s) + t = gated_client.get("/v1/models/planar_capacitance_flagship/schema?format=tool", headers=auth).json() + props = t["input_schema"]["properties"]["inputs"]["properties"] + assert "file_base64" in props and all("description" in v for v in props.values()) + d = gated_client.get("/v1/models/planar_capacitance_flagship", headers=auth).json() + assert d["numbers"]["error_39_new_layouts"] == {"median_pct": 1.05, "mae_fF": 0.132, "rmse_fF": 0.188} + assert d["limits"]["max_conductors"] == 70 and d["example"]["file"] == "examples/interdigital.gds" + h = client.get("/v1/health").json() + assert h["models"] == {OLIVIA: "ready"} and h["build"]["registry_sha256"] diff --git a/warm.py b/warm.py new file mode 100644 index 0000000000000000000000000000000000000000..bdbed78cc295237b7fde205c9b4d19ac16b1c7f3 --- /dev/null +++ b/warm.py @@ -0,0 +1,23 @@ +"""Build-time warm-up without weights: the physics priors and the geometric embedding of the example layout compile every +numba kernel the capacitance models use, so the image carries the compiled cache.""" +import time + +from squadds.ml.capacitance import coarse_physics_prior, optimized_physics_prior, prepare_layout +from squadds.ml.capacitance import _runtime as RT +from squadds.ml.capacitance._core import api as A +from squadds.ml.capacitance._core import paper as PA +from squadds.ml.capacitance._core._tlsq.uge import blocks as B +from squadds.ml.capacitance._core._tlsq.uge.graph import scene_graph + +GDS = "examples/interdigital.gds" +for f in (optimized_physics_prior, coarse_physics_prior): + t = time.perf_counter() + r = f(GDS) + print("warm.py", f.__name__, r.names, round(time.perf_counter() - t, 1), "s", flush=True) +t = time.perf_counter() +with RT.LOCK: + RT.configure(2) + B.FAR_DECIMATION.update(k=64, d_far=100.0) + sc = A.scene_from_prepared(prepare_layout(GDS)) + PA.lt.add_tokens(sc, scene_graph(sc)) +print("warm.py embedding", round(time.perf_counter() - t, 1), "s", flush=True)