merlin.core package

Core quantum layer components.

class merlin.core.AbstractComputationProcess

Bases: ABC

Abstract base class for quantum computation processes.

abstract compute(*args, **kwargs)

Perform the computation.

Args:

*args: Positional arguments for the computation. **kwargs: Keyword arguments for the computation.`

class merlin.core.BeamSplitter(targets, theta_role=ParameterRole.FIXED, theta_value=0.7854, phi_role=ParameterRole.FIXED, phi_value=0.0, theta_name=None, phi_name=None)

Bases: object

Beam splitter description.

get_params()

Describe which phase shifter angles should be exposed as parameters.

Return type:

dict[str, Any]

Returns:

Dict[str, Any]: Parameter placeholders keyed by their symbolic names.

phi_name: Optional[str] = None
phi_role: ParameterRole = 'fixed'
phi_value: float = 0.0
targets: tuple
theta_name: Optional[str] = None
theta_role: ParameterRole = 'fixed'
theta_value: float = 0.7854
class merlin.core.Circuit(n_modes, components=<factory>, metadata=<factory>)

Bases: object

Simple circuit container.

add(component)

Append a component and return the circuit for chained calls.

Return type:

Circuit

Args:

component: Circuit element (rotation, beam splitter, measurement, etc.).

Returns:

Circuit: self to support fluent-style chaining.

clear()

Remove every component and metadata entry from the circuit.

components: list[Any]
property depth: int

Estimate logical depth by summing component depths when available.

get_parameters()

Collect parameter placeholders exposed by each component.

Return type:

dict[str, Any]

Returns:

Dict[str, Any]: Mapping from parameter name to default value (or None).

metadata: dict[str, Any]
n_modes: int
property num_components: int

Return the count of registered components.

class merlin.core.Component

Bases: object

Base class for backward compatibility.

class merlin.core.ComputationProcess(circuit, input_state, trainable_parameters, input_parameters, n_photons=None, dtype=torch.float32, device=None, computation_space=None, no_bunching=None, output_map_func=None)

Bases: AbstractComputationProcess

Handles quantum circuit computation and state evolution.

compute(parameters)

Compute quantum output distribution.

Return type:

Tensor

compute_ebs_simultaneously(parameters, simultaneous_processes=1)

Evaluate a single circuit parametrisation against all superposed input states by chunking them in groups and delegating the heavy work to the TorchScript-enabled batch kernel.

The method converts the trainable parameters into a unitary matrix, normalises the input state (if it is not already normalised), filters out components with zero amplitude, and then queries the simulation graph for batches of Fock states. Each batch feeds SLOSComputeGraph.compute_batch(), producing a tensor that contains the amplitudes of all reachable output states for the selected input components. The partial results are accumulated into a preallocated tensor and finally weighted by the complex coefficients of self.input_state to produce the global output amplitudes.

Return type:

Tensor

Args:
parameters (list[torch.Tensor]): Differentiable parameters that

encode the photonic circuit. They are forwarded to self.converter to build the unitary matrix used during the simulation.

simultaneous_processes (int): Maximum number of non-zero input

components that are propagated in a single call to compute_batch. Tuning this value allows trading memory consumption for wall-clock time on GPU.

Returns:

torch.Tensor: The superposed output amplitudes with shape [batch_size, num_output_states] where batch_size corresponds to the number of independent input batches and num_output_states is the size of self.simulation_graph.mapped_keys.

Raises:

TypeError: If self.input_state is not a torch.Tensor. The simulation graph expects tensor inputs, therefore other sequence types (NumPy arrays, lists, etc.) cannot be used here.

Notes:
  • self.input_state is normalised in place to avoid an extra allocation.

  • Zero-amplitude components are skipped to minimise the number of calls to compute_batch.

  • The method is agnostic to the device: tensors remain on the device they already occupy, so callers should ensure parameters and self.input_state live on the same device.

compute_superposition_state(parameters, *, return_keys=False)
Return type:

Tensor | tuple[list[tuple[int, ...]], Tensor]

compute_with_keys(parameters)

Compute quantum output distribution and return both keys and probabilities.

class merlin.core.ComputationProcessFactory

Bases: object

Factory for creating computation processes.

static create(circuit, input_state, trainable_parameters, input_parameters, computation_space=None, **kwargs)

Create a computation process.

Return type:

ComputationProcess

enum merlin.core.ComputationSpace(value)

Bases: str, Enum

Enumeration of supported computational subspaces.

Member Type:

str

Valid values are as follows:

FOCK = <ComputationSpace.FOCK: 'fock'>
UNBUNCHED = <ComputationSpace.UNBUNCHED: 'unbunched'>
DUAL_RAIL = <ComputationSpace.DUAL_RAIL: 'dual_rail'>

The Enum and its members also have the following methods:

classmethod default(*, no_bunching)

Derive the default computation space from the legacy no_bunching flag.

Return type:

ComputationSpace

classmethod coerce(value)

Normalize user-provided values (enum instances or case-insensitive strings).

Return type:

ComputationSpace

class merlin.core.EntanglingBlock(targets='all', pattern='nearest_neighbor', depth=1, trainable=True, name_prefix=None)

Bases: object

Entangling block description.

depth: int = 1
get_params()

Entangling blocks themselves carry no direct parameters.

Return type:

dict[str, Any]

Returns:

Dict[str, Any]: Always empty because entangling blocks are metadata-only.

name_prefix: Optional[str] = None
pattern: str = 'nearest_neighbor'
targets: str | list[int] = 'all'
trainable: bool = True
class merlin.core.ProbabilityDistribution(tensor, n_modes, n_photons, computation_space=ComputationSpace.FOCK, logical_performance=None, _custom_basis=None)

Bases: object

Probability tensor bundled with Fock metadata and post-filter tracking.

Parameters

tensor:

Dense or sparse probabilities; leading dimensions are treated as batch axes.

n_modes:

Number of modes in the Fock space.

n_photons:

Total photon number represented by the distribution.

computation_space:

Basis enumeration used to order amplitudes (fock, unbunched, dual_rail).

logical_performance:

Optional per-batch scalar tracking kept/total probability after filtering.

Notes

Instances are normalized on construction; arithmetic-style temporary unnormalized states are not supported (unlike StateVector). Only shape, device, dtype, and requires_grad are delegated to the underlying torch.Tensor; tensor-like helpers to, clone, detach, and requires_grad_ mirror tensor semantics while keeping metadata and logical performance aligned. Layout-changing tensor operations should be done on tensor directly, then wrapped again via from_tensor to maintain a consistent basis.

property basis: Combinadics | FilteredBasis | tuple[tuple[int, ...], ...]
property basis_size: int
clone()

Return a cloned ProbabilityDistribution with metadata and logical performance copied.

Return type:

ProbabilityDistribution

computation_space: ComputationSpace = 'fock'
detach()

Return a detached ProbabilityDistribution sharing data without gradients.

Return type:

ProbabilityDistribution

filter(rule)

Apply post-selection filter and renormalize probabilities.

logical_performance records kept_mass / original_mass per batch.

Return type:

ProbabilityDistribution

Parameters

rule:

Computation space alias (fock, unbunched, dual_rail), a predicate, an explicit iterable of allowed states, or a tuple (space, predicate) to combine a computation-space constraint with an additional predicate.

Returns

ProbabilityDistribution

A new, normalized distribution; may shrink its basis when filtering to unbunched or dual_rail in the dense case.

Raises

ValueError

If dual_rail is selected with incompatible n_modes/n_photons or an unknown computation space is requested.

classmethod from_perceval(distribution, *, dtype=None, device=None, sparse=None)

Construct from a Perceval BSDistribution.

Validates that all entries share the same photon number and mode count.

Return type:

ProbabilityDistribution

Parameters

distribution:

Input Perceval distribution.

dtype / device:

Optional overrides for output tensor placement and precision.

sparse:

Force dense or sparse output; default auto-selects based on fill ratio.

Raises

ValueError

If the distribution is empty or inconsistent in shape/photon number.

classmethod from_state_vector(state_vector, *, dtype=None, device=None, computation_space=None)

Convert a StateVector to a probability distribution.

Return type:

ProbabilityDistribution

Parameters

state_vector:

Source amplitudes; must expose to_dense, n_modes, and n_photons.

dtype / device:

Optional overrides for output tensor placement and precision.

computation_space:

Optional basis scheme; defaults to fock.

classmethod from_tensor(tensor, *, n_modes, n_photons, computation_space=None, dtype=None, device=None)

Build a distribution from an explicit probability tensor.

Return type:

ProbabilityDistribution

Parameters

tensor:

Dense or sparse probability tensor; last dimension must match the basis size.

n_modes / n_photons:

Metadata for basis construction.

computation_space:

Optional basis scheme; defaults to fock.

dtype / device:

Optional overrides for output tensor placement and precision.

Raises

ValueError

If the last dimension does not match the expected basis size.

property is_normalized: bool
property is_sparse: bool
logical_performance: Optional[Tensor] = None
memory_bytes()

Return the tensor’s approximate memory footprint in bytes.

Return type:

int

n_modes: int
n_photons: int
normalize()

In-place normalization; safe for zero-mass batches.

Return type:

ProbabilityDistribution

Returns

ProbabilityDistribution

The same instance, normalized along the basis dimension.

probabilities()

Alias for to_dense() for readability.

Return type:

Tensor

requires_grad_(requires_grad=True)

Set requires_grad on underlying tensors and return self.

Return type:

ProbabilityDistribution

tensor: Tensor
to(*args, **kwargs)

Return a new ProbabilityDistribution with tensor (and logical_performance) moved/cast via torch.Tensor.to.

Return type:

ProbabilityDistribution

to_dense()

Return a dense, normalized tensor representation.

Return type:

Tensor

to_perceval()

Convert to Perceval BSDistribution (single) or list for batches.

class merlin.core.Rotation(target, role=ParameterRole.FIXED, value=0.0, axis='z', custom_name=None)

Bases: object

Rotation gate description.

The actual parameter name will be generated by the backend based on role.

axis: str = 'z'
custom_name: Optional[str] = None
get_params()

Return declared parameter placeholders for the rotation.

Non-fixed rotations expose either their custom name or the automatically generated identifier so that downstream tooling can bind data or trainable tensors to the gate.

Return type:

dict[str, Any]

Returns:

Dict[str, Any]: Mapping from parameter name to placeholder value.

role: ParameterRole = 'fixed'
target: int
value: float = 0.0
enum merlin.core.StatePattern(value)

Bases: str, Enum

Input photon state patterns.

Member Type:

str

Valid values are as follows:

DEFAULT = <StatePattern.DEFAULT: 'default'>
SPACED = <StatePattern.SPACED: 'spaced'>
SEQUENTIAL = <StatePattern.SEQUENTIAL: 'sequential'>
PERIODIC = <StatePattern.PERIODIC: 'periodic'>
class merlin.core.StateVector(tensor, n_modes, n_photons, _normalized=False)

Bases: object

Amplitude tensor bundled with its Fock metadata.

Keeps n_modes / n_photons and combinadics basis ordering alongside the underlying PyTorch tensor (dense or sparse).

Parameters

tensor:

Dense or sparse amplitude tensor; leading dimensions (if any) are treated as batch axes.

n_modes:

Number of modes in the Fock space.

n_photons:

Total photon number represented by the state.

_normalized:

Internal flag tracking whether the stored tensor is normalized.

Notes

This is a thin wrapper over a torch.Tensor: only shape, device, dtype, and requires_grad are delegated automatically, and tensor-like helpers to, clone, detach, and requires_grad_ are provided to mirror common tensor workflows while preserving metadata. Layout-changing operations (e.g., reshape/view) are intentionally not exposed; perform those on tensor explicitly if needed and rebuild via from_tensor.

property basis: Combinadics

Lazy combinadics basis for (n_modes, n_photons) in Fock ordering.

property basis_size: int

Return the number of basis states for (n_modes, n_photons).

clone()

Return a cloned StateVector with identical metadata and normalization flag.

Return type:

StateVector

detach()

Return a detached StateVector sharing data without gradients.

Return type:

StateVector

classmethod from_basic_state(state, *, dtype=None, device=None, sparse=True)

Create a one-hot state from a Fock occupation list/BasicState.

Return type:

StateVector

Args:

state: Occupation numbers per mode. dtype: Optional target dtype. device: Optional target device. sparse: Build sparse layout when True.

Returns:

StateVector: One-hot state.

classmethod from_perceval(state_vector, *, dtype=None, device=None, sparse=None)

Build from a pcvl.StateVector.

Return type:

StateVector

Args:

state_vector: Perceval state to wrap. dtype: Optional target dtype. device: Optional target device. sparse: Force sparse/dense; if None use density heuristic (<=30%).

Returns:

StateVector: Merlin wrapper with metadata and preserved amplitudes.

Raises:

ValueError: If the Perceval state is empty or has inconsistent photon/mode counts.

classmethod from_tensor(tensor, *, n_modes, n_photons, dtype=None, device=None)

Wrap an existing tensor with explicit metadata.

Return type:

StateVector

Args:

tensor: Dense or sparse amplitude tensor. n_modes: Number of modes. n_photons: Total photons. dtype: Optional target dtype. device: Optional target device.

Returns:

StateVector: Wrapped tensor.

Raises:

ValueError: If the last dimension does not match the basis size.

index(state)

Return basis index for the given Fock state.

Return type:

Optional[int]

Args:

state: Occupation list or BasicState.

Returns:

int | None: Basis index, or None if not present (or zero in sparse tensor).

property is_normalized: bool
property is_sparse: bool

Return True if the underlying tensor uses a sparse layout.

memory_bytes()

Approximate memory footprint (bytes) of the underlying tensor data.

Return type:

int

n_modes: int
n_photons: int
normalize()

Normalize this state in-place and return self.

Return type:

StateVector

normalized_str()

Human-friendly string of the normalized state (forces normalization for display).

Return type:

str

requires_grad_(requires_grad=True)

Set requires_grad on the underlying tensor and return self.

Return type:

StateVector

tensor: Tensor
tensor_product(other, *, sparse=None)

Tensor product of two states with metadata propagation.

If any operand is dense, the result is dense. Supports one-hot fast path. The resulting state is normalized before returning.

Return type:

StateVector

Args:

other: Another StateVector or a BasicState/occupation list. sparse: Override sparsity of the result; default keeps dense if any input dense.

Returns:

StateVector: Combined state with summed modes/photons (normalized).

Raises:

ValueError: If tensors are not 1D.

to(*args, **kwargs)

Return a new StateVector with the tensor moved/cast via torch.Tensor.to.

Return type:

StateVector

to_dense()

Return a dense, normalized tensor view of the amplitudes.

Return type:

Tensor

to_perceval()

Convert to pcvl.StateVector.

Return type:

StateVector | list[StateVector]

Args:

None

Returns:

pcvl.StateVector | list[pcvl.StateVector]: A Perceval state for 1D tensors, or a list for batched tensors, with amplitudes preserved (no extra renormalization).

merlin.core.generate_state(n_modes, n_photons, state_pattern=StatePattern.DEFAULT)

Generate a Perceval Fock input state as a BasicState.

Return type:

BasicState

Args:

n_modes: Number of photonic modes. n_photons: Total number of photons. state_pattern: Placement strategy for the photons.

Returns:

A perceval.BasicState instance.

Raises:

ValueError: If the inputs are inconsistent or the pattern is unknown.

Submodules