Spotting the Flaw: A Quantum-Classical Experiment in Visual Anomaly Detection

Every bottling line eventually produces a bottle it shouldn’t: a hairline fracture, a chip along the rim, a smear of contamination on the glass. Catching such defects automatically is a deceptively hard problem, not because the flaws themselves are complex, but because they are rare. A line can run for hours before producing a single bad unit, so there is rarely enough labeled defect data to train an ordinary classifier the way one might train a model to tell cats from dogs. The more practical framing, used in a recent study by the engineering team, is one-class learning: show a model thousands of images of what “good” looks like, and ask it to flag anything that deviates from that picture, without ever showing it an actual defect during training.

The study set out to compare two very different ways of drawing that boundary: a classical ensemble method called Isolation Forest, and a quantum circuit known as a Variational Quantum Classifier (VQC). Both were tested on the bottle category of MVTec AD, a widely used industrial benchmark whose images are either defect-free or flawed in one of three ways — broken_large (major structural fractures), broken_small (minor chips and cracks), or contamination (surface stains and deposits).

A shared starting point

To keep the comparison fair, both branches share an identical front end. Each 900×900 pixel image passes through a convolutional network pretrained on ImageNet with its final classification layer removed, producing not a label but a 2048-number fingerprint of the image’s visual texture and structure. Those numbers are standardized using statistics from the training set of good bottles only, so no information about the defects leaks into preprocessing, then compressed to just 10 dimensions with principal component analysis. Despite that aggressive compression, the ten retained components capture roughly half of the total variance in the embeddings — enough, it turns out, to separate the two classes; the first three components alone account for more than a quarter of it. Because both branches inherit these same ten numbers, any difference in performance downstream comes from how each classifier reasons over them, not from how the features were extracted.

Branch one: an old, reliable idea

The classical branch relies on Isolation Forest, which identifies outliers through a simple insight: anomalies are easier to isolate than normal points. The algorithm builds an ensemble of trees that split the data along random feature thresholds, and a point that differs from the bulk of the data tends to need far fewer splits before it sits alone in its own partition. This implementation used 400 such trees, fit exclusively on the compressed embeddings of defect-free bottles, and reached 91.6 percent accuracy on the test set, with a strong 98.3 percent precision on the anomaly class — it rarely cried wolf. Its weakness showed up in recall: it missed six defective bottles, mostly small chips and low-contrast contamination sitting close enough to normal texture variation to slip past the boundary.

Branch two: encoding a bottle into ten qubits

The quantum branch takes the same ten PCA values and uses each as a rotation angle, applying a Ry gate to initialize one qubit per feature. This “angle embedding” turns a classical vector into a quantum state living in a 1,024-dimensional Hilbert space, since ten qubits span two-to-the-tenth possible basis states. From there, the circuit applies three Strongly Entangling Layers: each one rotates every qubit through a further sequence of parameterized gates, then links neighboring qubits in a ring using CNOT gates, so the state of each qubit becomes correlated with its neighbor’s.

The full circuit has 90 trainable parameters, tuned with the Adam optimizer over 80 epochs, again using only defect-free images. Training pushes good bottles toward a state where all ten qubits are measured as zero; a bottle’s anomaly score is then one minus that measured probability, with the cutoff set at the 90th percentile of scores observed during training, 0.9972. The appeal of this design, in theory, is that entanglement lets the circuit represent joint, nonlinear relationships between the ten features that a tree-based model doesn’t naturally capture — though whether that theoretical appeal shows up in practice is the actual question the experiment set out to answer.

What the numbers say

