MerLin 0.4: Grimoire - #269
Conversation
…rify that no Error is raised
…en there is source noise and phase error without source noise reaches the coherent superpoisition path
…lct counts as mode-indexed metadata and triggers existing circuit-size compatibility check + added tests
…l processor and does not reach create_fresh_rp (which rejects local backend) + Deprecation of remote_processor with support in docs
PML-329 fix bad practices in tests with circuit construction
PML-280: introducing the ReservoirClassifier
…ctree issue is properly fixed
…ease # Conflicts: # pyproject.toml
PML-366: QCNN documentation
PML-374 Add memristor noise tests and TBPTT docs
PML-367(BugFix) Fixed user guide's toctree error
PML-368: photonic QGAN GPU tests and GPU benchmark
Merging main in release
|
@claude review |
|
Claude finished @CassNot's task in 7m 0s —— View job Claude review — MerLin 0.4: GrimoireReviewed the core source changes (≈100 files, 46k additions) across state/encoding, the noisy SLOS path, the measurement stack, 🔴 HIGH1. # merlin/core/merlin_processor.py:987,994
cache = self._layer_cache.get(layer.uid)
...
self._layer_cache[layer.uid] = {"config": config}All 2. Memristive state not moved by 🟠 MEDIUM3. Noisy g2 path allocates on 4. Unguarded renormalization on possibly-zero mass — 5. Occupancy readout silently renormalizes; 6. Memristive layers unusable with batched amplitude input — 7. 8. No seed / 9. Post-fit reconfiguration silently discards training — 10. Session path builds and discards a 11. 🟡 LOW / cleanup
Summary: Two HIGH issues (#1 shared |
✅ Coverage ReportOverall Coverage: 83.93% Coverage Status
Coverage reports are informational and do not block PRs. |
ben9871
left a comment
There was a problem hiding this comment.
Some issues but not blocking. Can be fixed in 0.4.1
MerLin v0.4: Grimoire
Overview
MerLin 0.4 is a major step toward practical photonic machine learning workflows.
It makes models easier to assemble, simulations more faithful to hardware, and
execution paths clearer from local experiments to QPU-oriented runs.
The release adds ready-to-use models in
merlin.models, including theQORC-inspired
ReservoirClassifier, thephotonic GAN
PhotonicGenerator, and thephotonic QCNN
QCNNClassifier. These models movecommon research patterns into reusable PyTorch modules, so users can spend less
time rebuilding plumbing and more time testing photonic learning ideas.
QuantumLayeralso becomes more hardware-aware. The new noisy SLOS simulationpath lets users train under realistic source, circuit, and photon-emission noise
when inference is intended to run on a QPU. This matters because training only
against ideal simulations can produce parameters that look good numerically but
fail once hardware noise is present. By exposing noise during training, MerLin
helps users optimize models for the conditions they actually expect at
inference time.
State preparation is now more explicit through
EncodingSpace. Users can choosehow an amplitude tensor represents a logical state, including full Fock,
unbunched, dual-rail, partitioned, and QLOQ-style encodings.
StateVectorthenvalidates and embeds that logical state into MerLin's canonical Fock basis,
removing a common source of silent shape and ordering mistakes.
Execution is more flexible as well.
MerlinProcessorcan now use a Percevalprocessor directly through
processor=, including local Perceval processors suchas SLOS and CliffordClifford backends. The same entry point also supports remote
processors, while session-based providers remain available. This keeps local
simulation, backend comparison, and remote execution inside the same Merlin
processor workflow.
Finally, 0.4 removes several compatibility paths that were deprecated in 0.3.
The supported APIs are now more explicit: computation space belongs in
MeasurementStrategy, amplitude inputs belong inforward(), and legacyboolean flags such as
no_bunchingare no longer accepted.New Features
ReservoirClassifier
ReservoirClassifieris the new ready-to-use QORC model inspired by thephotonic reservoir computing work. It builds a
frozen photonic reservoir from a Haar-random interferometer and trains only a
classical linear readout.
This makes the QORC workflow available as a reusable model instead of requiring
users to manually wire preprocessing, reservoir feature extraction, caching,
and readout training. The model supports optional scikit-learn dimensionality
reduction, reservoir feature normalization, cached embeddings, and direct
creation of PyTorch datasets for the readout.
Typical workflow:
ReservoirClassifier;fit_reservoir(X)on the training inputs;make_dataset(X, y)ortransform_reservoir(X)to train or inspect thereadout data;
predict(X)for logits on new inputs.PhotonicGenerator
PhotonicGeneratoris a PyTorch module for latent-to-sample generativeworkflows based on the photonic generative model. It
wraps one or more
QuantumLayerheads and delegates the final classicalinterpretation to an output adapter.
This provides a cleaner base for photonic GAN-style generators. Instead of
manually feeding latent variables into a quantum layer and reshaping raw
measurement distributions for each experiment, users can define a generator
with a latent dimension, one or more quantum heads, and an adapter such as
ImageAdapterorVectorAdapter.The generator exposes
sample_latent,measure,generate, and normalPyTorch
forwardbehavior.QCNNClassifier
QCNNClassifieradds a staged photonic QCNN model for image-like inputs,following the adaptive state-injection QCNN proposal.
Architectures are built from validated
QConv,QPool, andQDensestages.Users can provide their own stage sequence or rely on the default validated
architecture.
This gives users a higher-level image-classification model without requiring
them to assemble every quantum convolution, pooling step, and dense readout by
hand.
Memristive Phase Shifters
CircuitBuildernow supports memristive phase shifters throughadd_memristive_ps(...), following the idea explored inrecent photonic hardware work.
For machine-learning workflows, this gives a photonic layer a stateful
component that can carry information across repeated calls or timesteps. That
is useful for temporal dependence, recurrent-style models, feedback circuits,
and sequence experiments where the current circuit response should depend on
previous inputs rather than only on the current tensor.
The builder declares the memristive component, and
QuantumLayerowns theruntime state, history, serialization hooks, reset behavior, and
detach_memristive_state(...)helper. This moves a previously manual feedbacklayer pattern into the normal builder-layer contract.
Noisy SLOS Simulations
QuantumLayernow supports a noisy SLOS path driven bypcvl.NoiseModel.MerLin can account for the main hardware-relevant noise sources directly in
simulation:
g2;g2photons.Noisy simulations return probabilities. Source noise and stochastic phase
errors are represented as probability mixtures, so MerLin combines probability
distributions rather than returning ideal amplitudes.
For
g2and source-noise cases, outputs may span multiple photon-numbersectors. These outputs are represented through
SectoredDistributionandSectorResult, then converted back into tensors when required by the selectedmeasurement strategy.
EncodingSpace
EncodingSpacedescribes how the last dimension of an amplitude tensor mapsinto MerLin's canonical Fock basis. It makes logical amplitude inputs explicit
and removes the need to manually enumerate Fock states for common encodings.
Supported encodings include:
EncodingSpace.FOCKfor amplitudes already in full Fock order;EncodingSpace.UNBUNCHEDfor collision-free photonic states;EncodingSpace.DUAL_RAILfor qubit-like binary logical states;EncodingSpace(modes_per_photon=[...]);EncodingSpace.qloq(...).StateVector.from_tensor(..., encoding=...)validates the logical tensor,embeds it into Fock order, and returns a
StateVectorthat can be passed toQuantumLayer.forward().MerlinProcessor Local Processor Support
MerlinProcessornow accepts PercevalAProcessorobjects through thekeyword-only
processor=argument.This means local Perceval processors can be used from the same Merlin execution
interface as remote processors and sessions. Local processors use a local
backend route.
RemoteProcessorinstances passed throughprocessor=arenormalized to the remote backend route. The older
remote_processor=argumentstill works as a deprecated compatibility path.
This is useful when users want to evaluate Merlin models on local Perceval
backends, including local noisy or sampling backends, without leaving the
Merlin model execution workflow.
Improvements
Measurement and Output Handling
The measurement stack has been tightened around explicit output contracts.
MeasurementStrategynow owns the computation-space choice, and probabilityoutputs can be post-processed through readouts such as occupancy grouping.
Photon-loss, detector, and noisy source outputs are handled more consistently,
including outputs that span multiple photon-number sectors. Partial measurement
manual construction also validates measured and unmeasured mode partitions more
strictly.
Kernel and Feature-Map Cleanup
The kernel stack has been updated around the newer
QuantumLayerexecutionpath and clearer deprecation boundaries.
FeatureMapandFidelityKernelhave expanded coverage for builder metadata, angle encoding, state inputs, and
newer computation-space behavior.
Older kernel builder compatibility paths remain documented as deprecated where
they still exist.
StateVector and Sparse State Workflows
StateVectorand probability-distribution objects have improved support forsparse tensors and logical-to-Fock mappings. This helps amplitude-input
workflows stay memory-aware, especially when the logical state is much smaller
than the full Fock basis.
Documentation
The documentation has been expanded for the new 0.4 workflows:
StateVector.from_tensor(..., encoding=...);NoiseModelfields;PhotonicGenerator;ReservoirClassifierworkflows;MerlinProcessor;Several reproduced-paper and example notebooks were also updated or added,
including photonic QGAN, QCNN MNIST, QORC tutorials, neural network embedding,
HQPINN, NQE, and CACIB bankruptcy prediction.
Breaking Changes
no_bunchingremovedThe legacy
no_bunchingflag is no longer accepted on public layer and kernelentry points.
Use explicit computation-space configuration instead:
MeasurementStrategy.probs(computation_space=ComputationSpace.UNBUNCHED)MeasurementStrategy.probs(computation_space=ComputationSpace.FOCK)Constructor
computation_spaceremovedPassing
computation_spacedirectly toQuantumLayeris no longer supported.Computation space now belongs in the measurement strategy.
Legacy
MeasurementStrategyaccess removedLegacy enum-style measurement access such as
MeasurementStrategy.PROBABILITIES,MeasurementStrategy.MODE_EXPECTATIONS,and
MeasurementStrategy.AMPLITUDESnow fails with a migration error.Passing measurement strategies as strings, such as
"PROBABILITIES", is alsono longer supported. Use the factory methods:
MeasurementStrategy.probs(...)MeasurementStrategy.mode_expectations(...)MeasurementStrategy.amplitudes(...)MeasurementStrategy.partial(...)Constructor amplitude encoding removed
QuantumLayer(..., amplitude_encoding=True)is no longer accepted.Amplitude inputs should now be passed to
QuantumLayer.forward()as either aStateVectoror a complex tensor.Tensor constructor
input_stateremovedPassing a raw
torch.Tensoras constructorinput_stateis no longeraccepted. If a state object is needed at construction time, build it explicitly
with
StateVector.from_tensor(...).Deprecations
The
remote_processor=argument onMerlinProcessoris deprecated. New codeshould pass the same Perceval processor through
processor=.Kernel compatibility helpers such as
KernelCircuitBuilder,FidelityKernel.simple(...), and related simple-factory compatibilityarguments are deprecated and kept only for transition.
Compatibility and Maintenance
MerLin 0.4 updates the dependency floor to
perceval-quandela>=1.2.1andallows newer PyTorch versions up to
torch<=2.12.0.The test suite has been expanded substantially around noisy SLOS, g2 behavior,
encoding spaces, state-vector inputs, deprecation removals, MerlinProcessor
local execution, photonic generators, QCNNs, and QORC reservoir workflows.