Docs

Certified randomness

A quantum random-number generator turns an unpredictable physical source into certified bits. The hard part is not the qubit — it is keeping the source balanced while it drifts, so a randomness extractor stays efficient. SWC does this as a regulation problem, and the runtime needs no change to do it: it is the same residual update law, holding a measured value at a setpoint.

The principle: decouple control from extraction

Take a single-qubit source RY(α) with P(1)=sin²(α/2). Thermal and mechanical drift move the operating point off p=0.5. If you try to extract randomness directly from the raw control loop, the loop’s own dynamics leak into the bitstream — lag-1 autocorrelation climbs and the stream fails certification. The fix is to keep the two jobs separate:

  • Control (SWC): hold the measured p at 0.5 from one measurement per block. This is regulation, n=1, target=[0.5].
  • Extraction (standard, your side): run a published, certifiable extractor — von Neumann, or a leftover-hash / SHA-256 construction — on the balanced stream. The extractor, not SWC, guarantees full min-entropy and ~zero autocorrelation.

SWC improves the yield of certified bits; the extractor guarantees their quality. Keeping them decoupled is what makes the output certifiable.

Why balance is yield

A von Neumann extractor keeps one output bit per unequal adjacent pair, so its yield is proportional to 2p(1−p) — maximal at p=0.5 and collapsing as the source skews. Hold the source at balance and the extractor runs at peak efficiency every block; let it drift and most of the input is discarded.

Full client-side loop

The runtime is the regulator; the extractor lives entirely on your side. Each block: measure p over a window of shots, send it to the runtime, apply the returned control angle, extract from the raw bits.

copyfrom swc import swc_regulate
import numpy as np

SHOTS = 4096
alpha = np.pi / 2                     # start balanced

def measure(_):
    bits = sample_qubit(alpha, SHOTS)  # your hardware: returns 0/1 array
    measure.last = bits
    return [bits.mean()]               # observed p, in [0,1]

def von_neumann(bits):
    out = []
    for i in range(0, len(bits) - 1, 2):
        if bits[i] != bits[i+1]:
            out.append(int(bits[i]))   # certified bit
    return out

stream = []
def on_step(state):
    global alpha
    alpha = state.x[0]                 # runtime-held control angle
    stream.extend(von_neumann(measure.last))

swc_regulate(
    measure=measure,
    x0=[np.pi / 2],
    target=[0.5],                      # hold the source balanced
    license_key="EVAL-...",
    rounds=2000,
    on_step=on_step)

print(f"certified bits: {len(stream)}")

The runtime is necessary, not decorative

In a four-arm test under severe drift — (1) extractor alone, (2) SWC alone with no extractor, (3) SWC into the extractor, (4) a fixed-bias guess — only the arms that include a standard extractor are certifiable, and among those, SWC + extractor delivers materially more certified bits than the extractor alone on the same drift. SWC alone (no extractor) holds the source balanced but cannot certify; the extractor alone certifies but starves on yield as the source skews. You need both, and the runtime is what keeps the yield up. Removing the extractor is not an option — the raw regulated stream carries loop dynamics and fails certification on its own.

Where the advantage lives

Drift regimeCertified-yield advantage (SWC+ext vs ext alone)
Gentle~1.1× — source stays near balance on its own; little to recover
Moderate–severe1.5–1.8× — the regime where regulation pays
Unrecoverablefades — if drift outruns the control range, balance cannot be held

The stronger the extractor, the more the held source helps: against a leftover-hash / SHA-256 extractor the yield advantage was measured higher still, because a better extractor converts the recovered balance more fully into output bits.

Setup, step by step

A complete deployment is five decisions. None of them touch the runtime internals — you are wiring your entropy source and your extractor around a regulation session.

  1. Expose your source as a bias measurement. Your hardware must return, per block, an estimate of p = P(1) over a window of SHOTS raw bits. Larger windows give a less noisy p (the control signal) at the cost of latency; 2–8k shots/block is a sensible starting range. The runtime regulates on this single scalar per block.
  2. Pick your control handle. One actuator that moves the bias monotonically near balance — an RY rotation angle, a bias voltage, a detector threshold. You do not need its sign or gain; the regulation session measures the drive direction itself in its first few rounds (see drive-direction).
  3. Open a regulation session at the balance point. n=1, target=[0.5], start the actuator at its mid-range. Each block: read p, call step, apply the returned setting.
  4. Extract on the raw bits, never on p. Feed the per-block raw bitstream to a published extractor. Von Neumann is the simplest certifiable choice; for higher throughput use a leftover-hash / Toeplitz or SHA-256 construction with a conservative input-entropy estimate. The extractor is what certifies; the runtime only keeps its input balanced.
  5. Gate on certification, continuously. Run your health checks on the extracted stream (min-entropy rate, lag-1 autocorrelation, and your standard test battery) and drop output if a gate fails. The runtime keeps yield high; certification is still your release gate.

Drop-in reference

The same loop as above, written so each numbered decision is visible. Swap the two hardware stubs (sample_qubit, your extractor) for your bench and it runs unchanged.

copyfrom swc import SWCOptimizer
import numpy as np, hashlib

SHOTS   = 4096          # (1) bias-estimate window per block
TARGET  = [0.5]         # balance point

opt = SWCOptimizer(license_key="EVAL-...", n=1,
                   mode="regulation", target=TARGET)
x = opt.start([np.pi/2])              # (2)(3) start the actuator mid-range

def von_neumann(bits):                # (4) certifiable extractor
    return [int(bits[i]) for i in range(0, len(bits)-1, 2)
            if bits[i] != bits[i+1]]

stream = []
for _ in range(2000):
    bits = sample_qubit(x[0], SHOTS)  # your hardware: 0/1 array of length SHOTS
    stream.extend(von_neumann(bits))  # (4) extract on RAW bits
    p = float(np.mean(bits))          # (1) bias estimate -> control signal
    x = opt.step([p], target=TARGET)  # (3) runtime holds p at 0.5
opt.end()

# (5) certification gate on the extracted stream
s = np.array(stream); p1 = s.mean()
h_inf = -np.log2(max(p1, 1-p1))            # min-entropy rate, want ~1.0
ac1   = np.corrcoef(s[:-1], s[1:])[0,1]    # lag-1 autocorr, want ~0
assert h_inf > 0.99 and abs(ac1) < 0.01, "certification gate failed"
print(f"certified bits: {len(stream)}  H_inf={h_inf:.3f}  ac1={ac1:+.4f}")

The balance the runtime maintains shows up directly in the yield: the closer mean|p−0.5| stays to zero, the more pairs the extractor keeps. That is the entire mechanism, and it is why the advantage is a yield multiple, not a quality claim.

Scope & honesty

  • The numbers above are a faithful single-qubit simulation (RY source, finite shots, realistic drift). They are SIMULATED, not hardware-measured.
  • The advantage is a yield multiple in the 1.5–1.8× range — not orders of magnitude, and not a quality claim. Quality comes from the extractor.
  • Hardware validation on a real entropy source gates any product claim. The mechanism — regulation holds balance, balance is extractor yield — is substrate-independent, but the magnitude must be measured per device.
  • The advantage vanishes if drift is unbounded or unrecoverable; SWC rescues yield only when the source stays within the control range.

See the regulation docs for the underlying loop, and the certified-randomness demo to watch the yield curves separate as you raise drift severity.