The quantum circuit edged out the classical baseline, reaching 92.8 percent accuracy against 91.6, with recall improving to 93.7 percent from 90.5 — three additional defects caught, by the team’s count. It gave up a little precision in exchange, 96.7 percent versus the Isolation Forest’s 98.3, tripped up by two good bottles that scored between 0.998 and 0.999, just over the line. The quantum scores overall were sharply polarized: the great majority of defective bottles scored almost exactly 1.000, while good bottles spread more broadly across lower values, which suggests the cutoff is a reasonably stable one rather than a lucky draw. Both models, notably, stumbled on the same kind of case — subtle, low-contrast defects that resemble normal surface texture — which hints that the bottleneck may sit upstream, in the shared feature extraction, rather than in either classifier.

It’s worth being precise about what this result does and doesn’t show. The VQC here ran as a simulation on classical hardware, not on an actual quantum processor, and training it took on the order of ten to a hundred times longer than fitting the Isolation Forest, since every gradient step requires simulating a ten-qubit state vector. A recall gain at that computational cost is an interesting empirical result on one specific dataset, not evidence of a general “quantum advantage.” Both classifiers also share the same structural limits: neither can point to where on the bottle a flaw sits, since both output a single score rather than a localized map, and both thresholds are only as trustworthy as how well the training set of good bottles represents real-world variation.

The more useful reading is as a well-controlled feasibility check: a modestly sized quantum circuit can match, and here slightly exceed, a strong and far cheaper classical baseline on a real industrial vision task. The natural next steps — running the same circuit on actual quantum hardware such as IBM’s or IonQ’s processors, blending its score with a classical reconstruction-error signal, and adding tools like Grad-CAM to localize defects rather than merely flag them — should show whether this early edge survives outside of simulation, and whether it is worth the bill.

Bell inequality on real quantum hardware

Image: CERN – https://home.cern/news/news/physics/fifty-years-bells-theorem

We run a Bell test in the CHSH formulation on two real quantum platforms: the goal was not to demonstrate anything new, but to use a well-known experiment as a direct physical benchmark to understand how much a real quantum processor can preserve entangled correlations. This test could fit the purpose because it produces a number that is easy to interpret, that is the Bell parameter: if the value remains less than or equal to 2, the result is compatible with a local classical description. If it exceeds 2, a violation of Bell’s inequality is observed, and, in particular, the theoretical quantum maximum is 2*√2​, approximately 2.82843. An important aspect of this experiment is that the measurement basis is chosen using block randomization, that is instead of first measuring all the data for one given configuration and then moving on to the next, the different measurement settings are randomly mixed throughout the execution. This has been done to reduce the imperfection of the real hardware due to calibrations, noise, temporal drift, and operating conditions, thus making a random choice of measurement basis would reduce the risk. Further, this point wanted to reproduce the spirit of Alain Aspect’s experiments on the violation of Bell inequalities. In that case, the choice of measurement basis was critical: changing the orientation of the analyzers during the experiment served to avoid the particles from being interpreted as already “prepared” with respect to a fixed measurement configuration. In Aspect’s case, the change of basis therefore had a very deep foundational meaning, connected to locality and the separation between measurement choices.

In our case, much more humbly, no locality loophole is being closed: the qubits are on the same device, the experiment is digitally programmed, and the measurements are not spatially separated as in an optical Bell test and the methodological idea is: not allowing a fixed measurement configuration to dominate an ordered part of the experiment.

For each experiment, 100,000 shots were used because the quantities observed in the Bell test are derived from measured probabilities and increasing the number of shots reduces the statistical error on the observed frequencies and as a consequence on the calculated correlations.

The result (Bell parameter) on the first real hardware technology was 2.45294 ± 0.00499, well above the classical limit of 2. The deviation from the ideal quantum value was 0.37549, corresponding to about 86.7% of the theoretical maximum, that is the apparent loss of visibility was about 13.3% and the statistical significance with respect to the classical limit was approximately 90.7 sigma.

On the second real hardware technology, the result was also clearly quantum, as the measured value was 2.40736 ± 0.00505, still above the classical limit and this time the deviation from the ideal value was 0.42107, corresponding to about 85.1% of the theoretical maximum with an apparent loss of visibility of about 14.9%, with a statistical significance of approximately 80.7 sigma with respect to the classical limit.

It is useful to interpret the deviation from the ideal value not as a pure measure of a single type of “noise” but as an aggregate indicator of experimental degradation: gate errors, readout errors, decoherence, drift, and calibration imperfections all contribute to reducing the observed value, giving a better view of what measured experimentally with random circuits in previous pieces of work. In particular, it should be noted that the closer the result is to the ideal maximum, the better the device is preserving quantum correlations; the closer it moves toward the classical limit, the more noise has degraded the experiment.

Here below a sample of the used circuits and result of the 100000 runs on the first real hardware.

RESULTS ON REAL HARDWARE

E(a,b) = 0.62446 ± 0.00247 N = 100000
E(a,b’) = 0.59396 ± 0.00254 N = 100000
E(a’,b) = 0.60250 ± 0.00252 N = 100000
E(a’,b’) = -0.63202 ± 0.00245 N = 100000

S CHSH = 2.45294 ± 0.00499

Main readings for quantum circuits simulations

The following references provide background on quantum noise, random circuits, and entanglement dynamics. The presented notes are inspired by these research directions but focus on a simplified, empirical description of noise sensitivity based on effective scaling variables. I found them all interesting and hope you will too.


H. M. Wiseman and G. J. Milburn, Quantum Measurement and Control. Cambridge, U.K.: Cambridge Univ. Press, 2009
K. Jacobs and D. A. Steck, “A straightforward introduction to continuous quantum measurement,” Contemporary Physics, vol. 47, no. 5, pp. 279–303, 2006.
M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information. Cambridge, U.K.: Cambridge Univ. Press, 2000.
J. Preskill, “Quantum computing in the NISQ era and beyond,” Quantum, vol. 2, p. 79, 2018.
L. Willsch et al., “Benchmarking the QASMBench quantum circuits,” arXiv:2005.11227, 2020.
A. M. Dalzell, J. R. Garrison, Z. Kim, and J. Klassen, “Random quantum circuits transform local noise into global white noise,” arXiv:2111.14907, 2021.
A. M. Dalzell et al., “How noise transforms quantum circuits,” Communications in Mathematical Physics, 2024.
Y. Takahashi, S. Tani, and K. Sato, “Simulating quantum circuits with noise,” Theoretical Computer Science, vol. 876, pp. 1–18, 2021.
S. Bravyi, D. Gosset, and R. König, “Quantum advantage with shallow circuits,” Science, vol. 362, no. 6412, pp. 308–311, 2018.
D. N. Page, “Average entropy of a subsystem,” Physical Review Letters, vol. 71, no. 9, pp. 1291–1294, 1993.
A. W. Harrow and R. A. Low, “Random quantum circuits are approximate 2-designs,” Communications in Mathematical Physics, vol. 291, pp. 257–302, 2009.
A. W. Cross, G. Smith, and J. A. Smolin, “Quantum circuits for strongly mixing states,” Physical Review A, vol. 89, 2014.
Y. Zhang, B. Skinner, and A. Nahum, “Universal entanglement dynamics in noisy quantum circuits,” arXiv:2205.13999, 2022.
P. Hayden, D. Leung, and A. Winter, “Aspects of generic entanglement,” Communications in Mathematical Physics, vol. 265, pp. 95–117, 2006.
M. Urbanek et al., “Mitigating depolarizing noise on quantum computers,” arXiv:2103.08591, 2021.
K. Temme, S. Bravyi, and J. M. Gambetta, “Error mitigation for short-depth quantum circuits,” Physical Review Letters, vol. 119, p. 180509, 2017.
S. Endo, S. C. Benjamin, and Y. Li, “Practical quantum error mitigation for near-future applications,” Physical Review X, vol. 8, p. 031027, 2018.
A. Kandala et al., “Error mitigation extends the computational reach of a noisy quantum processor,” Nature, vol. 567, pp. 491–495, 2019.
A. Bouland, B. Fefferman, C. Nirkhe, and U. Vazirani, “On the complexity and verification of quantum random circuit sampling,” Nature Physics, vol. 15, pp. 159–163, 2019.
B. Fefferman and R. Umans, “The power of quantum Fourier sampling,” SIAM Journal on Computing, vol. 45, no. 2, pp. 551–575, 2016.
A. Nahum, J. Ruhman, S. Vijay, and J. Haah, “Quantum entanglement growth under random unitary dynamics,” Physical Review X, vol. 7, 2017.
B. Fefferman et al., “The effect of noise on quantum circuits,” PRX Quantum, vol. 5, 2024.

