Skip to content
epelesPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

shotglass

Statistical assertions for quantum circuit tests.

A quantum circuit doesn't return a value. It returns a distribution, sampled a few thousand times. Nearly every quantum test suite in the wild asserts on that sample with an operator built for deterministic code, and ends up with a test that is either flaky or asleep:

assert counts == {"00": 500, "11": 500}   # passes once, by luck, never again
assert counts["00"] > 450                 # where did 450 come from?
assert abs(counts["00"]/shots - 0.5) < 0.05   # what is the false-alarm rate here?

The third one is closest, and it is still guessing. shotglass replaces the guess with a hypothesis test whose false-alarm rate you choose on purpose.

import shotglass as sg

counts = backend.run(bell, shots=4096).result().get_counts()

sg.assert_distribution(counts, {"00": 0.5, "11": 0.5})

No runtime dependencies. Works with Qiskit, Cirq, Braket, PennyLane or a plain collections.Counter — every function takes a {outcome: count} mapping, which is the one thing they all agree on.


Install

pip install shotglass

What it gives you

1. Goodness of fit

Is this sample consistent with the distribution the circuit is supposed to produce? Pearson chi-square, with low-expectation bins pooled automatically.

sg.assert_distribution(counts, {"00": 0.5, "11": 0.5}, alpha=0.005)
sg.assert_uniform(counts, [f"{i:03b}" for i in range(8)])   # a Hadamard wall

Measuring an outcome the expected distribution gives zero weight is not treated as a statistical event at all. It fails immediately as a structural error, because no shot count makes it acceptable — it means the qubit ordering, the endianness or the circuit is wrong:

distribution: measured outcomes with zero expected probability: '01' x2.
  This is not noise. Check qubit ordering, bit-string endianness, or whether
  the circuit is the one you think it is.

2. The regression guard

You rarely know the exact distribution a non-trivial circuit should produce. You always know it should produce the same one it produced before your refactor.

sg.assert_same_distribution(counts, baseline, label_a="now", label_b="baseline")

Chi-square test of homogeneity, so the two runs may have different shot counts. This is the assertion that belongs in CI: it catches the transpiler upgrade, the gate-ordering slip and the seed that quietly stopped being fixed, without anyone deriving the right answer by hand.

3. Single outcomes — and the difference between two questions

sg.assert_probability(counts, "101", 0.25)                      # exact binomial
sg.assert_equivalent_probability(counts, "101", 0.25, 0.01)     # TOST
sg.assert_deterministic(counts, "101")                          # noiseless
sg.assert_deterministic(counts, "101", min_probability=0.95)    # on hardware

assert_probability asks "can I rule out that this differs from 0.25?". assert_equivalent_probability asks "can I show this is within 0.01 of 0.25?". These are different questions and the first cannot answer the second — a non-significant result is also what too few shots looks like. Equivalence has to be claimed directly, so the whole confidence interval must sit inside the tolerance band.

assert_deterministic with a hardware threshold applies it to the lower confidence bound, so 96 successes in 100 does not clear a 0.95 bar. It looks like 0.96, but with 100 shots the true rate could comfortably be 0.90.

4. Power: is this test capable of failing?

Run a Bell state with 20 shots and assert uniformity and it will pass almost whatever the circuit does — 20 shots cannot tell 50/50 from 65/35. Green, meaningless, and no one ever notices.

sg.required_shots(effect_size=0.1, dof=1, alpha=0.005, power=0.8)   # -> 1332
sg.detectable_effect(n=1024, dof=1)        # what this run can actually catch

Or make the assertion refuse to report a pass it couldn't have avoided:

sg.assert_distribution(counts, expected, detect=0.1)
InsufficientPowerError: 20 shots give only 1% power to detect an effect of
w=0.1 at alpha=0.005; you asked for 80%.
  This test would have passed almost whatever the circuit did.
  Use at least 1332 shots, or lower `detect`.

Shot count is the sample size of a quantum experiment. It is usually chosen by habit — 1024, because it's a power of two. This lets you choose it on purpose.


The flakiness problem, and the fix

Every statistical assertion fails on correct code some of the time. That is what alpha means. It is fine for one test and corrosive for a suite:

assertions alpha expected false failures per run
1 0.005 0.005
100 0.005 0.5
600 0.005 3
600 0.05 30

Three red builds a day, each a different test, none reproducible. The team learns that red means nothing and starts hitting re-run. The suite is now decoration.

Tightening alpha doesn't fix it — it just trades false alarms for blindness to real bugs. The fix is to stop judging each assertion alone and control the error rate of the suite as a whole:

with sg.deferred(fdr=0.05) as suite:
    for case in cases:
        sg.assert_distribution(run(case), case.expected)

print(suite.summary())
shotglass: 400 assertions, 4 below their own alpha, 0 surviving BH at q=0.05
  p-value uniformity (KS vs Uniform(0,1)): 0.031

Benjamini-Hochberg bounds the expected share of false alarms among the failures reported, so a large suite stays quiet when the code is correct and still goes red when it isn't. Structural failures — impossible outcomes — bypass the correction entirely; they aren't p-values and must not be smoothed away.

That p-value uniformity line is worth more than any single test. If every circuit under test is correct, the suite's p-values are uniform on (0, 1). A pile-up near zero means real bugs. A pile-up near one is more interesting: it usually means expectations were fitted to the same data being tested, or that shots are being reused across assertions.

pytest

The plugin installs itself:

pytest --shotglass-fdr=0.05

Assertions inside tests marked @pytest.mark.shotglass are collected across the whole session and judged together, with the p-value diagnostic in the terminal summary.


Why there is no assert_fidelity_above()

It was written, tested, and cut. Fidelity and total variation distance are the numbers this field reaches for, so a gate on them is the obvious feature — and it is wrong.

Observed fidelity is biased downward by finite shots. A perfectly correct 16-outcome circuit, measured with 100 shots, reports a fidelity around 0.96, not 1.0, because sampling noise alone moves the histogram away from the reference. Bootstrapping the shots reproduces that bias instead of removing it. So a gate at 0.95 fails correct circuits at low shot counts and passes broken ones at high ones: it is measuring your shot budget, not your circuit.

hellinger_fidelity, total_variation_distance and kl_divergence are all here, because they are useful for reporting and for ranking. They are not assertable, and shot_noise_interval() exists to show you how much of the number you're looking at is noise. When you want a pass/fail, use assert_distribution — it is calibrated, and its calibration is tested.


Design notes

No runtime dependencies. The incomplete gamma and beta functions, the chi-square, non-central chi-square, normal and binomial tails and the Wilson interval are implemented directly (_stats.py) from standard series and continued fractions. A test library that drags SciPy into every CI image is a test library people route around. The functions are verified against SciPy in the test suite — where it's installed — to a relative error below 1e-10.

No backend imports. Adapters for five frameworks are five things to keep working. A counts mapping is the interface.

The library is calibrated, and that is tested. tests/test_assertions.py runs 2000 correct Bell states and checks the false-alarm rate lands near alpha, runs a genuine 10% bias and checks it is caught essentially every time, and checks the p-values are uniform under the null. A statistics library that doesn't test its own error rates is asking to be trusted on vibes.

Wilson, not Wald. Wald intervals collapse to zero width at p=0 and p=1 — exactly where quantum tests live — and silently pass everything.


Status

Beta. The API is small on purpose and I'd rather cut a function than ship one that misleads. Issues and PRs welcome, particularly from people running these assertions against real hardware, where the noise model is not the one the tests assume.

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages