merlin.algorithms.layer_utils module
Utilities and helpers for QuantumLayer initialization and configuration.
Note
This module contains internal-but-documented helpers used during
QuantumLayer initialization and input
preparation.
- class merlin.algorithms.layer_utils.EncodingModeConfig(amplitude_encoding, input_size, n_photons, input_parameters)
Bases:
objectStore the validated encoding configuration.
- Parameters:
- class merlin.algorithms.layer_utils.CircuitSource(source_type, builder, circuit, experiment, trainable_parameters, input_parameters, angle_encoding_specs)
Bases:
objectStore the resolved circuit source configuration.
- Parameters:
source_type (Literal["builder", "circuit", "experiment"]) – Kind of source provided by the caller.
builder (CircuitBuilder | None) – Builder instance when
source_type == "builder".circuit (pcvl.Circuit | None) – Perceval circuit when
source_type == "circuit".experiment (pcvl.Experiment | None) – Perceval experiment when
source_type == "experiment".trainable_parameters (list[str]) – Resolved trainable parameter prefixes.
input_parameters (list[str]) – Resolved input parameter prefixes.
angle_encoding_specs (dict[str, dict[str, Any]]) – Stored angle encoding metadata extracted from the builder, if any.
-
builder:
Optional[CircuitBuilder]
-
experiment:
Optional[Experiment]
- class merlin.algorithms.layer_utils.ResolvedCircuit(circuit, experiment, noise_model, has_custom_noise)
Bases:
objectStore the resolved circuit and experiment pair.
- Parameters:
circuit (pcvl.Circuit) – Resolved circuit instance.
experiment (pcvl.Experiment) – Experiment wrapping the resolved circuit.
noise_model (Any | None) – Attached experiment noise model, if present.
has_custom_noise (bool) – Whether the experiment exposes a non-empty custom noise model.
-
experiment:
Experiment
- class merlin.algorithms.layer_utils.NoiseAndDetectorConfig(photon_survival_probs, has_custom_noise, detectors, has_custom_detectors, detector_warnings)
Bases:
objectStore extracted noise and detector configuration.
- Parameters:
photon_survival_probs (list[float]) – Photon survival probabilities derived from the experiment noise model.
has_custom_noise (bool) – Whether a custom noise model is present.
detectors (list[pcvl.Detector]) – Resolved detector list for every mode.
has_custom_detectors (bool) – Whether the experiment defines non-default detectors.
detector_warnings (list[str]) – Compatibility warnings emitted while resolving detector behavior.
- class merlin.algorithms.layer_utils.InitializationContext(device, dtype, complex_dtype, amplitude_encoding, input_size, circuit, experiment, noise_model, has_custom_noise, input_state, n_photons, trainable_parameters, input_parameters, angle_encoding_specs, photon_survival_probs, detectors, has_custom_detectors, computation_space, measurement_strategy, warnings, return_object)
Bases:
objectStore immutable QuantumLayer initialization state.
- Parameters:
device (torch.device | None) – Target device for the layer.
dtype (torch.dtype) – Real dtype used by the layer.
complex_dtype (torch.dtype) – Complex dtype paired with
dtype.amplitude_encoding (bool) – Whether amplitude encoding is enabled.
input_size (int | None) – Resolved classical input size.
circuit (pcvl.Circuit) – Resolved circuit.
experiment (pcvl.Experiment) – Resolved experiment.
noise_model (Any | None) – Attached noise model, if any.
has_custom_noise (bool) – Whether the experiment defines custom noise.
input_state (merlin.core.state_vector.StateVector | pcvl.BasicState | torch.Tensor | None) – Normalized input state.
n_photons (int | None) – Resolved photon count.
trainable_parameters (list[str]) – Trainable parameter prefixes.
input_parameters (list[str]) – Classical input parameter prefixes.
angle_encoding_specs (dict[str, dict[str, Any]]) – Angle encoding metadata extracted from the builder.
photon_survival_probs (list[float]) – Photon survival probabilities derived from the experiment.
detectors (list[pcvl.Detector]) – Resolved detector list.
has_custom_detectors (bool) – Whether custom detectors are configured.
computation_space (ComputationSpace) – Resolved computation space.
measurement_strategy (
MeasurementStrategyLike) – Measurement strategy used by the layer.warnings (list[str]) – Initialization warnings to surface to the caller.
return_object (bool) – Whether the layer returns structured objects instead of tensors.
-
computation_space:
ComputationSpace
-
experiment:
Experiment
-
input_state:
Union[StateVector,BasicState,Tensor,None]
-
measurement_strategy:
Union[MeasurementStrategy,_LegacyMeasurementStrategy]
- merlin.algorithms.layer_utils.validate_encoding_mode(amplitude_encoding, input_size, n_photons, input_parameters)
Validate amplitude-encoding constraints.
- Parameters:
- Returns:
Validated and normalized encoding configuration.
- Return type:
- Raises:
ValueError – If amplitude encoding is requested with incompatible classical-input settings.
- merlin.algorithms.layer_utils.prepare_input_state(input_state, n_photons, computation_space, device, complex_dtype, experiment=None, circuit_m=None, amplitude_encoding=False)
Normalize input_state to canonical form.
- Parameters:
input_state (
StateVector| pcvl.StateVector | pcvl.BasicState | list | tuple | torch.Tensor | None) – The input state in various formats.StateVectoris the canonical type. Legacy formats are auto-converted with deprecation warnings where appropriate.n_photons (int | None) – Number of photons (used for default state generation).
computation_space (ComputationSpace) – The computation space configuration.
device (torch.device | None) – Target device for tensors.
complex_dtype (torch.dtype) – Complex dtype for tensor conversion.
experiment (pcvl.Experiment | None) – Optional experiment whose input_state takes precedence.
circuit_m (int | None) – Number of modes in the circuit (for default state generation).
amplitude_encoding (bool) – Whether amplitude encoding is enabled.
- Returns:
The normalized input state and resolved photon count.
- Return type:
tuple[merlin.core.state_vector.StateVector | pcvl.BasicState | torch.Tensor | None, int | None]
- Raises:
ValueError – If neither input_state nor n_photons is provided, or if StateVector is empty.
- Warns:
DeprecationWarning – When
torch.Tensoris passed as input_state (deprecated in favor of StateVector).UserWarning – When both experiment.input_state and input_state are provided.
- merlin.algorithms.layer_utils.validate_and_resolve_circuit_source(builder, circuit, experiment, trainable_parameters, input_parameters)
Validate and normalize the circuit source selection.
- Parameters:
builder (CircuitBuilder | None) – Builder source, if provided.
circuit (pcvl.Circuit | None) – Circuit source, if provided.
experiment (pcvl.Experiment | None) – Experiment source, if provided.
trainable_parameters (list[str] | None) – User-provided trainable parameter prefixes.
input_parameters (list[str] | None) – User-provided input parameter prefixes.
- Returns:
Resolved circuit-source configuration.
- Return type:
- Raises:
ValueError – If zero or multiple circuit sources are provided, or if builder-derived prefixes are mixed with explicit parameter prefixes.
- merlin.algorithms.layer_utils.vet_experiment(experiment)
Check experiment constraints.
- Parameters:
experiment (pcvl.Experiment) – Experiment to validate.
- Returns:
Summary of experiment properties relevant to QuantumLayer support.
- Return type:
- Raises:
ValueError – If the experiment uses unsupported features such as post-selection, heralding, feed-forward, time dependence, or minimum-photon filters.
- merlin.algorithms.layer_utils.resolve_circuit(circuit_source, pcvl_module)
Resolve a builder, circuit, or experiment into a unified circuit form.
- Parameters:
circuit_source (CircuitSource) – Resolved circuit source configuration.
pcvl_module (Any) – Perceval module used to instantiate experiments when needed.
- Returns:
Unified circuit and experiment wrapper.
- Return type:
- Raises:
RuntimeError – If the provided
circuit_sourceis internally inconsistent.
- merlin.algorithms.layer_utils.setup_noise_and_detectors(experiment, circuit, computation_space, measurement_strategy)
Extract and validate photon-loss and detector configuration.
- Parameters:
experiment (pcvl.Experiment) – Experiment from which noise and detectors are extracted.
circuit (pcvl.Circuit) – Resolved circuit used to determine the number of modes.
computation_space (ComputationSpace) – Logical computation space requested by the layer.
measurement_strategy (
MeasurementStrategyLike) – Measurement strategy used to validate detector and noise compatibility.
- Returns:
Extracted and validated noise/detector configuration.
- Return type:
- Raises:
RuntimeError – If amplitude readout is requested together with incompatible noise or detector settings.
- merlin.algorithms.layer_utils.apply_angle_encoding(x, spec)
Apply custom angle encoding using stored metadata.
- Parameters:
x (torch.Tensor) – Input tensor to encode. May be one- or two-dimensional.
spec (dict[str, Any]) – Angle encoding metadata containing feature combinations and scales.
- Returns:
Encoded tensor matching the requested combinations.
- Return type:
- Raises:
ValueError – If
xhas unsupported rank or does not provide enough features for a requested combination.
- merlin.algorithms.layer_utils.prepare_input_encoding(x, prefix=None, angle_encoding_specs=None)
Prepare input encoding for a given parameter prefix.
- Parameters:
- Returns:
Encoded tensor if a matching specification is found, otherwise the input tensor unchanged.
- Return type:
- merlin.algorithms.layer_utils.split_inputs_by_prefix(prefixes, tensor, angle_encoding_specs, spec_mappings=None)
Split a logical input tensor into per-prefix chunks when possible.
- Parameters:
prefixes (list[str]) – Ordered parameter prefixes to split against.
tensor (torch.Tensor) – Input tensor containing all logical features.
angle_encoding_specs (dict[str, dict[str, Any]]) – Angle encoding specifications keyed by prefix.
spec_mappings (dict[str, list[str]] | None) – Optional spec mappings used as a fallback for feature counting.
- Returns:
Per-prefix tensor slices when the split is possible, otherwise
None.- Return type:
list[torch.Tensor] | None
- merlin.algorithms.layer_utils.feature_count_for_prefix(prefix, angle_encoding_specs, spec_mappings=None)
Infer the number of raw features associated with an encoding prefix.
- Parameters:
- Returns:
Number of raw features associated with
prefix, orNoneif it cannot be inferred.- Return type:
int | None