Predicting Quantum Circuit Noise Sensitivity from Structure,

Entropy, and Effective Noise Scaling


Understanding how noise propagates through quantum circuits is a central problem in near-term quantum computing. While gate error rates and circuit depth provide partial explanations of circuit degradation, the relationship between circuit structure, state properties, and observable noise sensitivity remains poorly characterized. In this work we introduce a predictive framework for estimating local noise sensitivity in quantum circuits. We combine (i) an effective noise accumulation coordinate derived from gate counting, (ii) entropy-based descriptors of local state mixing, and (iii) machine learning models trained on circuit structural features. Using simulations on QASMBench circuits under depolarizing and readout noise, we show that a simple exponential saturation model based on an effective noise coordinate explains moderate variance in local total variation distance (TVD).

Keywords: quantum circuit noise sensitivity, effective noise scaling, entropy-based descriptors, total variation distance, machine learning prediction

Local Entropy as a Universal Predictor of Noise Sensitivity

in Variational Quantum Circuits


Noise accumulation limits the performance of variational quantum circuits in the noisy intermediate-scale quantum (NISQ) regime. Standard analyses typically rely on global distributional metrics, such as total variation distance (TVD) over full measurement outputs. However, in highly expressive or scrambling circuits, global TVD often saturates and becomes insensitive to structural differences between ansatz families. In this work we show that local entropy provides a universal control parameter for local noise sensitivity under depolarizing noise. We prove that the marginal TVD of one-qubit and two-qubit subsystems is upper-bounded by a function of the entropic deficit from maximal mixing. We then demonstrate numerically that scrambling circuits exhibit entropic self-averaging, leading to a universal collapse of local TVD when plotted against mean single-qubit entropy. Furthermore, we identify the ratio between two-local and one-local sensitivities as a structural marker of scrambling dynamics. These results establish local entropy as a principled and architecture-independent predictor of measurement-level noise response.

Keywords: local entropy, noise sensitivity, variational quantum circuits, depolarizing noise, marginal total variation distance


Inversion and Reconstruction of Quantum States under Continuous – Weak Measurement and Discrete Circuit Noise


Abstract

Quantum information processing is fundamentally constrained by measurement backaction and environmental noise. This work develops a unified quantitative study of quantum state degradation and reconstruction across two complementary dynamical regimes: continuous weak measurement described by stochastic master equations (SME), and discrete gate-based quantum circuits subject to depolarizing and readout noise.

In the continuous regime, we demonstrate stable exponential convergence of a stochastic quantum filter toward the true conditional state under finite detection efficiency. In the circuit regime, we analyze a bounded subset of QASMBench OpenQASM circuits under a structured noise sweep and measure output distributional divergence using Total Variation Distance (TVD). We identify an empirical exponential saturation law and show that degradation collapses onto a compact effective interaction variable.

Keywords: quantum state reconstruction, stochastic master equation, continuous weak measurement, quantum circuit noise, total variation distance, exponential scaling law


Predicting Quantum Hardware Noise from Circuit Structure

A machine learning model was developed to predict the discrepancy between ideal and experimentally measured quantum circuit output distributions when executing circuits on a real quantum hardware backend. The target quantity is the total variation distance (TVD) between the ideal distribution obtained from classical simulation and the distribution observed from hardware execution. The goal is to determine whether structural properties of a circuit, together with information derived from ideal simulation, can be used to estimate how strongly hardware noise will distort the circuit’s output.

