merlin.algorithms.feed_forward module
- class merlin.algorithms.feed_forward.FFStage(unitary, active_modes, measured_modes, detectors, provider)
Bases:
objectStatic description of one feed-forward stage extracted from an experiment.
- Parameters:
unitary (pcvl.Circuit) – Circuit executed for the stage.
active_modes (tuple[int, ...]) – Modes actively transformed by the stage circuit.
measured_modes (tuple[int, ...]) – Modes measured immediately after the stage.
detectors (dict[int, pcvl.Detector | None]) – Detector configuration indexed by measured mode.
provider (FFCircuitProvider | None) – Optional conditional-circuit provider associated with the stage.
-
provider:
Optional[FFCircuitProvider]
- class merlin.algorithms.feed_forward.StageRuntime(circuit, pre_layer, detector_transform, conditional_circuits, conditional_default_key, measured_modes, global_measured_modes, active_modes, detectors, provider, pre_layers=<factory>, detector_cache=<factory>, conditional_layer_cache=<factory>, trainable_parameters=None, initial_amplitudes=None, classical_input_size=0)
Bases:
objectRuntime objects needed to execute one feed-forward stage.
- Parameters:
circuit (pcvl.Circuit) – Full circuit executed for the stage.
pre_layer (QuantumLayer | None) – Layer applied before any conditional branching.
detector_transform (DetectorTransform | None) – Detector transform used to process measured outputs.
conditional_circuits (dict[tuple[int, ...], pcvl.Circuit]) – Conditional circuits indexed by measurement outcomes.
conditional_default_key (tuple[int, ...] | None) – Default conditional-circuit key when no exact outcome match exists.
measured_modes (tuple[int, ...]) – Stage-local measured modes.
global_measured_modes (tuple[int, ...]) – Measured modes expressed in the global circuit indexing.
active_modes (tuple[int, ...]) – Modes actively transformed by this stage.
detectors (dict[int, pcvl.Detector | None]) – Detector configuration indexed by measured mode.
provider (FFCircuitProvider | None) – Optional provider used to build conditional circuits.
pre_layers (dict[int, QuantumLayer]) – Cache of pre-layers indexed by branch state size.
detector_cache (dict[int, DetectorTransform]) – Cache of detector transforms indexed by branch state size.
conditional_layer_cache (dict[tuple[tuple[int, ...], int], QuantumLayer]) – Cache of conditional layers indexed by measurement key and state size.
trainable_parameters (list[str] | None) – Trainable parameter prefixes kept for the stage.
initial_amplitudes (torch.Tensor | None) – Initial amplitudes for amplitude-encoding execution.
classical_input_size (int) – Number of classical inputs consumed by the stage. Default is
0.
-
detector_cache:
dict[int,DetectorTransform]
-
detector_transform:
Optional[DetectorTransform]
-
pre_layer:
Optional[QuantumLayer]
-
pre_layers:
dict[int,QuantumLayer]
-
provider:
Optional[FFCircuitProvider]
- class merlin.algorithms.feed_forward.BranchState(amplitudes, weight, remaining_n, measurement_key, basis_keys)
Bases:
objectState carried by one feed-forward branch during execution.
- Parameters:
amplitudes (torch.Tensor) – Branch amplitudes in the current basis.
weight (torch.Tensor) – Classical probability weight accumulated for the branch.
remaining_n (int) – Number of photons remaining after the branch measurements.
measurement_key (tuple[int | None, ...]) – Measurement outcomes accumulated so far.
basis_keys (tuple[tuple[int, ...], ...]) – Basis states associated with
amplitudes.
- class merlin.algorithms.feed_forward.FeedForwardBlock(experiment, *, input_state=None, trainable_parameters=None, input_parameters=None, computation_space=ComputationSpace.FOCK, measurement_strategy=MeasurementStrategy(type=<MeasurementKind.PROBABILITIES: 'PROBABILITIES'>, measured_modes=(), computation_space=<ComputationSpace.FOCK: 'fock'>, grouping=None), device=None, dtype=None)
Bases:
MerlinModuleFeed-forward photonic block constructed directly from a Perceval experiment.
The block introspects the provided
pcvl.Experiment, splits it into unitary / detector /FFCircuitProviderstages and turns each segment into one or moreQuantumLayerinstances. At run time the block executes every stage, branching on every partial measurement outcome and accumulating the classical probability for each branch.- Parameters:
experiment (pcvl.Experiment) – Perceval experiment containing the full feed-forward definition. The current implementation requires noise-free experiments (
NoiseModel()orNone).input_state (list[int] | pcvl.BasicState | pcvl.StateVector | torch.Tensor | None) – Initial quantum state. May be provided as a Fock occupation list, pcvl.BasicState,
StateVector, or a tensor whose components represent amplitudes in the experiment Fock basis. The tensor form is only required for amplitude-encoding inputs.trainable_parameters (list[str] | None) – Optional list of Perceval parameter prefixes that should remain learnable across all stages.
input_parameters (list[str] | None) – Perceval parameter prefixes that receive classical inputs. They are consumed by the first stage only; once the first detection happens all branches switch to amplitude encoding and the classical tensor is ignored.
computation_space (ComputationSpace) – Currently restricted to
ComputationSpace.FOCK.measurement_strategy (
MeasurementStrategyLike) –Controls how classical outputs are produced.
MeasurementStrategy.probs(computation_space)(default) returns a tensor of shape(batch_size, num_output_keys)whose columns match the fully specified Fock states stored inoutput_keys.MeasurementStrategy.mode_expectations(computation_space)collapses every branch into a single tensor of shape(batch_size, num_modes)that contains the per-mode photon expectations aggregated across all measurement keys. Theoutput_keysattribute is retained for metadata whileoutput_state_sizesreportsnum_modesfor every key.MeasurementStrategy.AMPLITUDESyields a list of tuples(measurement_key, branch_probability, remaining_photons, amplitudes)so callers can reason about the mixed state left by each branch.
device (torch.device | None) – Target device used for internal tensors and generated layers.
dtype (torch.dtype | None) – Real dtype used for classical outputs and derived complex amplitudes.
- describe()
Return a multi-line description of the feed-forward stages.
The summary lists, in order, the global modes that remain active at each step, the subset of measured modes, and the type of feed-forward configurator attached to the stage. It is primarily intended for debugging or for logging experiment structure.
- Returns:
Human-readable stage summary.
- Return type:
- forward(x=None)
Execute the feed-forward experiment.
- Parameters:
x (torch.Tensor | None) – Classical feature tensor. Only the first stage consumes classical inputs; subsequent stages operate purely in amplitude-encoding mode. When the experiment does not expose classical inputs this argument may be omitted (or
None), in which case an empty tensor is automatically supplied.- Returns:
PROBABILITIESreturns a tensor of shape(batch_size, len(output_keys))aligned with the fully specified Fock states inoutput_keys.MODE_EXPECTATIONSproduces a tensor of shape(batch_size, total_modes)where the columns already encode the per-mode expectations aggregated across all measurement keys (output_state_sizesstorestotal_modesfor every key).AMPLITUDESyields a list of tuples(measurement_key, branch_probability, remaining_photons, amplitudes)describing every branch of the resulting mixed state.- Return type:
torch.Tensor | list[tuple[tuple[int, …], torch.Tensor, int, torch.Tensor]]
- property output_keys: list[tuple[int, ...]]
Return the measurement keys associated with the most recent classical forward pass.
The list is populated after
forward()completes. For thePROBABILITIESstrategy the list lines up with the tensor columns. ForMODE_EXPECTATIONSit is retained for reference even though the returned tensor already aggregates all measurement outcomes. Calling the property before running the block raisesRuntimeError.- Returns:
Measurement keys describing the classical outputs.
- Return type:
- Raises:
RuntimeError – If the block has not been executed yet.
- property output_state_sizes: dict[tuple[int, ...], int]
Return the number of remaining Fock states represented by each entry in
output_keys.Only available when
measurement_strategyisPROBABILITIESorMODE_EXPECTATIONS. ForPROBABILITIESthe value is always1because each key now denotes a fully specified Fock state, while forMODE_EXPECTATIONSit equals the total number of modes contributing to the expectation vector.- Returns:
Mapping from measurement key to the size of the represented output state space.
- Return type:
- Raises:
RuntimeError – If the block has not produced classical outputs yet.