From d37b7629595401e21fe7fbe1955722a6a6466581 Mon Sep 17 00:00:00 2001 From: Arseniy Senokosov <70952998+sarseniy@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:18:22 +0200 Subject: [PATCH 1/5] feat(photonics): add a JSON codec for photonic circuit specs --- pyproject.toml | 1 + src/eigenkit/photonics/wire.py | 93 +++++++++++++++++++++++++++ tests/photonics/test_wire.py | 111 +++++++++++++++++++++++++++++++++ 3 files changed, 205 insertions(+) create mode 100644 src/eigenkit/photonics/wire.py create mode 100644 tests/photonics/test_wire.py diff --git a/pyproject.toml b/pyproject.toml index 637b369..d5bef67 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -363,6 +363,7 @@ source_modules = [ "eigenkit.photonics.ir", "eigenkit.photonics.executor", "eigenkit.photonics.gradients", + "eigenkit.photonics.wire", ] forbidden_modules = ["perceval", "torch", "pennylane", "qiskit", "braket", "sklearn", "qulacs"] diff --git a/src/eigenkit/photonics/wire.py b/src/eigenkit/photonics/wire.py new file mode 100644 index 0000000..1b75fcb --- /dev/null +++ b/src/eigenkit/photonics/wire.py @@ -0,0 +1,93 @@ +"""The JSON encoding of photonic circuits. + +This module is the photonic counterpart of `core.wire`. It turns a +`PhotonicCircuitSpec` into plain JSON data and back, so that a circuit can be sent +to a service or stored. It holds only data, and uses neither Perceval nor NumPy. + +The angles of the components use the same encoding as the parameters of the qubit +circuits, so a `WeightRef` or an `InputRef` means the same thing in both. +""" + +from __future__ import annotations + +from ..core.blocks import _param_from_json, _param_to_json +from .ir import BeamSplitter, Permutation, PhaseShifter, PhotonicCircuitSpec + + +def _component_to_json(comp) -> dict: + if isinstance(comp, PhaseShifter): + return {"c": "PS", "mode": int(comp.mode), "phi": _param_to_json(comp.phi)} + if isinstance(comp, BeamSplitter): + return { + "c": "BS", + "modes": [int(m) for m in comp.modes], + "theta": _param_to_json(comp.theta), + "phi": _param_to_json(comp.phi), + } + if isinstance(comp, Permutation): + return {"c": "PERM", "perm": [int(m) for m in comp.perm]} + raise TypeError(f"unknown photonic component: {type(comp).__name__}") + + +def _component_from_json(data: dict): + tag = data["c"] + if tag == "PS": + return PhaseShifter(data["mode"], _param_from_json(data["phi"])) + if tag == "BS": + return BeamSplitter( + tuple(data["modes"]), + _param_from_json(data["theta"]), + _param_from_json(data["phi"]), + ) + if tag == "PERM": + return Permutation(tuple(data["perm"])) + raise ValueError(f"unknown photonic component in JSON: {tag!r}") + + +def photonic_spec_to_json(spec: PhotonicCircuitSpec) -> dict: + """Encode a photonic circuit as JSON data. + + Args: + spec (PhotonicCircuitSpec): The circuit to encode. + + Returns: + A dictionary with the keys `"n_modes"`, `"n_weights"`, `"n_inputs"`, + `"input_state"` and `"components"`. Every integer in it is a plain + Python `int`, so `json.dumps` accepts it. + """ + return { + "n_modes": int(spec.n_modes), + "n_weights": int(spec.n_weights), + "n_inputs": int(spec.n_inputs), + "input_state": [int(n) for n in spec.input_state], + "components": [_component_to_json(comp) for comp in spec.components], + } + + +def photonic_spec_from_json(data: dict) -> PhotonicCircuitSpec: + """Build a photonic circuit from the data that `photonic_spec_to_json` produced. + + The circuit goes through the same checks as one built by hand. + + Args: + data (dict): The encoded circuit. + + Returns: + The decoded `PhotonicCircuitSpec`. + + Raises: + TypeError: If `data` is not a dictionary. + KeyError: If a key is missing. + ValueError: If a component is unknown, or the circuit is not valid. + """ + if not isinstance(data, dict): + raise TypeError( + f"a photonic circuit is encoded as a dict, got {type(data).__name__}" + ) + return PhotonicCircuitSpec( + n_modes=data["n_modes"], + n_weights=data["n_weights"], + n_inputs=data["n_inputs"], + components=tuple(_component_from_json(comp) for comp in data["components"]), + input_state=tuple(data["input_state"]), + ) diff --git a/tests/photonics/test_wire.py b/tests/photonics/test_wire.py new file mode 100644 index 0000000..29e6714 --- /dev/null +++ b/tests/photonics/test_wire.py @@ -0,0 +1,111 @@ +"""The JSON codec for photonic circuit specs.""" + +import json +import subprocess +import sys + +import numpy as np +import pytest + +from eigenkit.core.ir import Constant, InputRef, WeightRef +from eigenkit.photonics.ir import ( + BeamSplitter, + Permutation, + PhaseShifter, + PhotonicCircuitSpec, +) +from eigenkit.photonics.reservoir import random_reservoir_spec +from eigenkit.photonics.wire import photonic_spec_from_json, photonic_spec_to_json + + +SPEC = PhotonicCircuitSpec( + n_modes=4, + n_weights=1, + n_inputs=1, + components=( + PhaseShifter(1, InputRef(0)), + BeamSplitter((0, 1), WeightRef(0)), + Permutation((1, 0, 2, 3)), + ), + input_state=(1, 0, 1, 0), +) +GOLDEN = { + "n_modes": 4, + "n_weights": 1, + "n_inputs": 1, + "input_state": [1, 0, 1, 0], + "components": [ + {"c": "PS", "mode": 1, "phi": {"t": "InputRef", "i": 0}}, + { + "c": "BS", + "modes": [0, 1], + "theta": {"t": "WeightRef", "i": 0}, + "phi": {"t": "Constant", "v": 0.0}, + }, + {"c": "PERM", "perm": [1, 0, 2, 3]}, + ], +} + + +def test_golden_encoding(): + assert photonic_spec_to_json(SPEC) == GOLDEN + + +def test_golden_decoding(): + assert photonic_spec_from_json(GOLDEN) == SPEC + + +def test_round_trip_of_a_reservoir(): + spec, _ = random_reservoir_spec( + 4, 2, depth=2, input_state=(1, 1, 0, 0), rng=np.random.default_rng(0) + ) + wire = json.loads(json.dumps(photonic_spec_to_json(spec))) + assert photonic_spec_from_json(wire) == spec + + +def test_numpy_scalars_encode_as_plain_json(): + spec = PhotonicCircuitSpec( + n_modes=np.int64(2), + n_weights=0, + n_inputs=0, + components=(PhaseShifter(np.int64(0), Constant(np.float64(0.5))),), + input_state=(np.int64(1), np.int64(0)), + ) + data = photonic_spec_to_json(spec) + assert json.loads(json.dumps(data)) == data + assert type(data["n_modes"]) is int + assert type(data["components"][0]["mode"]) is int + assert type(data["input_state"][0]) is int + + +@pytest.mark.parametrize( + "bad, error", + [ + ({**GOLDEN, "components": [{"c": "XX"}]}, ValueError), + ({k: v for k, v in GOLDEN.items() if k != "input_state"}, KeyError), + ( + { + **GOLDEN, + "components": [ + { + "c": "BS", + "modes": [0, 2], + "theta": {"t": "Constant", "v": 0.0}, + "phi": {"t": "Constant", "v": 0.0}, + } + ], + }, + ValueError, + ), + ({**GOLDEN, "input_state": [1, 0, 1]}, ValueError), + ("not a dict", TypeError), + ], +) +def test_malformed_input_is_refused(bad, error): + with pytest.raises(error): + photonic_spec_from_json(bad) + + +def test_importing_the_codec_loads_no_perceval(): + code = "import sys, eigenkit.photonics.wire; assert 'perceval' not in sys.modules" + subprocess.run([sys.executable, "-c", code], check=True) From 614cc75ab51fb67e3c6589d3730372256da407bb Mon Sep 17 00:00:00 2001 From: Arseniy Senokosov <70952998+sarseniy@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:18:22 +0200 Subject: [PATCH 2/5] feat(photonics): build and read Quandela Cloud jobs offline, with batches --- .../photonics/backends/perceval_remote.py | 182 ++++++++++++++++ .../fixtures/quandela_platform_sim_slos.json | 18 ++ .../fixtures/quandela_result_batch.json | 8 + .../fixtures/quandela_result_single.json | 8 + tests/photonics/test_cloud_job.py | 195 ++++++++++++++++++ 5 files changed, 411 insertions(+) create mode 100644 tests/photonics/fixtures/quandela_platform_sim_slos.json create mode 100644 tests/photonics/fixtures/quandela_result_batch.json create mode 100644 tests/photonics/fixtures/quandela_result_single.json create mode 100644 tests/photonics/test_cloud_job.py diff --git a/src/eigenkit/photonics/backends/perceval_remote.py b/src/eigenkit/photonics/backends/perceval_remote.py index e61ffe6..2d23bb1 100644 --- a/src/eigenkit/photonics/backends/perceval_remote.py +++ b/src/eigenkit/photonics/backends/perceval_remote.py @@ -29,11 +29,16 @@ from __future__ import annotations import contextlib +import json import os import time import warnings +import numpy as np + +from ...core.ir import resolve from ...core.provider import CostWarning +from ..ir import BeamSplitter, PhaseShifter from .perceval_backend import build_perceval_circuit, fock_tuple @@ -79,6 +84,183 @@ def _counts_to_distribution(counts, n_modes): return {fock_tuple(state, n_modes): count / total for state, count in counts.items()} +class _CaptureHandler: + """A stand-in for Perceval's cloud handler that opens no connection. + + It answers the platform details that the caller already holds, and keeps the + body of the job instead of sending it. + """ + + def __init__(self, platform: str, platform_details: dict) -> None: + self.name = platform + self.url = "" + self.token = "" + self.proxies: dict = {} + self._platform_details = platform_details + self.body: dict | None = None + + def fetch_platform_details(self) -> dict: + return self._platform_details + + def create_job(self, cloud_data: dict) -> str: + self.body = cloud_data + return "not-submitted" + + +def _parametric_circuit(spec): + """Build the circuit with one named Perceval parameter per angle. + + Returns the circuit and the angle expressions, in the order of the parameters + `a0`, `a1`, and so on. A batch then needs one number per angle and per row, + whatever the expressions are. + """ + import perceval as pcvl + + circ = pcvl.Circuit(spec.n_modes) + angles = [] + + def placeholder(expression): + angles.append(expression) + return pcvl.P(f"a{len(angles) - 1}") + + for comp in spec.components: + if isinstance(comp, PhaseShifter): + circ.add(comp.mode, pcvl.PS(placeholder(comp.phi))) + elif isinstance(comp, BeamSplitter): + theta = placeholder(comp.theta) + circ.add( + tuple(comp.modes), pcvl.BS(theta=theta, phi_tr=placeholder(comp.phi)) + ) + else: + circ.add(0, pcvl.PERM(list(comp.perm))) + return circ, angles + + +def cloud_job_body( + spec, + weights, + inputs, + *, + platform: str, + platform_details: dict, + shots: int, + min_detected_photons: int | None = None, + job_name: str, +) -> dict: + """Build the body of a Quandela Cloud job, without a connection or a token. + + The body is the JSON that Perceval itself sends to create a job (`POST + /api/jobs`). A service that holds the token can send it later. The job samples + the circuit once for each row of `inputs`, so a batch is one job. + + Args: + spec (PhotonicCircuitSpec): The circuit to run. + weights (np.ndarray): The 1-D weight vector, used for every row. + inputs (np.ndarray): One 1-D input vector, or a 2-D array with one input + vector in each row. It needs at least one row. + platform (str): The name of the Quandela Cloud platform, for example + `"sim:slos"`. + platform_details (dict): The description of the platform, as the service + returns it (`GET /api/platforms/{name}/processor`). Perceval needs it to + prepare a job. + shots (int): The number of samples asked for in each row. It is also the + limit on the shots of each row. + min_detected_photons (int | None): Keep only the shots that detect at + least this many photons. The default is the number of photons in the + input state. + job_name (str): The name of the job on Quandela Cloud. + + Returns: + The body of the request, as a dictionary that `json.dumps` accepts. + + Raises: + ValueError: If `weights` is not 1-D with the length that the spec declares, + or if `inputs` is not one or more rows of that length. + """ + import perceval as pcvl + from perceval.algorithm import Sampler + + weights = np.asarray(weights, dtype=np.float64) + if weights.shape != (spec.n_weights,): + raise ValueError( + f"weights has shape {weights.shape} but the spec needs ({spec.n_weights},)" + ) + rows = np.asarray(inputs, dtype=np.float64) + if rows.ndim == 1: + rows = rows[np.newaxis, :] + if rows.ndim != 2 or rows.shape[0] < 1 or rows.shape[1] != spec.n_inputs: + raise ValueError( + f"inputs has shape {np.shape(inputs)} but the spec needs ({spec.n_inputs},) " + f"or (rows, {spec.n_inputs}) with at least one row" + ) + + handler = _CaptureHandler(platform, platform_details) + processor = pcvl.RemoteProcessor(rpc_handler=handler) + circuit, angles = _parametric_circuit(spec) + processor.set_circuit(circuit) + processor.min_detected_photons_filter( + spec.n_photons if min_detected_photons is None else min_detected_photons + ) + processor.with_input(pcvl.BasicState(list(spec.input_state))) + shots = int(shots) + sampler = Sampler(processor, max_shots_per_call=shots) + sampler.add_iteration_list( + [ + { + "circuit_params": { + f"a{index}": float(resolve(angle, weights, row)) + for index, angle in enumerate(angles) + }, + "max_samples": shots, + "max_shots": shots, + } + for row in rows + ] + ) + job = sampler.sample_count + job.name = job_name + job.execute_async(shots) + return handler.body + + +def cloud_job_counts(result: dict, n_modes: int) -> list[dict]: + """Read the counts of a finished Quandela Cloud job. + + Args: + result (dict): The result of the job, as the service returns it (`GET + /api/jobs/{id}/result`). + n_modes (int): The number of modes of the circuit. + + Returns: + One dictionary `{photon_counts: count}` for each row of the job, in the + order of the rows. A job with a single run gives a list of one. A row + in which no shot passed the photon filter is an empty dictionary. + + Raises: + ValueError: If the result holds no counts, for example because the job + failed or was cancelled. + """ + from perceval.serialization import deserialize + + inner = result.get("results") if isinstance(result, dict) else None + if isinstance(inner, str): + with contextlib.suppress(ValueError): + inner = json.loads(inner) + if isinstance(inner, dict) and "results_list" in inner: + entries = inner["results_list"] + elif isinstance(inner, dict) and "results" in inner: + entries = [inner] + else: + raise ValueError(f"the job result has no counts: {str(inner)[:200]!r}") + return [ + { + fock_tuple(state, n_modes): int(count) + for state, count in deserialize(entry["results"]).items() + } + for entry in entries + ] + + class RemoteJobHandle: """A handle to a Quandela Cloud job that is running. diff --git a/tests/photonics/fixtures/quandela_platform_sim_slos.json b/tests/photonics/fixtures/quandela_platform_sim_slos.json new file mode 100644 index 0000000..1c613b5 --- /dev/null +++ b/tests/photonics/fixtures/quandela_platform_sim_slos.json @@ -0,0 +1,18 @@ +{ + "status": "available", + "type": "simulator", + "perfs": {}, + "specs": { + "available_commands": [ + "probs", + "samples", + "sample_count" + ], + "constraints": { + "max_photon_count": 12, + "min_photon_count": 2, + "support_multi_photon": true + }, + "parameters": {} + } +} diff --git a/tests/photonics/fixtures/quandela_result_batch.json b/tests/photonics/fixtures/quandela_result_batch.json new file mode 100644 index 0000000..4b934e4 --- /dev/null +++ b/tests/photonics/fixtures/quandela_result_batch.json @@ -0,0 +1,8 @@ +{ + "duration": 1, + "intermediate_results": [], + "job_id": "00000000-0000-4000-8000-000000000000", + "results": "{\"results_list\": [{\"results\": \":PCVL:zip:eJyzCnAO87FyCnbOL80rsaquMdIxAEE7WyNz6xpDMMfQztbQFMQxhMiYWlrXgMSNQBwTE4gyQzAHJGEEUWUI5hhC9UN0ACXhbEOQuLFpLQATEx5/\", \"global_perf\": 1.0000000000000004, \"iteration\": {\"circuit_params\": {\"a0\": 4.002148315014479, \"a1\": 0.0, \"a10\": -0.7514334470008721, \"a11\": 0.34124882938726064, \"a12\": 4.583562073612696, \"a13\": 0.0, \"a14\": 3.415696558991173, \"a15\": 0.0, \"a16\": 5.8752333142921085, \"a17\": 0.0, \"a18\": 5.126159064066656, \"a19\": 0.017206504032783308, \"a2\": 1.6951199159934145, \"a20\": 5.3872299529679575, \"a21\": 0.21102439329246717, \"a22\": 4.584560380312186, \"a23\": 0.0, \"a24\": 1.1036768144935105, \"a25\": 0.0, \"a26\": 5.423513122375916, \"a27\": 0.0, \"a28\": 3.402101183476623, \"a29\": 1.8831453470115125, \"a3\": 0.0, \"a30\": 2.6558221377616955, \"a31\": 0.17793774164533058, \"a4\": 0.25744424357926954, \"a5\": 0.0, \"a6\": 0.10384619671527331, \"a7\": 5.109927617709579, \"a8\": 5.735012432197602, \"a9\": 3.811604993109835}, \"max_samples\": 200, \"max_shots\": 200}}, {\"results\": \":PCVL:zip:eJyzCnAO87FyCnbOL80rsaquMdIxAEE7WyMD6xpDMMfQztYQxDaESJhYWteAhI1gHJC4IYhjaAaSMYIoMzQEcQwh+k0hWoCSdrZQ7YYgcRODWgARyR5/\", \"global_perf\": 0.9999999999999996, \"iteration\": {\"circuit_params\": {\"a0\": 4.002148315014479, \"a1\": 0.0, \"a10\": 0.2943790231485002, \"a11\": 0.2307702229625077, \"a12\": 4.583562073612696, \"a13\": 0.0, \"a14\": 3.415696558991173, \"a15\": 0.0, \"a16\": 5.8752333142921085, \"a17\": 0.0, \"a18\": 5.126159064066656, \"a19\": 0.017206504032783308, \"a2\": 1.6951199159934145, \"a20\": 5.3872299529679575, \"a21\": 0.21102439329246717, \"a22\": 4.584560380312186, \"a23\": 0.0, \"a24\": 1.1036768144935105, \"a25\": 0.0, \"a26\": 5.423513122375916, \"a27\": 0.0, \"a28\": 3.402101183476623, \"a29\": 1.8831453470115125, \"a3\": 0.0, \"a30\": 2.6558221377616955, \"a31\": 0.17793774164533058, \"a4\": 0.25744424357926954, \"a5\": 0.0, \"a6\": 0.10384619671527331, \"a7\": 5.109927617709579, \"a8\": 5.735012432197602, \"a9\": 3.811604993109835}, \"max_samples\": 200, \"max_shots\": 200}}, {\"results\": \":PCVL:zip:eJyzCnAO87FyCnbOL80rsaquMdIxAEE7W1Mz6xpDMMfQztYExDaESBgBJYCCIK6drSGIbaBjBGKbGUJ0gCXAiowgOkwgioB8oAYDCMcQZKyxUS0A9rceRg==\", \"global_perf\": 0.9999999999999996, \"iteration\": {\"circuit_params\": {\"a0\": 4.002148315014479, \"a1\": 0.0, \"a10\": -0.23264489147623313, \"a11\": 0.994419871578422, \"a12\": 4.583562073612696, \"a13\": 0.0, \"a14\": 3.415696558991173, \"a15\": 0.0, \"a16\": 5.8752333142921085, \"a17\": 0.0, \"a18\": 5.126159064066656, \"a19\": 0.017206504032783308, \"a2\": 1.6951199159934145, \"a20\": 5.3872299529679575, \"a21\": 0.21102439329246717, \"a22\": 4.584560380312186, \"a23\": 0.0, \"a24\": 1.1036768144935105, \"a25\": 0.0, \"a26\": 5.423513122375916, \"a27\": 0.0, \"a28\": 3.402101183476623, \"a29\": 1.8831453470115125, \"a3\": 0.0, \"a30\": 2.6558221377616955, \"a31\": 0.17793774164533058, \"a4\": 0.25744424357926954, \"a5\": 0.0, \"a6\": 0.10384619671527331, \"a7\": 5.109927617709579, \"a8\": 5.735012432197602, \"a9\": 3.811604993109835}, \"max_samples\": 200, \"max_shots\": 200}}]}", + "results_type": null, + "shots": 0 +} diff --git a/tests/photonics/fixtures/quandela_result_single.json b/tests/photonics/fixtures/quandela_result_single.json new file mode 100644 index 0000000..ec05583 --- /dev/null +++ b/tests/photonics/fixtures/quandela_result_single.json @@ -0,0 +1,8 @@ +{ + "duration": 1, + "intermediate_results": [], + "job_id": "00000000-0000-4000-8000-000000000000", + "results": "{\"results\": \":PCVL:zip:eJyzCnAO87FyCnbOL80rsaquMdQxAEJDO1sjUzNrIA/Mt7M1NDGwrgHJGIF5hhbWYJWGEJ4xSM4IqtLIHMQzhJhiaAzVZwjmGZrVAgA8Jhqu\", \"global_perf\": 1.0}", + "results_type": null, + "shots": 0 +} diff --git a/tests/photonics/test_cloud_job.py b/tests/photonics/test_cloud_job.py new file mode 100644 index 0000000..70e9c0d --- /dev/null +++ b/tests/photonics/test_cloud_job.py @@ -0,0 +1,195 @@ +"""Building and reading a Quandela Cloud job without a connection.""" + +import json +from pathlib import Path + +import numpy as np +import pytest + + +pcvl = pytest.importorskip("perceval") + +from eigenkit.core.ir import Constant, resolve # noqa: E402 +from eigenkit.photonics.backends.perceval_remote import ( # noqa: E402 + cloud_job_body, + cloud_job_counts, +) +from eigenkit.photonics.ir import ( # noqa: E402 + BeamSplitter, + PhaseShifter, + PhotonicCircuitSpec, +) +from eigenkit.photonics.reservoir import random_reservoir_spec # noqa: E402 + + +FIXTURES = Path(__file__).parent / "fixtures" +DETAILS = json.loads((FIXTURES / "quandela_platform_sim_slos.json").read_text()) +SPEC, WEIGHTS = random_reservoir_spec( + 4, 2, depth=2, input_state=(1, 1, 0, 0), rng=np.random.default_rng(0) +) + + +def _body(inputs, **overrides): + kwargs = { + "platform": "sim:slos", + "platform_details": DETAILS, + "shots": 200, + "job_name": "eo-test", + **overrides, + } + return cloud_job_body(SPEC, WEIGHTS, inputs, **kwargs) + + +def _angles(spec): + for comp in spec.components: + if isinstance(comp, PhaseShifter): + yield comp.phi + elif isinstance(comp, BeamSplitter): + yield comp.theta + yield comp.phi + + +def _result(name): + return json.loads((FIXTURES / name).read_text()) + + +def test_body_names_the_platform_and_the_job(): + body = _body(np.zeros(2)) + assert body["platform_name"] == "sim:slos" + assert body["job_name"] == "eo-test" + assert body["payload"]["command"] == "sample_count" + + +def test_one_iteration_per_row_with_the_resolved_angles(): + rows = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]) + iterator = _body(rows)["payload"]["iterator"] + assert len(iterator) == 3 + for row, iteration in zip(rows, iterator, strict=True): + values = sorted(iteration["circuit_params"].values()) + expected = sorted(float(resolve(e, WEIGHTS, row)) for e in _angles(SPEC)) + assert values == pytest.approx(expected) + + +def test_one_d_inputs_are_a_batch_of_one(): + assert len(_body(np.array([0.1, 0.2]))["payload"]["iterator"]) == 1 + + +def test_shots_set_the_samples_and_the_shot_limit_of_every_row(): + for iteration in _body(np.zeros((2, 2)), shots=321)["payload"]["iterator"]: + assert iteration["max_samples"] == 321 + assert iteration["max_shots"] == 321 + + +def test_the_experiment_carries_the_modes_and_the_input_state(): + body = _body(np.zeros(2)) + experiment = pcvl.serialization.deserialize(body["payload"]["experiment"]) + assert experiment.m == 4 + assert list(experiment.input_state) == [1, 1, 0, 0] + + +def test_the_photon_filter_defaults_to_the_input_photons(): + default = pcvl.serialization.deserialize(_body(np.zeros(2))["payload"]["experiment"]) + lowered = pcvl.serialization.deserialize( + _body(np.zeros(2), min_detected_photons=1)["payload"]["experiment"] + ) + assert default.min_photons_filter == 2 + assert lowered.min_photons_filter == 1 + + +def test_body_is_json_and_survives_numpy_rows(): + body = _body(np.zeros((2, 2), dtype=np.float32)) + assert json.loads(json.dumps(body)) == body + + +def test_no_connection_is_opened(monkeypatch): + def refuse(*args, **kwargs): + raise AssertionError("network call") + + monkeypatch.setattr("requests.get", refuse) + monkeypatch.setattr("requests.post", refuse) + _body(np.zeros((2, 2))) + + +@pytest.mark.parametrize( + "inputs", [np.zeros((0, 2)), np.zeros((2, 3)), np.zeros((2, 2, 2)), np.zeros(3)] +) +def test_a_wrong_batch_shape_is_refused(inputs): + with pytest.raises(ValueError, match="inputs"): + _body(inputs) + + +def test_two_d_weights_are_refused(): + with pytest.raises(ValueError, match="weights"): + cloud_job_body( + SPEC, + np.zeros((2, SPEC.n_weights)), + np.zeros(2), + platform="sim:slos", + platform_details=DETAILS, + shots=1, + job_name="x", + ) + + +def test_a_circuit_without_inputs_keeps_its_row_count(): + spec = PhotonicCircuitSpec( + n_modes=2, + n_weights=0, + n_inputs=0, + components=(BeamSplitter((0, 1), Constant(np.pi / 2)),), + input_state=(1, 1), + ) + body = cloud_job_body( + spec, + np.array([]), + np.zeros((3, 0)), + platform="sim:slos", + platform_details=DETAILS, + shots=10, + job_name="x", + ) + assert len(body["payload"]["iterator"]) == 3 + + +def test_counts_of_a_single_run(): + (counts,) = cloud_job_counts(_result("quandela_result_single.json"), 4) + assert all(isinstance(key, tuple) and len(key) == 4 for key in counts) + assert all(type(n) is int for key in counts for n in key) + assert sum(counts.values()) == 1000 + + +def test_counts_of_a_batch_keep_the_row_order(): + result = _result("quandela_result_batch.json") + rows = cloud_job_counts(result, 4) + assert len(rows) == 3 + assert all(sum(row.values()) == 200 for row in rows) + entries = json.loads(result["results"])["results_list"] + for row, entry in zip(rows, entries, strict=True): + direct = pcvl.serialization.deserialize(entry["results"]) + assert sum(row.values()) == sum(direct.values()) + assert row == { + tuple(int(n) for n in state): count for state, count in direct.items() + } + + +def test_a_row_with_no_surviving_shot_is_empty(): + result = _result("quandela_result_batch.json") + inner = json.loads(result["results"]) + inner["results_list"][1]["results"] = pcvl.serialization.serialize(pcvl.BSCount()) + result["results"] = json.dumps(inner) + rows = cloud_job_counts(result, 4) + assert rows[1] == {} + assert rows[0] and rows[2] + + +@pytest.mark.parametrize( + "results", [None, "null", json.dumps("Error: Incorrect padding"), json.dumps({})] +) +def test_a_job_without_counts_is_refused(results): + with pytest.raises(ValueError, match="no counts"): + cloud_job_counts({"results": results, "job_id": "x"}, 4) + + +def test_a_result_without_the_results_key_is_refused(): + with pytest.raises(ValueError, match="no counts"): + cloud_job_counts({"job_id": "x"}, 4) From 83fd28ef85b63ac826d204c2fc6d58fd2ee75387 Mon Sep 17 00:00:00 2001 From: Arseniy Senokosov <70952998+sarseniy@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:18:22 +0200 Subject: [PATCH 3/5] feat(photonics): run a reservoir as one batch when the executor offers it --- src/eigenkit/photonics/reservoir.py | 16 +++++++-- tests/photonics/test_reservoir.py | 50 +++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/src/eigenkit/photonics/reservoir.py b/src/eigenkit/photonics/reservoir.py index 141caa7..9705c7e 100644 --- a/src/eigenkit/photonics/reservoir.py +++ b/src/eigenkit/photonics/reservoir.py @@ -203,7 +203,10 @@ def run_photonic_reservoir( weights (np.ndarray): The frozen weights of the reservoir. sequences (np.ndarray): The input sequences, of shape `(B, T, F)`. executor (Executor | None): The executor that runs each step. The default - is `PercevalBackend()`. + is `PercevalBackend()`. If its compiled circuit has a method + `run_batch(weights, rows)`, it is called once with all the steps, as + the rows of a 2-D array, and returns one distribution for each row. A + remote executor uses it to send one job instead of one job per step. policy (Stateless | None): The policy whose `expand_inputs` turns each timestep into the circuit's `n_inputs` values (`window * F`). The default is `Stateless(window=1)`. Policies that carry the state from one @@ -255,9 +258,16 @@ def run_photonic_reservoir( compiled = executor.compile(spec) flat = inputs_bt.reshape(batch * timesteps, spec.n_inputs) + if hasattr(compiled, "run_batch"): + dists = compiled.run_batch(weights, flat) + if len(dists) != len(flat): + raise RuntimeError( + f"the executor returned {len(dists)} distributions for {len(flat)} rows" + ) + else: + dists = [compiled.run(weights, x) for x in flat] rows = np.empty((batch * timesteps, n_features), dtype=np.float64) - for row, x in enumerate(flat): - dist = compiled.run(weights, x) + for row, dist in enumerate(dists): if features == "fock": rows[row] = fock_probability_features(dist, basis) else: diff --git a/tests/photonics/test_reservoir.py b/tests/photonics/test_reservoir.py index 2f8d8a6..5245174 100644 --- a/tests/photonics/test_reservoir.py +++ b/tests/photonics/test_reservoir.py @@ -9,6 +9,7 @@ import numpy as np import pytest +from eigenkit.photonics import PercevalBackend from eigenkit.photonics.reservoir import ( fock_basis, photon_number_features, @@ -173,3 +174,52 @@ def test_mse(x_matrix): # The linear-on-raw baseline can't fit a product (best linear fit ~ 0 -> MSE ~ var). assert reservoir_mse < 0.4 * raw_mse assert reservoir_mse < 0.3 * target_var + + +class _BatchCompiled: + """A compiled object that also offers `run_batch`, as a remote executor does.""" + + def __init__(self, inner, *, batch_result=None): + self.inner = inner + self.batch_result = batch_result + self.batches = [] + self.single_runs = 0 + + def run(self, weights, inputs): + self.single_runs += 1 + return self.inner.run(weights, inputs) + + def run_batch(self, weights, rows): + self.batches.append(np.shape(rows)) + if self.batch_result is not None: + return self.batch_result + return [self.inner.run(weights, row) for row in rows] + + +class _BatchExecutor: + def __init__(self, **compiled_kwargs): + self.compiled_kwargs = compiled_kwargs + self.compiled = None + + def compile(self, spec): + inner = PercevalBackend().compile(spec) + self.compiled = _BatchCompiled(inner, **self.compiled_kwargs) + return self.compiled + + +def test_run_batch_is_used_once_when_the_executor_has_it(): + spec, weights = random_reservoir_spec(3, 1, rng=np.random.default_rng(0)) + sequences = np.random.default_rng(1).uniform(-1, 1, (2, 5, 1)) + executor = _BatchExecutor() + batched = run_photonic_reservoir(spec, weights, sequences, executor=executor) + looped = run_photonic_reservoir(spec, weights, sequences) + assert executor.compiled.batches == [(10, 1)] + assert executor.compiled.single_runs == 0 + np.testing.assert_allclose(batched, looped) + + +def test_a_batch_of_the_wrong_length_is_refused(): + spec, weights = random_reservoir_spec(3, 1, rng=np.random.default_rng(0)) + executor = _BatchExecutor(batch_result=[]) + with pytest.raises(RuntimeError, match="10 rows"): + run_photonic_reservoir(spec, weights, np.zeros((2, 5, 1)), executor=executor) From 0664d5de9e3e944214ffa674b30982479cf347c4 Mon Sep 17 00:00:00 2001 From: Arseniy Senokosov <70952998+sarseniy@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:18:22 +0200 Subject: [PATCH 4/5] docs(photonics): describe the Router path and batched runs --- ARCHITECTURE.md | 1 + docs/user-guide/photonics.md | 36 ++++++++++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 0a1353e..0d028da 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -664,6 +664,7 @@ src/eigenkit/ │ ├── executor.py ← Executor / Compiled protocol + lazy executor registry │ ├── gradients.py ← photonic parameter-shift + finite-difference jacobians │ ├── reservoir.py ← photonic reservoir (fixed interferometer) +│ ├── wire.py ← JSON codec for PhotonicCircuitSpec │ ├── torch.py ← PhotonicCircuit nn.Module (loaded lazily) │ └── backends/ │ ├── perceval_backend.py ← Perceval SLOS executor (perceval imported lazily) diff --git a/docs/user-guide/photonics.md b/docs/user-guide/photonics.md index a28a203..d50398c 100644 --- a/docs/user-guide/photonics.md +++ b/docs/user-guide/photonics.md @@ -243,6 +243,37 @@ fails, or if the post-selection on the number of detected photons and the live test marked `qpu` in `tests/photonics/test_quandela_cloud.py`, which you run with `pytest -m qpu` and a token set. +## Running through the EigenOrbit Router + +A photonic circuit can also reach Quandela Cloud through the +[EigenOrbit Router](https://router.eigenorbit.com), with a Router API key in place of +a Quandela token. The executor is `RouterPhotonicBackend`, from the package +`eigenorbit-router-client` (version 0.4 or later). It is used like the other two +executors, so a circuit moves from the local simulator to the Router when you replace +the executor. The photonic devices of the Router are in limited preview. + +```python +from eigenorbit_router_client import RouterConfig, RouterPhotonicBackend + +from eigenkit.photonics.reservoir import run_photonic_reservoir + +router = RouterPhotonicBackend(RouterConfig(device="quandela/sim_slos", shots=2000)) +states = run_photonic_reservoir(spec, weights, sequences, executor=router) +``` + +The reservoir sends all its time steps as **one** job, because the compiled circuit of +this executor has a method `run_batch(weights, rows)`. `run_photonic_reservoir` calls +it once when an executor offers it, and calls `run` for each step when it does not, as +with the local `PercevalBackend`. The results are sampled, so gradients are not +available, as on Quandela Cloud. + +Two functions support services that submit jobs for their users, as the Router does. +`cloud_job_body` builds the request that creates a Quandela Cloud job, with one run +for each row of inputs, and `cloud_job_counts` reads the counts of a finished job. +Both are in `eigenkit.photonics.backends.perceval_remote`, and neither opens a +connection nor needs a token. `eigenkit.photonics.wire` encodes a +`PhotonicCircuitSpec` as JSON data, and decodes it. + ## How it maps to the qubit core The photonics package has the same layers as the core, for a different model of @@ -268,8 +299,9 @@ adapter belongs to the photonics package, not to the qubit `torch/` package. The qubit statevector of size \(2^n\). - **Execution on Quandela Cloud**, on a real QPU or a cloud simulator, goes through `QuandelaCloudBackend`. The results are sampled, so there are no gradients. -- **One scalar observable is evaluated at a time, for one sample.** There is no - batching yet. +- **One scalar observable is evaluated at a time, for one sample.** `run`, + `expectation` and `PhotonicCircuit` take one sample for each call. Only + `run_photonic_reservoir` sends a batch, to an executor that offers `run_batch`. - **Only observables that are diagonal in the Fock basis are supported.** ## Roadmap From 2ad0df00262b76dbecd082eeb4718f7e94d2e040 Mon Sep 17 00:00:00 2001 From: Arseniy Senokosov <70952998+sarseniy@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:35:08 +0200 Subject: [PATCH 5/5] fix(photonics): guard concurrent job builds and plain-number angles Building a Quandela Cloud job goes through Perceval methods that share state between instances, so concurrent builds could swap input states or corrupt an experiment. The Perceval section now runs under a lock. A platform without the sample_count command is refused, because its results would need a conversion cloud_job_counts does not make. The codec writes NumPy scalars inside angle expressions as Python numbers. --- docs/user-guide/photonics.md | 9 ++- .../photonics/backends/perceval_remote.py | 73 ++++++++++++------- src/eigenkit/photonics/wire.py | 33 ++++++++- tests/photonics/test_cloud_job.py | 64 ++++++++++++++++ tests/photonics/test_wire.py | 23 +++++- 5 files changed, 166 insertions(+), 36 deletions(-) diff --git a/docs/user-guide/photonics.md b/docs/user-guide/photonics.md index d50398c..a425182 100644 --- a/docs/user-guide/photonics.md +++ b/docs/user-guide/photonics.md @@ -261,10 +261,11 @@ router = RouterPhotonicBackend(RouterConfig(device="quandela/sim_slos", shots=20 states = run_photonic_reservoir(spec, weights, sequences, executor=router) ``` -The reservoir sends all its time steps as **one** job, because the compiled circuit of -this executor has a method `run_batch(weights, rows)`. `run_photonic_reservoir` calls -it once when an executor offers it, and calls `run` for each step when it does not, as -with the local `PercevalBackend`. The results are sampled, so gradients are not +The reservoir sends all its time steps in **one** call, because the compiled circuit of +this executor has a method `run_batch(weights, rows)`. The executor sends them as one +job, or as a few jobs when the device limits the rows of a job. +`run_photonic_reservoir` calls `run_batch` once when an executor offers it, and calls +`run` for each step when it does not, as with the local `PercevalBackend`. The results are sampled, so gradients are not available, as on Quandela Cloud. Two functions support services that submit jobs for their users, as the Router does. diff --git a/src/eigenkit/photonics/backends/perceval_remote.py b/src/eigenkit/photonics/backends/perceval_remote.py index 2d23bb1..24cf4f7 100644 --- a/src/eigenkit/photonics/backends/perceval_remote.py +++ b/src/eigenkit/photonics/backends/perceval_remote.py @@ -31,6 +31,7 @@ import contextlib import json import os +import threading import time import warnings @@ -84,6 +85,12 @@ def _counts_to_distribution(counts, n_modes): return {fock_tuple(state, n_modes): count / total for state, count in counts.items()} +# Perceval dispatches some methods (for example `with_input`, and the serializer) +# through state that all instances share, so two threads that build a job at the same +# time can swap input states or corrupt an experiment. One build takes milliseconds. +_BUILD_LOCK = threading.Lock() + + class _CaptureHandler: """A stand-in for Perceval's cloud handler that opens no connection. @@ -153,6 +160,9 @@ def cloud_job_body( /api/jobs`). A service that holds the token can send it later. The job samples the circuit once for each row of `inputs`, so a batch is one job. + Several threads can call this function at the same time: the calls into Perceval + run one after another. + Args: spec (PhotonicCircuitSpec): The circuit to run. weights (np.ndarray): The 1-D weight vector, used for every row. @@ -175,7 +185,8 @@ def cloud_job_body( Raises: ValueError: If `weights` is not 1-D with the length that the spec declares, - or if `inputs` is not one or more rows of that length. + if `inputs` is not one or more rows of that length, or if the platform + does not offer the `sample_count` command. """ import perceval as pcvl from perceval.algorithm import Sampler @@ -194,33 +205,41 @@ def cloud_job_body( f"or (rows, {spec.n_inputs}) with at least one row" ) - handler = _CaptureHandler(platform, platform_details) - processor = pcvl.RemoteProcessor(rpc_handler=handler) - circuit, angles = _parametric_circuit(spec) - processor.set_circuit(circuit) - processor.min_detected_photons_filter( - spec.n_photons if min_detected_photons is None else min_detected_photons - ) - processor.with_input(pcvl.BasicState(list(spec.input_state))) shots = int(shots) - sampler = Sampler(processor, max_shots_per_call=shots) - sampler.add_iteration_list( - [ - { - "circuit_params": { - f"a{index}": float(resolve(angle, weights, row)) - for index, angle in enumerate(angles) - }, - "max_samples": shots, - "max_shots": shots, - } - for row in rows - ] - ) - job = sampler.sample_count - job.name = job_name - job.execute_async(shots) - return handler.body + handler = _CaptureHandler(platform, platform_details) + with _BUILD_LOCK: + processor = pcvl.RemoteProcessor(rpc_handler=handler) + circuit, angles = _parametric_circuit(spec) + processor.set_circuit(circuit) + processor.min_detected_photons_filter( + spec.n_photons if min_detected_photons is None else min_detected_photons + ) + processor.with_input(pcvl.BasicState(list(spec.input_state))) + sampler = Sampler(processor, max_shots_per_call=shots) + sampler.add_iteration_list( + [ + { + "circuit_params": { + f"a{index}": float(resolve(angle, weights, row)) + for index, angle in enumerate(angles) + }, + "max_samples": shots, + "max_shots": shots, + } + for row in rows + ] + ) + job = sampler.sample_count + job.name = job_name + job.execute_async(shots) + body = handler.body + # Without a native `sample_count`, Perceval asks for another command and converts + # the result itself; `cloud_job_counts` reads the service's own counts only. + if body["payload"]["command"] != "sample_count": + raise ValueError( + f"the platform {platform!r} does not offer the sample_count command" + ) + return body def cloud_job_counts(result: dict, n_modes: int) -> list[dict]: diff --git a/src/eigenkit/photonics/wire.py b/src/eigenkit/photonics/wire.py index 1b75fcb..8d93b70 100644 --- a/src/eigenkit/photonics/wire.py +++ b/src/eigenkit/photonics/wire.py @@ -2,7 +2,7 @@ This module is the photonic counterpart of `core.wire`. It turns a `PhotonicCircuitSpec` into plain JSON data and back, so that a circuit can be sent -to a service or stored. It holds only data, and uses neither Perceval nor NumPy. +to a service or stored. It holds only data, and does not use Perceval. The angles of the components use the same encoding as the parameters of the qubit circuits, so a `WeightRef` or an `InputRef` means the same thing in both. @@ -10,19 +10,44 @@ from __future__ import annotations +import numbers + from ..core.blocks import _param_from_json, _param_to_json from .ir import BeamSplitter, Permutation, PhaseShifter, PhotonicCircuitSpec +def _plain(value): + """Replace the NumPy scalars of an encoded angle with Python numbers. + + The parameter encoding of the qubit circuits writes numbers as it finds them, + and `json.dumps` refuses a NumPy integer or a 32-bit float. + """ + if isinstance(value, dict): + return {key: _plain(item) for key, item in value.items()} + if isinstance(value, list): + return [_plain(item) for item in value] + if isinstance(value, bool | str) or type(value) in (int, float): + return value + if isinstance(value, numbers.Integral): + return int(value) + if isinstance(value, numbers.Real): + return float(value) + return value + + +def _angle_to_json(angle) -> dict: + return _plain(_param_to_json(angle)) + + def _component_to_json(comp) -> dict: if isinstance(comp, PhaseShifter): - return {"c": "PS", "mode": int(comp.mode), "phi": _param_to_json(comp.phi)} + return {"c": "PS", "mode": int(comp.mode), "phi": _angle_to_json(comp.phi)} if isinstance(comp, BeamSplitter): return { "c": "BS", "modes": [int(m) for m in comp.modes], - "theta": _param_to_json(comp.theta), - "phi": _param_to_json(comp.phi), + "theta": _angle_to_json(comp.theta), + "phi": _angle_to_json(comp.phi), } if isinstance(comp, Permutation): return {"c": "PERM", "perm": [int(m) for m in comp.perm]} diff --git a/tests/photonics/test_cloud_job.py b/tests/photonics/test_cloud_job.py index 70e9c0d..1fdba95 100644 --- a/tests/photonics/test_cloud_job.py +++ b/tests/photonics/test_cloud_job.py @@ -1,6 +1,8 @@ """Building and reading a Quandela Cloud job without a connection.""" import json +import sys +from concurrent.futures import ThreadPoolExecutor from pathlib import Path import numpy as np @@ -10,6 +12,9 @@ pcvl = pytest.importorskip("perceval") from eigenkit.core.ir import Constant, resolve # noqa: E402 +from eigenkit.photonics.backends.perceval_backend import ( # noqa: E402 + build_perceval_circuit, +) from eigenkit.photonics.backends.perceval_remote import ( # noqa: E402 cloud_job_body, cloud_job_counts, @@ -193,3 +198,62 @@ def test_a_job_without_counts_is_refused(results): def test_a_result_without_the_results_key_is_refused(): with pytest.raises(ValueError, match="no counts"): cloud_job_counts({"job_id": "x"}, 4) + + +def test_each_row_builds_the_circuit_the_single_run_path_builds(): + rows = np.random.default_rng(3).uniform(-50, 50, (4, 2)) + body = _body(rows) + experiment = pcvl.serialization.deserialize(body["payload"]["experiment"]) + for row, iteration in zip(rows, body["payload"]["iterator"], strict=True): + bound = experiment.copy() + parameters = bound.get_circuit_parameters() + for name, value in iteration["circuit_params"].items(): + parameters[name].set_value(value) + built = np.array(bound.unitary_circuit().compute_unitary()) + expected = np.array(build_perceval_circuit(SPEC, WEIGHTS, row).compute_unitary()) + np.testing.assert_allclose(built, expected, atol=1e-12) + + +def test_concurrent_builds_do_not_mix(): + # Perceval dispatches some methods through state shared by all instances, so + # unguarded concurrent builds can swap input states or corrupt the experiment. + jobs = [] + for index in range(16): + spec, weights = random_reservoir_spec( + 4, + 2, + depth=2, + input_state=(1, 1, 0, 0) if index % 2 else (1, 0, 1, 0), + rng=np.random.default_rng(index), + ) + jobs.append((spec, weights, np.full((2, 2), 0.1 * index), f"eo-{index}")) + + def build(job): + spec, weights, rows, name = job + body = cloud_job_body( + spec, + weights, + rows, + platform="sim:slos", + platform_details=DETAILS, + shots=10, + job_name=name, + ) + return json.dumps(body, sort_keys=True) + + expected = [build(job) for job in jobs] + interval = sys.getswitchinterval() + sys.setswitchinterval(1e-5) + try: + with ThreadPoolExecutor(max_workers=8) as pool: + for _ in range(15): + assert list(pool.map(build, jobs)) == expected + finally: + sys.setswitchinterval(interval) + + +def test_a_platform_without_sample_count_is_refused(): + details = json.loads(json.dumps(DETAILS)) + details["specs"]["available_commands"] = ["samples"] + with pytest.raises(ValueError, match="sample_count"): + _body(np.zeros(2), platform_details=details) diff --git a/tests/photonics/test_wire.py b/tests/photonics/test_wire.py index 29e6714..fd0a7c4 100644 --- a/tests/photonics/test_wire.py +++ b/tests/photonics/test_wire.py @@ -7,7 +7,7 @@ import numpy as np import pytest -from eigenkit.core.ir import Constant, InputRef, WeightRef +from eigenkit.core.ir import Constant, InputRef, Scale, Sum, WeightRef from eigenkit.photonics.ir import ( BeamSplitter, Permutation, @@ -78,6 +78,27 @@ def test_numpy_scalars_encode_as_plain_json(): assert type(data["input_state"][0]) is int +def test_numpy_scalars_inside_angles_encode_as_plain_json(): + angle = Sum((Scale(InputRef(np.int64(0)), np.float32(0.5)), WeightRef(np.int64(1)))) + spec = PhotonicCircuitSpec( + n_modes=2, + n_weights=2, + n_inputs=1, + components=( + PhaseShifter(0, angle), + PhaseShifter(1, Constant(np.float32(0.25))), + ), + input_state=(1, 0), + ) + data = photonic_spec_to_json(spec) + assert json.loads(json.dumps(data)) == data + phi = data["components"][0]["phi"] + assert type(phi["es"][0]["e"]["i"]) is int + assert type(phi["es"][0]["f"]) is float + assert type(phi["es"][1]["i"]) is int + assert type(data["components"][1]["phi"]["v"]) is float + + @pytest.mark.parametrize( "bad, error", [