The dataset consists of families of parameterized quantum circuits with varying depth, entangling structure, and topology. For each circuit, the ideal output distribution is computed using a classical simulator, while the same circuit is executed on a real quantum processing backend to obtain the measured output distribution. From these circuits, features describing the circuit structure (such as depth and two-qubit gate structure) and statistics of the ideal output distribution are extracted and used as inputs to a regression model.

A ML algorithm trained on these features achieves strong predictive performance when evaluated on a held-out test set drawn from the same circuit family distribution, achieving an R2 score of approximately 0.57 with a mean absolute error of about 0.033 TVD units. The model also shows a strong rank correlation (Spearman ρ≈0.82), indicating that it can reliably order circuits from more to less noise-sensitive even when exact prediction errors remain.

To test generalization beyond the training distribution, an additional experiment was conducted in which the model was trained on circuits belonging to two circuit topology families and evaluated on circuits from a third, previously unseen topology. Under this topology shift, predictive performance decreases to R2≈0.19 with a mean absolute error of approximately 0.048 and a rank correlation of ρ≈0.66. Although absolute prediction accuracy drops under this distribution shift, the model still preserves moderate ability to rank circuits by expected deviation from ideal behavior.

Overall, these results suggest that circuit-level structural features combined with ideal-simulation statistics contain meaningful information about hardware noise sensitivity. While accurate regression across unseen circuit families remains challenging, the model demonstrates promising capability for estimating relative circuit robustness prior to execution on quantum hardware that is extremely useful for high intensive and expensive workloads.

Navigating with the Wayfinder

The Vegvísir (Icelandic for “wayfinder”) is a magical stave from Icelandic folklore, often called the “Viking Compass,” designed to help its bearer find their way through storms or unknown territory, guiding them physically and spiritually.

I’d say that the closing year was really a rollercoaster due to tariffs concerns, interest rates, wars and geo-political issues.

Nevertheless, we wanted to close the experiments we were planning last year to combine a portfolio with 1/N allocation strategy and pick ten underlying by using a combined ML and mean variance techiques.

The final gain was 31% without recapitalization and a simple investment strategy, buy and hold for one year. In these days we are repeating the underlying selection for 2026 and get back with results in 12 months time, that is neither short nor long term.

This is compared with MVP OOS analysis, same period (violet curve) that lead to about 30% gain with deeper drawdowns. The other defect of the strategy is that it assumes the underlying will behave in the future as they did in the past and so it has no forecasting component in it, that, for example, would have led to losses in 2022.

Have a nice and healthy 2026!

Predicting the unpredictable

After two years out-of-sample test (shadow-trading) of the trading strategy, from August 2023 to August 2025 we can finally share results over a reasonable timeframe, with a severe shock in the market due to global market trade tariffs negotiations, several wars ongoing, etc.

The selected underlyings are NQ=F, ES=F, RTY=F, YM=F, futures on major indexes, extremely liquid, thus they could be related to most of the stock markets trends. No balance of the associated margins, one future each underlying traded and simple trading strategy. Daily predict gain or loss for each underlying and trade long or short accordingly, achieving a natural balance (almost market neutral as they could trade long or short independently every day). Initial margin 53k.

The summary results shows pros and cons and I leave to the reader to interpret results, especially because it is always personal in terms of the acceptable risk and the expected gains.

FULL PERFORMANCE SUMMARY (509 trading days)
Initial capital (margin): 53,000
Total PnL series length: 509 days
Equity = 53,000 + cumulative PnL
Starting equity: 57,465
Ending equity: 498,079

Return Metrics
Average daily return: +0.4538%
Average monthly return (~21 trading days): +9.97%
CAGR (annualized compound return): +189.44% per year
Total equity growth factor: ~8.7×

