Download tests/test_v1.py from SQuADDS/squadds-ml-inference-api: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/SQuADDS/squadds-ml-inference-api/resolve/main/tests/test_v1.py
- Command line
-
hf download hf://spaces/SQuADDS/squadds-ml-inference-api/tests/test_v1.py
-
curl -L -o test_v1.py https://huggingface.co/spaces/SQuADDS/squadds-ml-inference-api/resolve/main/tests/test_v1.py
11.6 kB
| 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 ---------- | |
| def test_hidden_everywhere(hidden_client, auth, model_id, with_token): | |
| client = hidden_client | |
| 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(hidden_client): | |
| assert hidden_client.app.state.registry.fetched == ["SQuADDS/transmon-cross-hamiltonian-inverse"] | |
| # ---------- public (the released registry) ---------- | |
| def test_registry_capacitance_public(): | |
| import yaml | |
| reg = yaml.safe_load((ROOT / "registry.yaml").read_text()) | |
| assert {k: reg["models"][k]["visibility"] for k in CAP} == {"qcap": "public", "qcap-fast": "public"} | |
| def test_public_without_token_capacitance(client, model_id): | |
| assert model_id in [m["id"] for m in client.get("/v1/models").json()["models"]] | |
| assert client.get("/v1/health").json()["models"][model_id] == "ready" | |
| assert client.get(f"/v1/models/{model_id}").status_code == 200 | |
| ex = json.loads((ROOT / f"examples/{model_id}.json").read_text())["response"]["outputs"] | |
| r = client.post(f"/v1/models/{model_id}/predict", files={"file": ("x.gds", (ROOT / "examples/interdigital.gds").read_bytes())}) | |
| assert r.status_code == 200, r.text | |
| o = r.json()["outputs"] | |
| assert o["names"] == ex["names"] and o["matrix_fF"] == ex["matrix_fF"] | |
| # ---------- gated ---------- | |
| 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 ---------- | |
| 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 ("QCap", "QCap-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 | |
| def test_capacitance_equals_direct(gated_client, auth, direct, name, lay, how): | |
| gds = (GDS_DIR / f"{lay}.gds").read_bytes() | |
| url = f"/v1/models/{name.lower()}/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/qcap/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") | |
| for t in (0.5, 0, -3, "0.2"): | |
| e = err(gated_client.post(cap, files={"file": ("x.gds", gds)}, data={"inputs": json.dumps({"thickness_um": t})}, headers=auth), | |
| 400, "invalid_input") | |
| assert "at least 1" in e["message"], e | |
| 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/qcap/predict", files={"file": ("x.gds", big)}, headers=auth), | |
| 413, "too_large") | |
| err(gated_client.post("/v1/models/qcap/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/qcap-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/qcap/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, hidden_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/qcap/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/qcap", 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 = hidden_client.get("/v1/health").json() | |
| assert h["models"] == {OLIVIA: "ready"} and h["build"]["registry_sha256"] | |
| assert client.get("/v1/health").json()["models"] == {OLIVIA: "ready", **{k: "ready" for k in CAP}} | |
| def test_llms_txt_lists_public_models_only(client, hidden_client): | |
| assert all(k in client.get("/llms.txt").text for k in CAP) | |
| r = hidden_client.get("/llms.txt") | |
| assert r.status_code == 200 and r.headers["content-type"].startswith("text/plain") | |
| assert "transmon_cross_hamiltonian_inverse" in r.text and "/v1/models/{model_id}/schema?format=tool" in r.text | |
| assert "qcap" not in r.text.lower() and "planar_capacitance" not in r.text | |