Risk Metrics
Annualized volatility: 38.05%
Sharpe ratio (rf = 0): 2.98
Sortino ratio: 5.58
Maximum drawdown: –17.64%
Calmar ratio (CAGR / MaxDD): 10.74
Win rate: 56.89%
Average up day: +1.61%
Average down day: –1.08%

Tail Risk (Historical)
1-day VaR 95%: –2.45%
1-day Expected Shortfall 95% (ES): –3.95%

Chaos in the Markets: Mandelbrot’s Fractal Vision of Finance

Some years back I received a gift from a friend (Antonio), a game-changing book “The (Mis)Behavior of Markets: A Fractal View of Risk, Ruin, and Reward”. In 2004 Mandelbrot introduced a new theory about the market movements suggesting that it is much more chaotic than what described by the classical theory. He showed that extreme price movements (crashes, booms) occur much more often than expected, thus suggesting that the long-tails of price movements are fatter than expected and markets are riskier than the used models can predict (including the most recent ones based on AI and ML). The two implications I have identified clearly, the former is that the Black-Scholes model is not suitable for options pricing as its assumption is that asset returns follow a normal distribution, while a distribution with fat tails is closer to the cauchy distribution. New fractal models have then been introduced under the assumption of the self similarity prices variation at different scale, based on volatility or, how I use to say, the energy of the system. It is curious to me that to some extent, the contents of the book, in some way, predicted the crash of 2008. The latter is that more attention should be paid to extreme cases as they occur more frequently than expected.

For first point, I wanted to verify the price distribution of three real underlyings, AAPL, BRK-A and IBM and their daily price variations over the last 42 years. You may notice that they follow a distribution more similar to Cauchy than to a Gaussian.

One of the most common suggested techniques by professional traders is to cover by buying a put option for every 100 owned stocks. Using AAPL stock again, as a reference, if a private investor owns 100 shares of Apple (AAPL) purchased at $218.27 each (as of close on last Friday), to protect the investment against potential declines, he/she decides to buy a put option with a strike price of $210 and an expiration in one month (priced at 3,65$). The cost of this option, known as the premium, varies based on factors like volatility and time until expiration, that is he/she has one month time to exercise the option, that is can profit both from an excessive drop and from a rise in price. If the price remains the same for one month, the loss is the option price that is 365$. Of course if the purchased put options are 3, at 200$ or the price is reached in an extremely volatile market, the value is not linear and the gain might be more consistent, covering the loss or even make the overall trade profitable. Last obvious consideration, when exercising the option in a positive ground, should close the long operation on the underlying as well to avoid a loss.

And now we come to the backtest simulation we anticipated in last article, that is reported in the following video. I have hypothesized two thresholds from open +3xσ and -3xσ (under the assumption the distribution of the previous days is normal even if we’ve understood it’s not) and that the trade is a buy when traversing the +3xσ and sell when traversing the -3xσ. If the price rebounds, in order to avoid losses, the trade operation is closed at the same price, otherwise at close. In two years it would have implied 389 operations and 13,4% gain on $100K if the trading commission is fixed and stop limit orders are executed perfectly (for lower capital the risk of impact of spread b/a is too high). You also need a perfect automated trading system to do that. As usual, it’s a matter of acceptable or not acceptable risk/reward ratio.

Considering that it’s not easy to gather historical price of options as the price is dependent from strike price, current price but also from volatility, assuming instead there is no overprice due to volatility (and the current market is extremely volatile), the dynamic P/L is shown in the following figure.

To make the long story short, looking at the graphs, in both cases (buying 1 PUT or 3 PUT) with a risk lower than 5% at any time, you could easily gain more than 20% in two weeks time, not considering the volatility component that would raise that value a lot.

Given that acceptable risk/reward is absolutely subjective – didn’t ever manage to get a response to the question: “what is an acceptable risk/reward ratio?” – up to the reader to evaluate if it is a good and safe trading strategy.