diff --git a/docs/algorithms/orthogonal-networks.md b/docs/algorithms/orthogonal-networks.md index 7539242..9598ecb 100644 --- a/docs/algorithms/orthogonal-networks.md +++ b/docs/algorithms/orthogonal-networks.md @@ -184,5 +184,12 @@ The limits come from the same structure: ## Next The interface is in [Orthogonal Networks](../user-guide/orthogonal.md) and in the -`OrthogonalQNN` section of [Layers](../user-guide/layers.md). The papers are listed -in [References](references.md#orthogonal-networks). +`OrthogonalQNN` section of [Layers](../user-guide/layers.md). Three examples use +them on medical images: the +[certified classifier](../examples/orthogonal-certified-training.md) trains a deep +network of butterfly layers that keeps its Lipschitz bound at 1, the +[certified fine-tuning example](../examples/orthogonal-certified-fine-tuning.md) +adapts it from axial to coronal CT slices without losing its certificate, and the +[orthogonal QNN classifier](../examples/orthogonal-qnn-classifier.md) compares an +orthogonal circuit with classical networks and a variational circuit. The papers +are listed in [References](references.md#orthogonal-networks). diff --git a/docs/algorithms/references.md b/docs/algorithms/references.md index dbb39f0..d66a13f 100644 --- a/docs/algorithms/references.md +++ b/docs/algorithms/references.md @@ -257,6 +257,13 @@ These papers cover the orthogonal networks of `eigenkit.orthogonal`. [arXiv:2311.06243](https://arxiv.org/abs/2311.06243); X. Ma et al., *Parameter Efficient Quasi-Orthogonal Fine-Tuning via Givens Rotation*, ICML (2024), [arXiv:2404.04316](https://arxiv.org/abs/2404.04316). +- **Certified fine-tuning with butterfly adapters.** O. Tsurkan, L. Domingo, + V. Orlova, A. Sagingalieva, I. Zalaudek, R. D. Caposiena Caro, *Quantum-inspired + orthogonal adapters for certifiably robust medical image classification* (2026), + [arXiv:2611.18775](https://arxiv.org/abs/2611.18775). It shows that a butterfly + adapter keeps the Lipschitz bound, and with it the certified radius, of the + network it adapts, while LoRA and full fine-tuning do not. The two certified + examples follow it. ## Cross-cutting foundations diff --git a/docs/examples/orthogonal-certified-fine-tuning.md b/docs/examples/orthogonal-certified-fine-tuning.md new file mode 100644 index 0000000..28092a3 --- /dev/null +++ b/docs/examples/orthogonal-certified-fine-tuning.md @@ -0,0 +1,587 @@ +--- +extras: [torch, viz, benchmark] +--- + +# Certified Fine-Tuning with Butterfly Adapters + +## What this example shows + +The [previous example](orthogonal-certified-training.md) trained a network whose +Lipschitz bound \(L\) is 1, so every prediction comes with a certified radius: a +distance within which no change of the image can change the prediction. This +example asks what happens to that guarantee when such a network is adapted to a +new task. + +The certified radius of an image is + +\[ +r(x) = \min_{j \ne p} \frac{z_p(x) - z_j(x)}{L \, \lVert w_p - w_j \rVert_2}, +\] + +where \(z\) are the logits, \(p\) the predicted class, \(w_k\) the rows of the head +and \(L\) the bound of the features in front of the head. Adapting the network +changes its weights, and with them \(L\). Ordinary fine-tuning lets the +singular values of every weight drift, \(L\) grows, and the radii shrink by the +same factor, even when the accuracy is good. + +A *butterfly adapter* changes a frozen weight \(W\) by an orthogonal rotation +\(R(\theta)\), built from RBS (Givens) rotations, in front of it: + +\[ +W' = R(\theta) \, W, \qquad +W'^\top W' = W^\top R^\top R \, W = W^\top W . +\] + +\(W'\) has exactly the singular values of \(W\), for any \(W\) and any angles, so +the bound of the adapted network stays \(L_0\), the bound of the pretrained one, +and the certificate keeps its meaning. The angles start at zero, where +\(R = I\), so training starts from the pretrained network. + +We compare four ways of adapting the same pretrained network, all with a new +classification head: + +- **head only**: every pretrained weight stays frozen; +- **butterfly**: a butterfly adapter in front of every pretrained matrix; +- **LoRA** (Hu et al., ICLR 2022): a low-rank update \(W' = W + BA\) of rank 4, + with \(B = 0\) at the start, the usual parameter-efficient method; +- **full**: every pretrained weight is trained. + +See the [user guide](../user-guide/orthogonal.md#orthogonal-fine-tuning) for +`apply_orthogonal_adapters` and for the adapter on a single layer. + +## The data + +Two MedMNIST datasets (Yang et al., *Scientific Data* 10, 41, 2023) show the same +eleven abdominal organs in CT scans, cut in two different planes: + +- **OrganAMNIST**: axial slices, 34,561 training images. The network is + pretrained on it; +- **OrganCMNIST**: coronal slices, 12,975 training images and 8,216 test + images. The network is adapted to it, with only **1,000** labelled training + images, as when a new view of the data has few labels. + +The images are \(28 \times 28\) and grey. As in the previous example, each one is +padded to \(32 \times 32\) and flattened to a vector of 1024 values in \([0, 1]\), which +changes no distances. The files come from the MedMNIST record on Zenodo (CC BY +4.0) and are downloaded once, about 70 MB, into `~/.cache/medmnist`. + +```python +import copy +import time +import urllib.request +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import torch.nn.functional as F + +from eigenkit import GenericClassifier +from eigenkit.datasets import STYLE_COLORS, rc_params +from eigenkit.orthogonal.torch import ( + LLNHead, + MaxMin, + Orthogonal, + OrthogonalAdapter, + apply_orthogonal_adapters, + certified_accuracy, + certified_radius, + lipschitz_bound, +) + +URL = "https://zenodo.org/records/10519652/files/{}.npz?download=1" +FOLDER = Path.home() / ".cache" / "medmnist" + + +def load_medmnist(name): + """Images padded to 32 x 32 and flattened to 1024 values in [0, 1].""" + path = FOLDER / f"{name}.npz" + if not path.exists(): + FOLDER.mkdir(parents=True, exist_ok=True) + urllib.request.urlretrieve(URL.format(name), path) + out = {} + with np.load(path) as data: + for split in ("train", "val", "test"): + images = data[f"{split}_images"].astype(np.float32) / 255 + images = np.pad(images, ((0, 0), (2, 2), (2, 2))) + out[split] = (images.reshape(len(images), -1), data[f"{split}_labels"][:, 0]) + return out + + +source = load_medmnist("organamnist") +target = load_medmnist("organcmnist") +device = "cuda" if torch.cuda.is_available() else "cpu" + +subset = np.random.default_rng(0).permutation(len(target["train"][0]))[:1000] +X_few, y_few = target["train"][0][subset], target["train"][1][subset] +X_test, y_test = target["test"] +print(f"source train {source['train'][0].shape}") +print(f"target train {X_few.shape}, every class present: {len(np.unique(y_few)) == 11}") +print(f"target test {X_test.shape}") +``` + +```text +source train (34561, 1024) +target train (1000, 1024), every class present: True +target test (8216, 1024) +``` + +The same six organs, once in each dataset, show how different the two views +are. The network has to carry what it learned on the top row over to the bottom +row: + +```python +organs = ( + "bladder", + "femur-left", + "femur-right", + "heart", + "kidney-left", + "kidney-right", + "liver", + "lung-left", + "lung-right", + "pancreas", + "spleen", +) +shown = (0, 3, 4, 6, 7, 10) +with plt.rc_context(rc_params(theme="light")): + fig, axes = plt.subplots(2, 6, figsize=(9, 3.6)) + for row, (name, data) in zip(axes, (("axial", source), ("coronal", target))): + X, y = data["train"] + for ax, organ in zip(row, shown): + ax.imshow( + X[np.flatnonzero(y == organ)[0]].reshape(32, 32), + cmap="gray", + vmin=0, + vmax=1, + ) + ax.set_axis_off() + if name == "axial": + ax.set_title(organs[organ], fontsize=10) + row[0].text(-4, 16, name, rotation=90, ha="right", va="center", fontsize=10) + fig.tight_layout() + plt.show() +``` + +![png](orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_1_0_light.png){ .theme-image-light } +![png](orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_1_0_dark.png){ .theme-image-dark } + +## The pretrained certified network + +The pretrained network is the butterfly network of the previous example, eight +blocks deep, now with eleven outputs: + +\[ +x \in \mathbb{R}^{1024} +\;\to\; 8 \times \big[\, \text{butterfly}(1024) \to \mathrm{MaxMin} \,\big] +\;\to\; \text{head}(1024 \to 11). +\] + +It is trained on OrganAMNIST by `GenericClassifier`, as before: Adam with a +learning rate of \(10^{-3}\), batches of 128, cross-entropy, 30 epochs. + +A pretrained network usually reaches us as plain weight matrices, not as +rotation angles. To start from that situation, we turn every trained butterfly +into an ordinary `nn.Linear` layer that holds its \(1024 \times 1024\) matrix. The +matrices are orthogonal because of how they were trained, but nothing in an +`nn.Linear` keeps them so, and that is exactly the situation of fine-tuning. +The bound of the result, \(L_0\), is the product of their largest singular +values. + +```python +def make_network(depth, n_classes): + blocks = [] + for _ in range(depth): + blocks += [Orthogonal(1024, "butterfly"), MaxMin()] + return nn.Sequential(*blocks, LLNHead(1024, n_classes)) + + +start = time.time() +pretrained = GenericClassifier( + make_network(8, 11).to(device), + in_features=1024, + lr=1e-3, + epochs=30, + batch_size=128, + show_progress=False, + random_state=0, +).fit(*source["train"]) +source_accuracy = (pretrained.predict(source["test"][0]) == source["test"][1]).mean() +print( + f"pretrained on OrganAMNIST in {time.time() - start:.0f} s, " + f"test accuracy {source_accuracy:.3f}" +) + +layers = [] +for layer in pretrained.model_[:-1]: # every block, without the head + if isinstance(layer, Orthogonal): + linear = nn.Linear(1024, 1024, bias=False) + with torch.no_grad(): + linear.weight.copy_(layer.matrix()) + layer = linear + layers.append(layer) +backbone = nn.Sequential(*layers).to(device) +L0 = lipschitz_bound(backbone) +print(f"bound of the pretrained features: L0 = {L0:.6f}") +``` + +```text +pretrained on OrganAMNIST in 680 s, test accuracy 0.727 +bound of the pretrained features: L0 = 1.000002 +``` + +## Four ways to adapt it + +Every strategy gets a copy of the frozen backbone and a new head, +`LLNHead(1024, 11)`, which is always trained. + +- **Head only** leaves the backbone as it is. +- **Butterfly** calls `apply_orthogonal_adapters`, which replaces every + `nn.Linear` it selects by an `OrthogonalAdapter`: the frozen weight times a + butterfly rotation whose angles start at zero. It freezes everything else. +- **LoRA** has no module in the library, so a few lines define it: the frozen + weight plus \(BA\), with \(A\) of shape \(4 \times 1024\), and \(B\) of shape + \(1024 \times 4\) starting at zero. +- **Full** makes every backbone weight trainable. + +In all four, the adapted network at step zero computes exactly the pretrained +features. + +```python +class LoRA(nn.Module): + """A frozen linear layer plus a trainable update B @ A of low rank.""" + + def __init__(self, base, rank=4): + super().__init__() + self.base = base + self.A = nn.Parameter(torch.randn(rank, base.in_features) * 0.01) + self.B = nn.Parameter(torch.zeros(base.out_features, rank)) + + @property + def weight(self): + return self.base.weight + self.B @ self.A + + def forward(self, x): + return F.linear(x, self.weight) + + +def adapt(strategy): + torch.manual_seed(0) # the LoRA matrices A and the new head are drawn below + body = copy.deepcopy(backbone) + for p in body.parameters(): + p.requires_grad_(strategy == "full") + if strategy == "butterfly": + apply_orthogonal_adapters(body, lambda name, m: isinstance(m, nn.Linear)) + if strategy == "LoRA": + body = nn.Sequential(*[LoRA(m) if isinstance(m, nn.Linear) else m for m in body]) + return nn.Sequential(body, LLNHead(1024, 11)).to(device) + + +strategies = ("head only", "butterfly", "LoRA", "full") +pd.DataFrame( + { + "strategy": strategies, + "trainable parameters": [ + sum(p.numel() for p in adapt(s).parameters() if p.requires_grad) + for s in strategies + ], + } +) +``` + +| strategy | trainable parameters | +|:---|---:| +| head only | 11,275 | +| butterfly | 52,235 | +| LoRA | 76,811 | +| full | 8,399,883 | + +A butterfly adapter on 1024 channels has \(5{,}120\) angles, so the eight of them +train \(40{,}960\) parameters, fewer than the \(65{,}536\) of LoRA and 200 times +fewer than the \(8{,}388{,}608\) of full fine-tuning. The counts in the table add +the \(11{,}275\) parameters of the head to each. + +## Training + +`GenericClassifier` starts every fit by initialising the network again, which +is right for training from scratch but would throw the pretrained weights away; +an `OrthogonalAdapter` refuses to be re-initialised for this reason. Fine-tuning +therefore uses a short loop of its own. It is the same for every strategy: Adam +on the trainable parameters, batches of 128, cross-entropy, and the model after +the last epoch is the one we evaluate. + +The learning rate and the number of epochs differ between the strategies. Both +were chosen on the validation split of OrganCMNIST, by the highest validation +accuracy; the test set was not used. The learning rate came first, from +\(\{10^{-3}, 10^{-2}\}\) for the head, \(\{3 \cdot 10^{-3}, 10^{-2}, 3 \cdot 10^{-2}\}\) for +butterfly, \(\{10^{-4}, 10^{-3}, 10^{-2}\}\) for LoRA and +\(\{3 \cdot 10^{-5}, 10^{-4}, 3 \cdot 10^{-4}, 10^{-3}\}\) for full fine-tuning. The number +of epochs came next, from \(\{30, 60, 120, 200\}\). Full fine-tuning is best after +30 epochs and then starts to overfit the 1,000 images; the other three are best +after 120. The angles of a rotation need a larger step than the entries of a +weight matrix: a change of one angle turns a whole pair of rows. + +```python +def fine_tune(model, X, y, lr, epochs, batch_size=128): + params = [p for p in model.parameters() if p.requires_grad] + optimizer = torch.optim.Adam(params, lr=lr) + X = torch.tensor(X, device=device) + y = torch.tensor(y, device=device, dtype=torch.long) + generator = torch.Generator().manual_seed(0) + model.train() + for _ in range(epochs): + for batch in torch.randperm(len(X), generator=generator).split(batch_size): + optimizer.zero_grad() + F.cross_entropy(model(X[batch]), y[batch]).backward() + optimizer.step() + return model.eval() + + +def bound(body): + """L of the adapted features; LoRA layers are bounded by their weight.""" + if any(isinstance(m, LoRA) for m in body): + b = 1.0 + for m in body: + if isinstance(m, LoRA): + b *= float(torch.linalg.matrix_norm(m.weight.detach().double(), 2)) + return b + return lipschitz_bound(body) + + +def evaluate(model, X, y): + with torch.no_grad(): + logits = model(torch.tensor(X, device=device)) + L = bound(model[0]) + cert = certified_radius(logits, model[1].get_weight(), L) + correct = cert.pred == torch.as_tensor(y) + return L, cert, correct + + +learning_rates = {"head only": 1e-3, "butterfly": 1e-2, "LoRA": 1e-4, "full": 3e-5} +epochs = {"head only": 120, "butterfly": 120, "LoRA": 120, "full": 30} +radii = (0.25, 0.5, 1.0) +models, results, rows = {}, {}, [] +for strategy in strategies: + start = time.time() + model = fine_tune( + adapt(strategy), X_few, y_few, learning_rates[strategy], epochs[strategy] + ) + L, cert, correct = evaluate(model, X_test, y_test) + models[strategy] = model + results[strategy] = { + "L / L0": L / L0, + "accuracy": certified_accuracy(correct, cert.radius, 0), + "certified": [certified_accuracy(correct, cert.radius, e) for e in radii], + "radius": cert.radius[correct].numpy(), + } + rows.append( + { + "strategy": strategy, + "L / L0": f"{L / L0:.3g}", + "accuracy": results[strategy]["accuracy"], + **{ + f"certified at {e}": c + for e, c in zip(radii, results[strategy]["certified"]) + }, + "time, s": round(time.time() - start), + } + ) + +pd.DataFrame(rows) +``` + +| strategy | L / L0 | accuracy | certified at 0.25 | certified at 0.5 | certified at 1.0 | time, s | +|:---|---:|---:|---:|---:|---:|---:| +| head only | 1 | 0.701 | 0.587 | 0.465 | 0.265 | 2 | +| butterfly | 1 | 0.753 | 0.654 | 0.531 | 0.305 | 50 | +| LoRA | 48.6 | 0.685 | 0.000 | 0.000 | 0.000 | 18 | +| full | 10.4 | 0.703 | 0.274 | 0.045 | 0.000 | 2 | + +```python +with plt.rc_context(rc_params(theme="light")): + fig, axes = plt.subplots(1, 2, figsize=(11, 4), width_ratios=(1.3, 1)) + positions = np.arange(len(strategies)) + colors = [STYLE_COLORS[k] for k in (6, 2, 4, 0)] + axes[0].bar( + positions, + [results[s]["accuracy"] for s in strategies], + 0.6, + fill=False, + edgecolor=colors, + linewidth=1.5, + label="accuracy", + ) + axes[0].bar( + positions, + [results[s]["certified"][1] for s in strategies], + 0.6, + color=colors, + label=r"certified accuracy at $\varepsilon = 0.5$", + ) + for k, s in enumerate(strategies): + axes[0].text( + k, + results[s]["certified"][1] + 0.01, + f"{results[s]['certified'][1]:.2f}", + ha="center", + va="bottom", + ) + axes[0].set_xticks(positions, strategies) + axes[0].set_ylim(0, 0.85) + axes[0].legend(loc="upper right", fontsize=9) + axes[0].set_title("OrganCMNIST, 1,000 training labels") + grid = np.linspace(0, 1.5, 151) + for s, c in zip(strategies, colors): + radius = np.sort(results[s]["radius"]) + n_test = len(y_test) + axes[1].plot(grid, [(radius > e).sum() / n_test for e in grid], color=c, label=s) + axes[1].set_xlabel(r"radius $\varepsilon$") + axes[1].set_ylabel("certified accuracy") + axes[1].set_title("Certified accuracy against the radius") + axes[1].legend(fontsize=9) + fig.tight_layout() + plt.show() +``` + +![png](orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_5_0_light.png){ .theme-image-light } +![png](orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_5_0_dark.png){ .theme-image-dark } + +Butterfly is the most accurate strategy, 0.753 against 0.701 for the head alone, +0.685 for LoRA and 0.703 for full fine-tuning, which train more parameters. It +also certifies the most test images at every radius in the table, 0.531 at +\(\varepsilon = 0.5\) against 0.465 for the head alone. Butterfly and head only +keep \(L / L_0 = 1\), so their certificates mean what they meant before the +adaptation. + +LoRA and full fine-tuning raise the bound 49 and 10 times. Their accuracy is +close to that of the head alone, but at 0.5 they certify 0% and 4.5% of the test +images. The right panel shows the whole range of radii. The curve of LoRA falls +to zero before a radius of 0.2, and that of full fine-tuning before 0.8. +Butterfly stays above head only at every radius up to 1.5. + +## Where the guarantee goes + +The certificate of LoRA and of full fine-tuning is lost through \(L\), and \(L\) +is a product over the eight matrices. The next cell prints the largest +singular value of every adapted matrix: it is 1 for the pretrained network, and +it stays 1, to rounding, in every butterfly-adapted layer. + +```python +def adapted_matrices(body): + for m in body: + if isinstance(m, (nn.Linear, OrthogonalAdapter, LoRA)): + yield m.weight.detach().double() + + +pd.DataFrame( + { + strategy: [ + f"{float(torch.linalg.matrix_norm(w, 2)):.4g}" + for w in adapted_matrices(models[strategy][0]) + ] + for strategy in ("butterfly", "LoRA", "full") + }, + index=pd.Index(range(1, 9), name="layer"), +) +``` + +| layer | butterfly | LoRA | full | +|---:|---:|---:|---:| +| 1 | 1 | 1.24 | 1.165 | +| 2 | 1 | 1.246 | 1.259 | +| 3 | 1 | 1.327 | 1.31 | +| 4 | 1 | 1.497 | 1.372 | +| 5 | 1 | 1.564 | 1.393 | +| 6 | 1 | 1.778 | 1.411 | +| 7 | 1 | 2.396 | 1.412 | +| 8 | 1 | 2.376 | 1.415 | + +Every butterfly-adapted layer keeps the largest singular value of its +pretrained matrix, 1, to the four digits printed. LoRA raises it to between 1.24 +and 2.40 per layer, and full fine-tuning to between 1.17 and 1.42. Each factor is +modest, but they multiply: their products are the 48.6 and 10.4 of the table, +and every certified radius is divided by them. + +## With all the labels + +The comparison above uses 1,000 labels, a setting with few labels. The cell below +repeats it with all 12,975 training images of OrganCMNIST and the same learning +rates. The numbers of epochs were chosen on the validation split again, from +\(\{15, 30, 60\}\): 30 for the head and LoRA, 60 for butterfly and full +fine-tuning. + +```python +epochs_all_labels = {"head only": 30, "butterfly": 60, "LoRA": 30, "full": 60} +rows = [] +for strategy in strategies: + start = time.time() + model = fine_tune( + adapt(strategy), + *target["train"], + learning_rates[strategy], + epochs_all_labels[strategy], + ) + L, cert, correct = evaluate(model, X_test, y_test) + rows.append( + { + "strategy": strategy, + "L / L0": f"{L / L0:.3g}", + "accuracy": certified_accuracy(correct, cert.radius, 0), + "certified at 0.5": certified_accuracy(correct, cert.radius, 0.5), + "time, s": round(time.time() - start), + } + ) + +pd.DataFrame(rows) +``` + +| strategy | L / L0 | accuracy | certified at 0.5 | time, s | +|:---|---:|---:|---:|---:| +| head only | 1 | 0.743 | 0.511 | 5 | +| butterfly | 1 | 0.778 | 0.602 | 318 | +| LoRA | 171 | 0.741 | 0.000 | 29 | +| full | 181 | 0.812 | 0.000 | 42 | + +With all the labels, full fine-tuning is the most accurate strategy, 0.812 +against 0.778 for butterfly, but its bound grows 181 times and it certifies +nothing at 0.5; LoRA certifies nothing either. Butterfly keeps \(L_0\), is the +most accurate of the strategies that keep the certificate, and certifies 0.602 +of the test images, more than the 0.511 of the head alone. With more data an +unconstrained update finds a better accuracy, but only the orthogonal update +keeps a guarantee. + +## Takeaway + +A certified network adapted with butterfly adapters stays certified. Its bound is +exactly the pretrained one, by construction, so its certificates keep their +meaning. On OrganCMNIST with 1,000 labels, butterfly is both the most accurate +strategy and the one that certifies the most test images, with 52,235 trainable +parameters. LoRA and full fine-tuning train more parameters, reach a lower +accuracy, and lose the certificate through a bound that grows layer by layer. +With all the labels, full fine-tuning becomes more accurate by about 0.03, at +the price of every guarantee. + +## Citation + +This example follows *Quantum-inspired orthogonal adapters for certifiably robust +medical image classification* ([arXiv:2611.18775](https://arxiv.org/abs/2611.18775)), +which studies butterfly layers and butterfly adapters in certified classifiers of +medical images. The code of the paper is in +[eigenorbit/quantum-inspired-fine-tuning](https://github.com/eigenorbit/quantum-inspired-fine-tuning). +If you use these methods in your research, please cite the paper: + +```bibtex +@misc{tsurkan2026quantum, + title = {Quantum-inspired orthogonal adapters for certifiably robust medical image classification}, + author = {Tsurkan, Olga and Domingo, Laia and Orlova, Victoria and Sagingalieva, Asel and Zalaudek, Iris and Caposiena Caro, Raffaele Dante}, + year = {2026}, + eprint = {2611.18775}, + archivePrefix = {arXiv}, + primaryClass = {cs.CV}, + doi = {10.48550/arXiv.2611.18775}, + url = {https://arxiv.org/abs/2611.18775} +} +``` diff --git a/docs/examples/orthogonal-certified-training.md b/docs/examples/orthogonal-certified-training.md new file mode 100644 index 0000000..056b11c --- /dev/null +++ b/docs/examples/orthogonal-certified-training.md @@ -0,0 +1,507 @@ +--- +extras: [torch, viz, benchmark] +--- + +# Certified Classifier from Orthogonal Layers + +## Why a prediction needs more than accuracy + +A classifier is usually judged by one number: how often it is right on a test +set. For a model that is going to inform a real decision, that is not enough. A +model can be right on almost every test image and still change its answer when +the image changes by an amount nobody would notice — another camera, a +re-encoding, a handful of pixels. Accuracy on a fixed test set cannot see this, +because it only ever asks about the images in the set, never about the images +next to them. + +So there is a second question to ask of a prediction, next to whether it is +right: how much can the input change before the prediction changes? + +One way to answer it is to attack the model — search for a small change that +flips the prediction, and report the smallest one found. That is useful, but it +only bounds the robustness from above: a better search may find a smaller change +tomorrow, and the answer depends on the attack. The guarantee we want points the +other way. Around each image we want a radius inside which *no* change at all can +flip the prediction: not "no attack we tried succeeded", but "no attack can +succeed". A prediction that comes with such a radius is *certifiably robust*, and +the radius is a proof about the network, not the result of one search. + +This example builds classifiers whose predictions carry such a radius, where the +radius follows from the way the network is constructed rather than from anything +done to it after training. + +## The certificate + +Let \(h\) be the part of the network that maps the image to the features in front +of the last linear layer. The one thing the proof needs about \(h\) is how much it +can stretch a change of its input: a number \(L\) with + +\[ +\lVert h(x) - h(x') \rVert_2 \le L \, \lVert x - x' \rVert_2 \quad \text{for all } x, x'. +\] + +Such an \(L\) is a *Lipschitz bound* of \(h\). It is a worst case over every pair of +inputs and every direction, which is what makes it strong enough to prove +something rather than merely to describe the data at hand. + +The rest follows from the last layer. If the logits are +\(z_k = w_k^\top h(x) + b_k\) and \(p\) is the predicted class, class \(j\) can +overtake class \(p\) only by closing the gap \(z_p - z_j\), and a change \(\delta\) +of the image closes it by at most +\(L \lVert w_p - w_j \rVert \, \lVert \delta \rVert\). The prediction therefore +cannot change while \(\lVert \delta \rVert\) stays below the *certified radius* + +\[ +r(x) = \min_{j \ne p} \frac{z_p(x) - z_j(x)}{L \, \lVert w_p - w_j \rVert_2}. +\] + +The radius comes from one forward pass, with no attack and no sampling. Two +things have to hold for it to be worth anything. \(L\) must be small, and \(L\) of +a deep network is the product of the bounds of its layers, so every layer has to +be controlled. The margins \(z_p - z_j\) must also stay large — which, as the rest +of this example shows, is where networks built for a small \(L\) tend to fail. + +## What this example shows + +This example trains the same small network with three kinds of linear layer and +watches what happens to accuracy and to the certificate as the network gets +deeper: + +- **butterfly**: an orthogonal matrix built from RBS (Givens) rotations, the + classical form of a quantum orthogonal layer. Every singular value is exactly 1, + for every value of the angles; +- **dense-sn**: an ordinary dense matrix divided by its largest singular value + (spectral normalisation). Its largest singular value is 1, but the others are + free to be smaller; +- **dense**: an ordinary dense matrix with no constraint. + +All three are trained with the library's +[`GenericClassifier`](../user-guide/estimators.md), with the same loss, optimiser +and number of epochs. See the [user guide](../user-guide/orthogonal.md) for the +orthogonal modules and [Orthogonal networks](../algorithms/orthogonal-networks.md) +for the theory of RBS circuits. + +## The data + +[PneumoniaMNIST](https://medmnist.com/) (Yang et al., *Scientific Data* 10, 41, +2023) holds paediatric chest X-rays of \(28 \times 28\) pixels, labelled normal or +pneumonia: 4,708 training images and 624 test images. The file comes from the +MedMNIST record on Zenodo (CC BY 4.0) and is downloaded once, about 4 MB, into +`~/.cache/medmnist`. + +Every image is padded with zeros to \(32 \times 32\) and flattened into a vector of +1024 pixels in \([0, 1]\). The padding only adds zeros and the flattening only +reorders the pixels, so the distance between two images does not change: a +certificate for the vector is a certificate for the image. The width 1024 is a +power of two, which the butterfly layout needs. + +```python +import time +import urllib.request +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +from torch.nn.utils import parametrize + +from eigenkit import GenericClassifier +from eigenkit.datasets import STYLE_COLORS, rc_params +from eigenkit.orthogonal.torch import ( + LLNHead, + MaxMin, + Orthogonal, + certified_accuracy, + certified_radius, + lipschitz_bound, + sigma_max, +) + +URL = "https://zenodo.org/records/10519652/files/{}.npz?download=1" +FOLDER = Path.home() / ".cache" / "medmnist" + + +def load_medmnist(name): + """Images padded to 32 x 32 and flattened to 1024 values in [0, 1].""" + path = FOLDER / f"{name}.npz" + if not path.exists(): + FOLDER.mkdir(parents=True, exist_ok=True) + urllib.request.urlretrieve(URL.format(name), path) + out = {} + with np.load(path) as data: + for split in ("train", "test"): + images = data[f"{split}_images"].astype(np.float32) / 255 + images = np.pad(images, ((0, 0), (2, 2), (2, 2))) + out[split] = (images.reshape(len(images), -1), data[f"{split}_labels"][:, 0]) + return out + + +data = load_medmnist("pneumoniamnist") +X_train, y_train = data["train"] +X_test, y_test = data["test"] +device = "cuda" if torch.cuda.is_available() else "cpu" + +print(f"train {X_train.shape}, labels {np.bincount(y_train).tolist()}") +print(f"test {X_test.shape}, labels {np.bincount(y_test).tolist()}") +print(f"median norm of a test image: {np.median(np.linalg.norm(X_test, axis=1)):.1f}") +print(f"norm of a change of 1/255 in every one of the 784 pixels: {28 / 255:.2f}") +``` + +```text +train (4708, 1024), labels [1214, 3494] +test (624, 1024), labels [234, 390] +median norm of a test image: 16.6 +norm of a change of 1/255 in every one of the 784 pixels: 0.11 +``` + +The last two lines give a scale for the radii below. A radius of 0.5 is about 3% +of the norm of a typical image, or a change of about four grey levels in every +pixel at once. + +Here are six training images of each class, as the network receives them, +padding included: + +```python +classes = ("normal", "pneumonia") +with plt.rc_context(rc_params(theme="light")): + fig, axes = plt.subplots(2, 6, figsize=(9, 3.4)) + for label, row in zip((0, 1), axes): + for ax, i in zip(row, np.flatnonzero(y_train == label)[:6]): + ax.imshow(X_train[i].reshape(32, 32), cmap="gray", vmin=0, vmax=1) + ax.set_axis_off() + row[0].set_title(classes[label], loc="left", fontsize=11) + fig.tight_layout() + plt.show() +``` + +![png](orthogonal_certified_training_files/orthogonal_certified_training_1_0_light.png){ .theme-image-light } +![png](orthogonal_certified_training_files/orthogonal_certified_training_1_0_dark.png){ .theme-image-dark } + +## The network + +The network is a stack of \(D\) identical blocks, followed by a linear head: + +\[ +x \in \mathbb{R}^{1024} +\;\to\; \big[\, W_1 \to \mathrm{MaxMin} \,\big] +\;\to\; \cdots +\;\to\; \big[\, W_D \to \mathrm{MaxMin} \,\big] +\;\to\; \text{head} \;\to\; (z_0, z_1). +\] + +The matrices carry no bias and there is no normalisation layer. Only the \(W_i\) +change between the three variants. The other two pieces are the same in all of +them, and both are chosen so that they never stretch a change of their input. + +`MaxMin` splits the 1024 features into the 512 disjoint pairs +\((u_{2k}, u_{2k+1})\) and sorts each pair on its own, smaller value first: + +\[ +\mathrm{MaxMin}(u)_{2k} = \min(u_{2k},\, u_{2k+1}), \qquad +\mathrm{MaxMin}(u)_{2k+1} = \max(u_{2k},\, u_{2k+1}). +\] + +It either leaves a pair as it is or swaps its two entries, so on any given input +it is a permutation of the 1024 coordinates: it keeps the norm of its input and +is 1-Lipschitz (Anil, Lucas and Grosse, ICML 2019). *Which* permutation it +applies depends on the input, and that is what makes it non-linear. + +`LLNHead` is a linear head whose rows are normalised to unit length at every +call, so the distances \(\lVert w_p - w_j \rVert\) in the radius depend only on +the directions of the rows. + +Because `MaxMin` is 1-Lipschitz, each block contributes exactly the bound of its +matrix, and the bound of the features is their product, +\(L = \prod_{i=1}^{D} \sigma_{\max}(W_i)\); `lipschitz_bound` computes it for any +stack of these layers. For the butterfly variant \(L = 1\) by construction. For +dense-sn every factor is 1 too, through a parametrisation that divides the weight +by its largest singular value at every call (`sigma_max` computes it exactly). For +dense nothing holds \(L\) down. + +```python +class UnitSpectralNorm(nn.Module): + """Divide a weight by its largest singular value.""" + + def forward(self, weight): + return weight / sigma_max(weight) + + +def mixer(kind): + if kind == "butterfly": + return Orthogonal(1024, "butterfly") + layer = nn.Linear(1024, 1024, bias=False) + if kind == "dense-sn": + parametrize.register_parametrization(layer, "weight", UnitSpectralNorm()) + return layer + + +def make_network(kind, depth, n_classes=2): + blocks = [] + for _ in range(depth): + blocks += [mixer(kind), MaxMin()] + return nn.Sequential(*blocks, LLNHead(1024, n_classes)) + + +for kind in ("butterfly", "dense-sn", "dense"): + n = sum(p.numel() for p in mixer(kind).parameters()) + print(f"{kind:10s} {n:9,d} parameters per block") +``` + +```text +butterfly 5,120 parameters per block +dense-sn 1,048,576 parameters per block +dense 1,048,576 parameters per block +``` + +A butterfly on \(n = 1024\) wires has \(\log_2 n = 10\) layers of \(n/2 = 512\) +rotations, so \(5{,}120\) angles instead of the \(1{,}048{,}576\) entries of a dense +matrix. The angles start at zero, so an untrained butterfly block is the +identity. + +## Training + +Each network is trained by `GenericClassifier`, which wraps any `nn.Module` in the +`fit` / `predict` interface of scikit-learn and runs the standard training loop of +the library: Adam with a learning rate of \(10^{-3}\), batches of 128, the +cross-entropy loss, and 10 epochs, the same for every model. We train every +variant at depths 2, 8 and 32. The fitted network is `clf.model_`. The time +column of the output was measured on a GPU; on a CPU the deepest networks take +longest. + +After training we compute, on the 624 test images: + +- the accuracy; +- the bound \(L\) of the features, with `lipschitz_bound`; +- the certified radius of every image, with `certified_radius`, from the logits, + the normalised head weights and \(L\); +- the *certified accuracy* at radius \(\varepsilon\) with `certified_accuracy`: the + share of test images that are classified correctly *and* have + \(r(x) > \varepsilon\). It is the accuracy that is guaranteed against every change + of norm up to \(\varepsilon\), whatever its direction. + +```python +def certify(model, X, y): + """Logits, bound, certificate and correctness on a test set.""" + model.eval() + with torch.no_grad(): + logits = model(torch.tensor(X, device=device)) + L = lipschitz_bound(model[:-1]) # every block, without the head + cert = certified_radius(logits, model[-1].get_weight(), L) + correct = cert.pred == torch.as_tensor(y) + return L, cert, correct + + +depths = (2, 8, 32) +kinds = ("butterfly", "dense-sn", "dense") +radii = (0.25, 0.5, 1.0) +models, results, rows = {}, {}, [] +for depth in depths: + for kind in kinds: + start = time.time() + torch.manual_seed(0) # the dense weights are drawn when the network is built + clf = GenericClassifier( + make_network(kind, depth).to(device), + in_features=1024, + lr=1e-3, + epochs=10, + batch_size=128, + show_progress=False, + random_state=0, + ) + clf.fit(X_train, y_train) + L, cert, correct = certify(clf.model_, X_test, y_test) + models[kind, depth] = clf.model_ + results[kind, depth] = { + "L": L, + "accuracy": certified_accuracy(correct, cert.radius, 0), + "certified": [certified_accuracy(correct, cert.radius, e) for e in radii], + } + rows.append( + { + "depth": depth, + "mixer": kind, + "L": f"{L:.3g}", + "accuracy": results[kind, depth]["accuracy"], + **{ + f"certified at {e}": c + for e, c in zip(radii, results[kind, depth]["certified"]) + }, + "time, s": round(time.time() - start), + } + ) + +pd.DataFrame(rows) +``` + +| depth | mixer | L | accuracy | certified at 0.25 | certified at 0.5 | certified at 1.0 | time, s | +|---:|:---|---:|---:|---:|---:|---:|---:| +| 2 | butterfly | 1 | 0.853 | 0.772 | 0.675 | 0.426 | 9 | +| 2 | dense-sn | 1 | 0.822 | 0.763 | 0.663 | 0.460 | 12 | +| 2 | dense | 9.44 | 0.830 | 0.673 | 0.458 | 0.043 | 1 | +| 8 | butterfly | 1 | 0.854 | 0.769 | 0.683 | 0.421 | 25 | +| 8 | dense-sn | 1 | 0.822 | 0.590 | 0.551 | 0.417 | 47 | +| 8 | dense | 2.27e+03 | 0.771 | 0.000 | 0.000 | 0.000 | 3 | +| 32 | butterfly | 1 | 0.790 | 0.708 | 0.657 | 0.527 | 82 | +| 32 | dense-sn | 1 | 0.625 | 0.625 | 0.000 | 0.000 | 188 | +| 32 | dense | 8.15e+20 | 0.625 | 0.000 | 0.000 | 0.000 | 12 | + +```python +with plt.rc_context(rc_params(theme="light")): + fig, axes = plt.subplots(1, 3, figsize=(12, 3.8)) + lines = {"butterfly": ("o", "-"), "dense-sn": ("s", "--"), "dense": ("^", ":")} + for k, kind in enumerate(kinds): + marker, linestyle = lines[kind] + style = dict( + marker=marker, linestyle=linestyle, color=STYLE_COLORS[2 * k], label=kind + ) + axes[0].plot(depths, [results[kind, d]["accuracy"] for d in depths], **style) + axes[1].plot(depths, [results[kind, d]["certified"][1] for d in depths], **style) + axes[2].plot(depths, [results[kind, d]["L"] for d in depths], **style) + majority = np.bincount(y_test).max() / len(y_test) + axes[0].axhline(majority, color="grey", linestyle=":", label="always 'pneumonia'") + axes[0].set_title("Accuracy") + axes[1].set_title(r"Certified accuracy at $\varepsilon = 0.5$") + axes[2].set_title("Bound $L$ of the features") + axes[2].set_yscale("log") + for ax in axes: + ax.set_xscale("log", base=2) + ax.set_xticks(depths, [str(d) for d in depths]) + ax.set_xlabel("depth $D$") + axes[0].set_ylim(0.3, 0.9) + axes[1].set_ylim(-0.03, 0.8) + handles, labels = axes[0].get_legend_handles_labels() + fig.legend(handles, labels, loc="upper center", ncol=4) + fig.tight_layout(rect=(0, 0, 1, 0.88)) + plt.show() +``` + +![png](orthogonal_certified_training_files/orthogonal_certified_training_4_0_light.png){ .theme-image-light } +![png](orthogonal_certified_training_files/orthogonal_certified_training_4_0_dark.png){ .theme-image-dark } + +At depth 2 the three variants are close. Their accuracy is 0.82 to 0.85, and the +two constrained ones certify about two thirds of the test images at +\(\varepsilon = 0.5\). The unconstrained network already has \(L \approx 9\), which +divides every radius by 9, and it certifies less, 0.458. + +With depth they part ways. The bound of the dense network grows with every +layer, to \(2.3 \cdot 10^{3}\) at depth 8 and \(8 \cdot 10^{20}\) at depth 32. At depth +8 its predictions are still often right, 0.771, but not one of them is certified +at any radius in the table. Spectral normalisation keeps \(L = 1\), but at depth 32 +the network answers "pneumonia" for every image: its accuracy, 0.625, is the share +of that class in the test set, and it certifies nothing at 0.5. The butterfly +network keeps \(L = 1\) at every depth and still certifies 0.657 of the test images +at depth 32, almost as many as at depth 2. Its accuracy goes down from 0.853 to +0.790 with the same 10 epochs, but it never collapses to one class. + +## Why spectral normalisation fails at depth + +Both constrained variants have \(L = 1\), so the difference between them is not in +the bound. It is in what the layers do to the signal. A layer with +\(\sigma_{\max} = 1\) cannot enlarge any input, but if its other singular values +are smaller than one it shrinks the inputs along those directions, and a stack of +such layers shrinks them again and again. The logits are then small, and so are +the margins \(z_p - z_j\) that the radius is made of. An orthogonal layer keeps +the norm of every input, \(\lVert Wx \rVert = \lVert x \rVert\), and `MaxMin` keeps it +too, so the features of the butterfly network have exactly the norm of the image, +at any depth. + +The next cell measures this: the median of \(\lVert h(x) \rVert / \lVert x \rVert\) over +the test images, and the smallest singular value of the matrices of each +network. + +```python +def norm_kept(model, X): + with torch.no_grad(): + x = torch.tensor(X, device=device) + h = model[:-1](x) + return float((h.norm(dim=1) / x.norm(dim=1)).median()) + + +def smallest_singular_value(model): + """The smallest singular value over the matrices of a network.""" + values = [] + for layer in model[:-1]: + if isinstance(layer, nn.Linear): + weight = layer.weight + elif isinstance(layer, Orthogonal): + weight = layer.matrix() # a butterfly builds its matrix from the angles + else: + continue # MaxMin has no matrix + values.append(torch.linalg.svdvals(weight.detach().double()).min()) + return float(min(values)) + + +pd.DataFrame( + [ + { + "depth": depth, + "mixer": kind, + "‖h(x)‖ / ‖x‖": f"{norm_kept(models[kind, depth], X_test):.4f}", + "smallest singular value": f"{smallest_singular_value(models[kind, depth]):.2e}", + } + for depth in depths + for kind in ("butterfly", "dense-sn") + ] +) +``` + +| depth | mixer | ‖h(x)‖ / ‖x‖ | smallest singular value | +|---:|:---|---:|---:| +| 2 | butterfly | 1.0000 | 1.00e+00 | +| 2 | dense-sn | 0.0988 | 3.51e-05 | +| 8 | butterfly | 1.0000 | 1.00e+00 | +| 8 | dense-sn | 0.0644 | 1.99e-05 | +| 32 | butterfly | 1.0000 | 1.00e+00 | +| 32 | dense-sn | 0.0000 | 1.04e-06 | + +The butterfly networks keep the norm of every image exactly, and the smallest +singular value of their matrices is 1; since \(L = 1\) bounds the largest, every +singular value is 1. The dense-sn networks have singular values down to +\(10^{-5}\) even at depth 2, and their features keep about 10% of the norm of the +image at depth 2, 6% at depth 8, and nothing measurable at depth 32. With unit +rows in the head, the gap between two logits is at most +\(\lVert w_p - w_j \rVert \, \lVert h(x) \rVert\) plus the difference of the biases. +When \(h(x)\) is almost zero, only the biases are left: they pick one class for +every image, and the margin no longer depends on the image at all. That is the +collapse in the plot. A bound \(L = 1\) is therefore not enough. The layers must +also not lose the signal, and orthogonal layers are the linear layers that lose +none. + +## Takeaway + +On PneumoniaMNIST, a network built from butterfly layers keeps its Lipschitz +bound at exactly 1 and keeps the norm of the signal through 32 layers. It +certifies about two thirds of the test images at a radius of 0.5 at every depth +we tried. A dense network of the same shape loses its certificate as its bound +grows. A spectrally normalised one keeps the bound but loses the signal, and at +depth 32 it predicts one class. Each butterfly layer has 5,120 parameters instead +of more than a million, and the whole network is trained with +`GenericClassifier` like any other model of the library. + +The next example, [Certified Fine-Tuning with Butterfly +Adapters](orthogonal-certified-fine-tuning.md), starts from such a network and +adapts it to a new task without losing the certificate. + +## Citation + +This example follows *Quantum-inspired orthogonal adapters for certifiably robust +medical image classification* ([arXiv:2611.18775](https://arxiv.org/abs/2611.18775)), +which studies butterfly layers and butterfly adapters in certified classifiers of +medical images. The code of the paper is in +[eigenorbit/quantum-inspired-fine-tuning](https://github.com/eigenorbit/quantum-inspired-fine-tuning). +If you use these methods in your research, please cite the paper: + +```bibtex +@misc{tsurkan2026quantum, + title = {Quantum-inspired orthogonal adapters for certifiably robust medical image classification}, + author = {Tsurkan, Olga and Domingo, Laia and Orlova, Victoria and Sagingalieva, Asel and Zalaudek, Iris and Caposiena Caro, Raffaele Dante}, + year = {2026}, + eprint = {2611.18775}, + archivePrefix = {arXiv}, + primaryClass = {cs.CV}, + doi = {10.48550/arXiv.2611.18775}, + url = {https://arxiv.org/abs/2611.18775} +} +``` diff --git a/docs/examples/orthogonal-qnn-classifier.md b/docs/examples/orthogonal-qnn-classifier.md new file mode 100644 index 0000000..d1352cc --- /dev/null +++ b/docs/examples/orthogonal-qnn-classifier.md @@ -0,0 +1,489 @@ +--- +extras: [torch, pennylane, viz] +--- + +# Orthogonal QNN as a Compact Classifier + +## What this example shows + +A quantum orthogonal neural network (Landman et al., *Quantum* 6, 881, 2022) +classifies data with three parts: + +1. a **unary loader** puts the input \(x \in \mathbb{R}^n\) into the amplitudes of + \(n\) qubits, one amplitude per qubit: + \(\lvert x \rangle = \sum_i \frac{x_i}{\lVert x \rVert} \lvert e_i \rangle\), where + \(\lvert e_i \rangle\) has a single 1 on qubit \(i\); +2. a network of **RBS gates** rotates the state. RBS gates keep the number of 1s + fixed, so the state stays a combination of the \(n\) unary states, and the + network acts on its amplitudes as an \(n \times n\) orthogonal matrix \(W\); +3. a **measurement** finds the single 1 on qubit \(i\) with probability + \(p_i = (Wx)_i^2 / \lVert x \rVert^2\). The \(p_i\) are a probability distribution + over the qubits by construction. + +This example uses such a network as a binary classifier on medical images, and +compares it with three other models that see the same inputs: logistic +regression, a small classical network (MLP) and the variational quantum +classifier of the library, `HQNC`. Every model is trained by an estimator of the +library: `GenericClassifier` for the classical models and the orthogonal network, +`HQNC` for the variational one. See [Orthogonal +networks](../algorithms/orthogonal-networks.md) for the theory of RBS circuits and +the [user guide](../user-guide/orthogonal.md#from-trained-angles-to-a-circuit) for +exporting trained angles to a circuit. + +## The data + +[PneumoniaMNIST](https://medmnist.com/) (Yang et al., *Scientific Data* 10, 41, +2023) holds paediatric chest X-rays of \(28 \times 28\) pixels, labelled normal or +pneumonia: 4,708 training images and 624 test images. The file comes from the +MedMNIST record on Zenodo (CC BY 4.0) and is downloaded once, about 4 MB, into +`~/.cache/medmnist`. + +A circuit of 8 qubits loads 8 numbers, so every image is reduced to 8 features +by a principal component analysis (PCA) fitted on the training images. Every +feature is then scaled to \([0, 1]\) over the training set, and test values are +clipped to stay non-negative. + +The scaling matters for the orthogonal network. The loader keeps only the +direction \(x / \lVert x \rVert\), and the measurement returns squares +\((Wx)_i^2\), so the network cannot tell \(x\) from \(-x\). Centred PCA features +carry much of the class in their signs, which would be lost. On \([0, 1]\) every +feature is non-negative, and the direction keeps what the classes need. `HQNC` +scales its inputs to \([0, 1]\) by itself, so all models see the same values. + +```python +import time +import urllib.request +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +import torch +import torch.nn as nn +from sklearn.decomposition import PCA +from sklearn.metrics import roc_auc_score +from sklearn.preprocessing import MinMaxScaler + +from eigenkit import HQNC, Circuit, GenericClassifier, OrthogonalQNN, PennyLaneConfig +from eigenkit.datasets import STYLE_COLORS, rc_params +from eigenkit.orthogonal import Topology, to_block, topology +from eigenkit.orthogonal.torch import Orthogonal + +URL = "https://zenodo.org/records/10519652/files/{}.npz?download=1" +FOLDER = Path.home() / ".cache" / "medmnist" + + +def load_medmnist(name): + path = FOLDER / f"{name}.npz" + if not path.exists(): + FOLDER.mkdir(parents=True, exist_ok=True) + urllib.request.urlretrieve(URL.format(name), path) + with np.load(path) as data: + return { + split: ( + data[f"{split}_images"].reshape(len(data[f"{split}_images"]), -1) / 255, + data[f"{split}_labels"][:, 0], + ) + for split in ("train", "test") + } + + +data = load_medmnist("pneumoniamnist") +images_train, y_train = data["train"] +images_test, y_test = data["test"] + +n = 8 +pca = PCA(n_components=n, random_state=0).fit(images_train) +scaler = MinMaxScaler().fit(pca.transform(images_train)) +X_train = scaler.transform(pca.transform(images_train)).astype(np.float32) +X_test = np.clip(scaler.transform(pca.transform(images_test)), 0, None).astype(np.float32) + +print(f"train {X_train.shape}, labels {np.bincount(y_train).tolist()}") +print(f"test {X_test.shape}, labels {np.bincount(y_test).tolist()}") +``` + +```text +train (4708, 8), labels [1214, 3494] +test (624, 8), labels [234, 390] +``` + +The images below are six training X-rays of each class (top), and the same +images rebuilt from their 8 principal components alone (bottom). The 8 numbers +keep the overall shape and brightness of the chest, not its details; this is all +that every model of the example sees. + +```python +classes = ("normal", "pneumonia") +shown = np.concatenate([np.flatnonzero(y_train == c)[:3] for c in (0, 1)]) +rebuilt = pca.inverse_transform(pca.transform(images_train[shown])) +with plt.rc_context(rc_params(theme="light")): + fig, axes = plt.subplots(2, 6, figsize=(9, 3.6)) + for k, i in enumerate(shown): + axes[0, k].imshow(images_train[i].reshape(28, 28), cmap="gray", vmin=0, vmax=1) + axes[1, k].imshow(rebuilt[k].reshape(28, 28), cmap="gray", vmin=0, vmax=1) + axes[0, k].set_title(classes[y_train[i]], fontsize=10) + for ax in axes.flat: + ax.set_axis_off() + fig.tight_layout() + plt.show() +``` + +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_1_0_light.png){ .theme-image-light } +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_1_0_dark.png){ .theme-image-dark } + +## The orthogonal classifier + +With \(n = 8\) qubits and two classes, the class is read from the two halves of +the qubits: + +\[ +P(\text{pneumonia} \mid x) = \sum_{i=4}^{7} p_i = \sum_{i=4}^{7} \frac{(Wx)_i^2}{\lVert x \rVert^2}, +\] + +so every measurement of the circuit is one vote for a class. + +The circuit computes exactly \((Wx)_i^2 / \lVert x \rVert^2\), so the network can be +trained in this *matrix form*: the module `Orthogonal` holds the angles of the RBS +gates and builds \(W\) from them. Training then works with an \(8 \times 8\) matrix +instead of simulating the \(2^8 = 256\) amplitudes of the circuit, and the trained +angles are copied into the circuit afterwards. + +The probability has no bias, and the classes are not balanced: 74% of the +training images show pneumonia. Two classical numbers, a scale \(a\) and an offset +\(b\), turn the probability into the logit that the cross-entropy needs, +\(z = a \, (P - \tfrac{1}{2}) + b\). They only move and sharpen the decision +threshold on \(P\); the ranking of the images, and so the AUC, comes from the +circuit alone. + +We use two layouts of the RBS gates on 8 qubits: the **butterfly**, 12 gates in +3 layers, and the **pyramid**, 28 gates, which connects every pair of qubits and +is the layout of Landman et al. + +Both are drawn below. Each link joins the two qubits that one RBS gate acts on, +and the gates in a column act at the same time, so the number of columns is the +depth of the circuit. The butterfly pairs qubits at distance 1, then 2, then 4, +which is why 3 layers reach every qubit from every other. The pyramid walks a +single pair across the register and back. The bottom panel is what one of those +links becomes on hardware. + +```python +def draw_layout(ax, name, title): + """The RBS gates of a topology: one line per qubit, one link per gate. + + Gates of the same layer act at the same time; they are drawn a little apart + so that links which span the same wires stay readable. + """ + layers = topology(name, n).layers + width = len(layers) - 0.4 + for q in range(n): + ax.plot([-0.45, width], [q, q], color=STYLE_COLORS[7], lw=1, zorder=0) + ax.text(-0.65, q, f"$q_{q}$", ha="right", va="center", fontsize=9) + for depth, layer in enumerate(layers): + spread = 0.13 * (len(layer) - 1) + for k, (a, b) in enumerate(sorted(layer)): + x = depth - spread / 2 + 0.13 * k if len(layer) > 1 else depth + ax.plot([x, x], [a, b], color=STYLE_COLORS[2], lw=2.2, zorder=1) + ax.plot([x, x], [a, b], "o", color=STYLE_COLORS[2], ms=5.5, zorder=2) + gates = sum(len(layer) for layer in layers) + ax.set_title(f"{title} — {gates} RBS gates in {len(layers)} layers", fontsize=10) + ax.set_xlim(-1.1, width + 0.2) + ax.set_ylim(n - 0.4, -0.9) + ax.set_axis_off() + + +with plt.rc_context(rc_params(theme="light")): + fig, axes = plt.subplots(3, 1, figsize=(9.5, 8.0), height_ratios=(1.1, 1.1, 0.8)) + draw_layout(axes[0], "butterfly", "butterfly") + draw_layout(axes[1], "pyramid", "pyramid") + one_gate = Circuit([to_block(Topology(2, (((0, 1),),)), [0.3])]) + one_gate.draw_mpl(style="eigen-universal", ax=axes[2]) + axes[2].set_title("one RBS gate, as a backend runs it", fontsize=10) + fig.tight_layout() + plt.show() +``` + +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_2_0_light.png){ .theme-image-light } +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_2_0_dark.png){ .theme-image-dark } + +```python +class OrthogonalClassifier(nn.Module): + """P(class 1) from the second half of the qubits, then a scale and an offset.""" + + def __init__(self, n, topology): + super().__init__() + self.n = n + self.rotation = Orthogonal(n, topology, init="random", std=1.0) + self.scale = nn.Parameter(torch.tensor(4.0)) + self.offset = nn.Parameter(torch.tensor(0.0)) + + def probability(self, x): + p = self.rotation(x) ** 2 / (x**2).sum(dim=1, keepdim=True).clamp_min(1e-12) + return p[:, self.n // 2 :].sum(dim=1) + + def forward(self, x): + z = self.scale * (self.probability(x) - 0.5) + self.offset + return torch.stack([-z / 2, z / 2], dim=1) + + +def make(name, seed): + common = dict( + epochs=30, batch_size=64, lr=0.02, show_progress=False, random_state=seed + ) + if name == "logistic regression": + return GenericClassifier(nn.Linear(n, 2), in_features=n, **common) + if name == "MLP [8, 4, 2]": + mlp = nn.Sequential(nn.Linear(n, 4), nn.Sigmoid(), nn.Linear(4, 2)) + return GenericClassifier(mlp, in_features=n, **common) + if name == "HQNC": + return HQNC(in_features=n, n_qubits=n, depth=2, n_classes=2, **common) + topology = name.split()[1] + return GenericClassifier(OrthogonalClassifier(n, topology), in_features=n, **common) + + +names = ( + "logistic regression", + "MLP [8, 4, 2]", + "HQNC", + "orthogonal butterfly", + "orthogonal pyramid", +) +``` + +## Size of every model + +The next cell counts the trainable parameters of every model and, for the quantum +ones, the gates of the circuit. Each RBS gate is compiled to two CNOTs, and the +loader adds \(n - 1 = 7\) more RBS gates. The butterfly uses the parallel loader, +which needs a power of two and is 3 layers deep; the pyramid uses the diagonal +loader, which works for any \(n\). + +```python +def count(model): + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + +probe = HQNC( + in_features=n, n_qubits=n, depth=2, n_classes=2, epochs=1, show_progress=False +) +probe.fit(X_train[:8], np.arange(8) % 2) +circuits = { + "HQNC": probe.model_[1].circuit.spec, + "orthogonal butterfly": OrthogonalQNN(n, "butterfly", loader="parallel").circuit.spec, + "orthogonal pyramid": OrthogonalQNN(n, "pyramid", loader="diagonal").circuit.spec, +} +print("model parameters gates CNOTs") +for name in names: + if name == "HQNC": + size = count(probe.model_) + else: + size = count(make(name, 0).model) + spec = circuits.get(name) + gates = ( + f"{len(spec.gates):6d} {sum(g.name == 'CNOT' for g in spec.gates):6d}" + if spec + else " - -" + ) + print(f"{name:22s} {size:10d} {gates}") +``` + +```text +model parameters gates CNOTs +logistic regression 18 - - +MLP [8, 4, 2] 46 - - +HQNC 34 38 14 +orthogonal butterfly 14 153 38 +orthogonal pyramid 30 281 70 +``` + +The orthogonal butterfly is the smallest model: 12 angles, plus the scale and +the offset. The pyramid has 28 angles, the variational classifier `HQNC` has 16 +circuit weights and a linear layer of 18 after the circuit, and the MLP has 46 +weights. In gates the order is reversed. Every RBS gate is compiled into two +CNOTs and single-qubit rotations, and the loader adds its own RBS gates, so the +orthogonal circuits are deeper than the circuit of `HQNC`. The butterfly needs +about half the CNOTs of the pyramid. + +`HQNC` builds a circuit of a different kind. It writes each of the 8 features +into the angle of an `RX` rotation, follows them with trainable `RY` rotations +and a ladder of CNOTs, and measures every qubit; a linear layer then turns those +expectations into the two logits. + +```python +with plt.rc_context(rc_params(theme="light")): + fig, ax = plt.subplots(figsize=(11, 4.2)) + probe.model_[1].circuit.draw_mpl(style="eigen-universal", ax=ax) + ax.set_title("HQNC — two variational layers on 8 qubits", fontsize=10) + fig.tight_layout() + plt.show() +``` + +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_5_0_light.png){ .theme-image-light } +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_5_0_dark.png){ .theme-image-dark } + +The encoded features (`x_0` to `x_7`) and the 16 trainable weights (`w_0` to +`w_15`) are visible in the boxes. Nothing here keeps the number of 1s fixed, so +the state leaves the unary subspace and the circuit has to be simulated over all +\(2^8\) amplitudes, which is why it is the slowest model to train. + +## Training and results + +Every model is trained with the same settings: Adam with a learning rate of +0.02, batches of 64, 30 epochs, cross-entropy, and three seeds. We report the +area under the ROC curve (AUC), which measures how well the model ranks the +images, and the accuracy, on the test set, after the last epoch. + +```python +results, fitted = {}, {} +for name in names: + start = time.time() + scores = [] + for seed in range(3): + clf = make(name, seed).fit(X_train, y_train) + probability = clf.predict_proba(X_test)[:, 1] + scores.append( + (roc_auc_score(y_test, probability), (clf.predict(X_test) == y_test).mean()) + ) + fitted[name, seed] = clf + results[name] = np.array(scores) + seconds = (time.time() - start) / 3 + auc, acc = results[name].mean(axis=0) + auc_sd, acc_sd = results[name].std(axis=0) + print( + f"{name:22s} AUC {auc:.3f} ± {auc_sd:.3f} accuracy {acc:.3f} ± {acc_sd:.3f}" + f" {seconds:5.0f} s per fit" + ) +``` + +```text +logistic regression AUC 0.887 ± 0.000 accuracy 0.796 ± 0.003 2 s per fit +MLP [8, 4, 2] AUC 0.889 ± 0.001 accuracy 0.781 ± 0.010 3 s per fit +HQNC AUC 0.908 ± 0.006 accuracy 0.823 ± 0.017 180 s per fit +orthogonal butterfly AUC 0.886 ± 0.001 accuracy 0.800 ± 0.011 5 s per fit +orthogonal pyramid AUC 0.894 ± 0.008 accuracy 0.818 ± 0.016 11 s per fit +``` + +```python +with plt.rc_context(rc_params(theme="light")): + fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) + positions = np.arange(len(names)) + colors = [STYLE_COLORS[k] for k in (6, 4, 0, 2, 3)] + for ax, column, title in zip(axes, (0, 1), ("Test AUC", "Test accuracy")): + means = [results[name][:, column].mean() for name in names] + errors = [results[name][:, column].std() for name in names] + ax.bar(positions, means, 0.6, yerr=errors, capsize=3, color=colors) + for k, (m, e) in enumerate(zip(means, errors)): + ax.text(k, m + e + 0.006, f"{m:.3f}", ha="center", va="bottom", fontsize=9) + ax.set_xticks( + positions, [name.replace(" ", "\n", 1) for name in names], fontsize=9 + ) + ax.set_ylim(0.6, 0.97) + ax.set_title(title) + fig.tight_layout() + plt.show() +``` + +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_7_0_light.png){ .theme-image-light } +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_7_0_dark.png){ .theme-image-dark } + +The orthogonal pyramid ranks the images better than the two classical models, +with an AUC of 0.894 against 0.887 and 0.889. It is also more accurate, 0.818 +against 0.796 and 0.781. The butterfly matches logistic regression, AUC 0.886 +and accuracy 0.800 against 0.887 and 0.796, with 14 parameters, fewer than any +other model. + +`HQNC` is the best model here, with an AUC of 0.908 and an accuracy of 0.823. Its +accuracy is that of the pyramid within the spread over the seeds (±0.017 and +±0.016). It is also the most expensive to train: minutes per fit, against seconds for +the orthogonal networks (the last column; the times depend on the machine). +`HQNC` is trained by simulating its circuit, while the orthogonal network is +trained in its matrix form, which gives the output of the circuit exactly +without simulating the quantum state. + +## From infinite shots to a real device + +The orthogonal networks were trained in their matrix form, which returns +\((Wx)_i^2 / \lVert x \rVert^2\) exactly. Those are the probabilities a circuit +would give if every image were measured infinitely many times. A real device +returns samples instead. Each shot of the orthogonal circuit finds the single 1 +on one qubit, and the share of shots that land on the second half of the qubits +estimates \(P(\text{pneumonia})\). + +The cell below copies the trained angles of the pyramid of seed 0 into +`OrthogonalQNN`, runs it on PennyLane's simulator with a finite number of shots, +which samples as a noiseless device would, and applies the same scale and offset. +The dashed line is the exact probability, the infinite-shot limit that the matrix +form computes. + +```python +def with_shots(model, shots): + """AUC and accuracy when P is estimated from a finite number of shots.""" + config = PennyLaneConfig(device_name="default.qubit", shots=shots) + sampled = OrthogonalQNN(n, "pyramid", loader="diagonal", provider=config) + with torch.no_grad(): + sampled.circuit.weights.copy_(model.rotation.theta.double()) + p = sampled(torch.tensor(X_test, dtype=torch.float64))[:, n // 2 :].sum(dim=1) + z = model.scale * (p.float() - 0.5) + model.offset + predictions = (z > 0).numpy().astype(int) + return roc_auc_score(y_test, p.numpy()), (predictions == y_test).mean() + + +model = fitted["orthogonal pyramid", 0].model_ +exact = results["orthogonal pyramid"][0] +np.random.seed(0) # PennyLane's default.qubit samples from NumPy's global generator +shot_counts = (10, 30, 100, 300, 1000, 3000) +measured = np.array([with_shots(model, s) for s in shot_counts]) + +with plt.rc_context(rc_params(theme="light")): + fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) + for ax, column, title, value in zip( + axes, (0, 1), ("Test AUC", "Test accuracy"), exact + ): + ax.axhline( + value, color=STYLE_COLORS[7], linestyle="--", label="exact (infinite shots)" + ) + ax.plot( + shot_counts, + measured[:, column], + marker="o", + color=STYLE_COLORS[2], + label="sampled", + ) + ax.set_xscale("log") + ax.set_xticks(shot_counts, [str(s) for s in shot_counts]) + ax.set_xlabel("shots per image") + ax.set_title(title) + axes[0].legend(fontsize=9, loc="lower right") + fig.tight_layout() + plt.show() +``` + +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_8_0_light.png){ .theme-image-light } +![png](orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_8_0_dark.png){ .theme-image-dark } + +Both curves climb towards the dashed line and are close to it by a thousand +shots: an AUC of 0.888 and an accuracy of 0.793, against 0.895 and 0.806 exactly, +and 0.893 and 0.800 with three thousand. Below a hundred shots the estimate of +\(P\) is too noisy for the images near the threshold, and both fall away quickly +— at ten shots the AUC is 0.727. + +That the curves converge to the dashed line is also the check that the circuit +computes what was trained: the matrix form and the sampled circuit agree once +enough shots are taken, so training on the matrix and running on a device are the +same model. The shots are random, and `np.random.seed(0)` fixes them because +PennyLane's `default.qubit` draws its samples from NumPy's global generator; +another seed moves the points slightly. Each shot is a vote for one class, so how +many are needed depends on how close \(P\) is to the threshold, not on the number +of qubits. + +## Takeaway + +On PneumoniaMNIST reduced to 8 features, an orthogonal network of RBS gates, +trained with `GenericClassifier` like any other model, is as good as or better +than logistic regression and an MLP with the same inputs. It needs only 14 to 30 +parameters. The pyramid reaches the accuracy of the variational classifier +`HQNC` within the spread over the seeds, in a fraction of its training time, +because its matrix form gives the output of the circuit exactly, without +simulating the quantum state. Its output is a probability distribution over the +qubits by construction, so each shot is a vote for a class: measured on a +simulator, 1,000 shots per image come within about 0.01 of the exact AUC and +accuracy, and 3,000 within 0.006. The price is the depth of the circuit: 38 to +70 CNOTs against 14 for `HQNC`. diff --git a/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_1_0_dark.png b/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_1_0_dark.png new file mode 100644 index 0000000..279f604 Binary files /dev/null and b/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_1_0_dark.png differ diff --git a/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_1_0_light.png b/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_1_0_light.png new file mode 100644 index 0000000..86a0ebe Binary files /dev/null and b/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_1_0_light.png differ diff --git a/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_5_0_dark.png b/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_5_0_dark.png new file mode 100644 index 0000000..2a892e7 Binary files /dev/null and b/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_5_0_dark.png differ diff --git a/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_5_0_light.png b/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_5_0_light.png new file mode 100644 index 0000000..eeb58b5 Binary files /dev/null and b/docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_5_0_light.png differ diff --git a/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_1_0_dark.png b/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_1_0_dark.png new file mode 100644 index 0000000..5759904 Binary files /dev/null and b/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_1_0_dark.png differ diff --git a/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_1_0_light.png b/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_1_0_light.png new file mode 100644 index 0000000..a91cb79 Binary files /dev/null and b/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_1_0_light.png differ diff --git a/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_4_0_dark.png b/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_4_0_dark.png new file mode 100644 index 0000000..3489e23 Binary files /dev/null and b/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_4_0_dark.png differ diff --git a/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_4_0_light.png b/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_4_0_light.png new file mode 100644 index 0000000..cff9cf9 Binary files /dev/null and b/docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_4_0_light.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_1_0_dark.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_1_0_dark.png new file mode 100644 index 0000000..ba95a96 Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_1_0_dark.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_1_0_light.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_1_0_light.png new file mode 100644 index 0000000..1a34b4f Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_1_0_light.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_2_0_dark.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_2_0_dark.png new file mode 100644 index 0000000..e757198 Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_2_0_dark.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_2_0_light.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_2_0_light.png new file mode 100644 index 0000000..539870c Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_2_0_light.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_5_0_dark.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_5_0_dark.png new file mode 100644 index 0000000..65b4006 Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_5_0_dark.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_5_0_light.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_5_0_light.png new file mode 100644 index 0000000..cc36775 Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_5_0_light.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_7_0_dark.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_7_0_dark.png new file mode 100644 index 0000000..bc3df06 Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_7_0_dark.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_7_0_light.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_7_0_light.png new file mode 100644 index 0000000..eea9222 Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_7_0_light.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_8_0_dark.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_8_0_dark.png new file mode 100644 index 0000000..fe45005 Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_8_0_dark.png differ diff --git a/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_8_0_light.png b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_8_0_light.png new file mode 100644 index 0000000..9f73fca Binary files /dev/null and b/docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_8_0_light.png differ diff --git a/docs/user-guide/layers.md b/docs/user-guide/layers.md index ddbf840..02507ca 100644 --- a/docs/user-guide/layers.md +++ b/docs/user-guide/layers.md @@ -172,7 +172,9 @@ load, so it gives the uniform distribution \(1/n\) on all \(n\) qubits, and no gradient flows back to it; the other rows of the batch are not affected. The circuit simulates \(2^n\) amplitudes, so the layer is practical up to about 20 qubits; `eigenkit.orthogonal.torch.Orthogonal` computes the same matrix classically at any -width. +width. The [orthogonal QNN classifier](../examples/orthogonal-qnn-classifier.md) +trains the matrix classically, runs it as a circuit, and compares it +with classical networks and `HQNC` on PneumoniaMNIST. ## `MinMaxNorm` diff --git a/docs/user-guide/orthogonal.md b/docs/user-guide/orthogonal.md index ec2acc5..1511c68 100644 --- a/docs/user-guide/orthogonal.md +++ b/docs/user-guide/orthogonal.md @@ -252,7 +252,10 @@ raises a `RuntimeError`. `target_modules` takes qualified names or a predicate `(name, module) -> bool`. `fold_bn(conv, bn)` folds an eval-mode BatchNorm into the convolution before it, -so that a convolution and its BatchNorm can be adapted as one layer. +so that a convolution and its BatchNorm can be adapted as one layer. The +[certified fine-tuning example](../examples/orthogonal-certified-fine-tuning.md) +compares butterfly adapters with head-only training, LoRA and full fine-tuning +from axial to coronal CT slices. ### Certified robustness diff --git a/examples/notebooks/orthogonal-certified-fine-tuning.ipynb b/examples/notebooks/orthogonal-certified-fine-tuning.ipynb new file mode 100644 index 0000000..a915eb8 --- /dev/null +++ b/examples/notebooks/orthogonal-certified-fine-tuning.ipynb @@ -0,0 +1,734 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "79112c4d2dbe", + "metadata": {}, + "source": [ + "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/eigenorbit/eigenkit/blob/main/examples/notebooks/orthogonal-certified-fine-tuning.ipynb)" + ] + }, + { + "cell_type": "code", + "id": "fc1fc31eb854", + "metadata": {}, + "source": [ + "%pip install -q \"eigenkit[torch,viz,benchmark]\"" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "5e7b4c25c474", + "metadata": {}, + "source": [ + "# Certified Fine-Tuning with Butterfly Adapters\n", + "\n", + "## What this example shows\n", + "\n", + "The [previous example](../../docs/examples/orthogonal-certified-training.md) trained a network whose\n", + "Lipschitz bound \\(L\\) is 1, so every prediction comes with a certified radius: a\n", + "distance within which no change of the image can change the prediction. This\n", + "example asks what happens to that guarantee when such a network is adapted to a\n", + "new task.\n", + "\n", + "The certified radius of an image is\n", + "\n", + "\\[\n", + "r(x) = \\min_{j \\ne p} \\frac{z_p(x) - z_j(x)}{L \\, \\lVert w_p - w_j \\rVert_2},\n", + "\\]\n", + "\n", + "where \\(z\\) are the logits, \\(p\\) the predicted class, \\(w_k\\) the rows of the head\n", + "and \\(L\\) the bound of the features in front of the head. Adapting the network\n", + "changes its weights, and with them \\(L\\). Ordinary fine-tuning lets the\n", + "singular values of every weight drift, \\(L\\) grows, and the radii shrink by the\n", + "same factor, even when the accuracy is good.\n", + "\n", + "A *butterfly adapter* changes a frozen weight \\(W\\) by an orthogonal rotation\n", + "\\(R(\\theta)\\), built from RBS (Givens) rotations, in front of it:\n", + "\n", + "\\[\n", + "W' = R(\\theta) \\, W, \\qquad\n", + "W'^\\top W' = W^\\top R^\\top R \\, W = W^\\top W .\n", + "\\]\n", + "\n", + "\\(W'\\) has exactly the singular values of \\(W\\), for any \\(W\\) and any angles, so\n", + "the bound of the adapted network stays \\(L_0\\), the bound of the pretrained one,\n", + "and the certificate keeps its meaning. The angles start at zero, where\n", + "\\(R = I\\), so training starts from the pretrained network.\n", + "\n", + "We compare four ways of adapting the same pretrained network, all with a new\n", + "classification head:\n", + "\n", + "- **head only**: every pretrained weight stays frozen;\n", + "- **butterfly**: a butterfly adapter in front of every pretrained matrix;\n", + "- **LoRA** (Hu et al., ICLR 2022): a low-rank update \\(W' = W + BA\\) of rank 4,\n", + " with \\(B = 0\\) at the start, the usual parameter-efficient method;\n", + "- **full**: every pretrained weight is trained.\n", + "\n", + "See the [user guide](../../docs/user-guide/orthogonal.md#orthogonal-fine-tuning) for\n", + "`apply_orthogonal_adapters` and for the adapter on a single layer.\n", + "\n", + "## The data\n", + "\n", + "Two MedMNIST datasets (Yang et al., *Scientific Data* 10, 41, 2023) show the same\n", + "eleven abdominal organs in CT scans, cut in two different planes:\n", + "\n", + "- **OrganAMNIST**: axial slices, 34,561 training images. The network is\n", + " pretrained on it;\n", + "- **OrganCMNIST**: coronal slices, 12,975 training images and 8,216 test\n", + " images. The network is adapted to it, with only **1,000** labelled training\n", + " images, as when a new view of the data has few labels.\n", + "\n", + "The images are \\(28 \\times 28\\) and grey. As in the previous example, each one is\n", + "padded to \\(32 \\times 32\\) and flattened to a vector of 1024 values in \\([0, 1]\\), which\n", + "changes no distances. The files come from the MedMNIST record on Zenodo (CC BY\n", + "4.0) and are downloaded once, about 70 MB, into `~/.cache/medmnist`." + ] + }, + { + "cell_type": "code", + "id": "fe11ec4eee91", + "metadata": {}, + "source": [ + "import copy\n", + "import time\n", + "import urllib.request\n", + "from pathlib import Path\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "\n", + "from eigenkit import GenericClassifier\n", + "from eigenkit.datasets import STYLE_COLORS, rc_params\n", + "from eigenkit.orthogonal.torch import (\n", + " LLNHead,\n", + " MaxMin,\n", + " Orthogonal,\n", + " OrthogonalAdapter,\n", + " apply_orthogonal_adapters,\n", + " certified_accuracy,\n", + " certified_radius,\n", + " lipschitz_bound,\n", + ")\n", + "\n", + "URL = \"https://zenodo.org/records/10519652/files/{}.npz?download=1\"\n", + "FOLDER = Path.home() / \".cache\" / \"medmnist\"\n", + "\n", + "\n", + "def load_medmnist(name):\n", + " \"\"\"Images padded to 32 x 32 and flattened to 1024 values in [0, 1].\"\"\"\n", + " path = FOLDER / f\"{name}.npz\"\n", + " if not path.exists():\n", + " FOLDER.mkdir(parents=True, exist_ok=True)\n", + " urllib.request.urlretrieve(URL.format(name), path)\n", + " out = {}\n", + " with np.load(path) as data:\n", + " for split in (\"train\", \"val\", \"test\"):\n", + " images = data[f\"{split}_images\"].astype(np.float32) / 255\n", + " images = np.pad(images, ((0, 0), (2, 2), (2, 2)))\n", + " out[split] = (images.reshape(len(images), -1), data[f\"{split}_labels\"][:, 0])\n", + " return out\n", + "\n", + "\n", + "source = load_medmnist(\"organamnist\")\n", + "target = load_medmnist(\"organcmnist\")\n", + "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "\n", + "subset = np.random.default_rng(0).permutation(len(target[\"train\"][0]))[:1000]\n", + "X_few, y_few = target[\"train\"][0][subset], target[\"train\"][1][subset]\n", + "X_test, y_test = target[\"test\"]\n", + "print(f\"source train {source['train'][0].shape}\")\n", + "print(f\"target train {X_few.shape}, every class present: {len(np.unique(y_few)) == 11}\")\n", + "print(f\"target test {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "45017e928c0b", + "metadata": {}, + "source": [ + "*Output recorded in the documentation:*\n", + "\n", + "```text\n", + "source train (34561, 1024)\n", + "target train (1000, 1024), every class present: True\n", + "target test (8216, 1024)\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "ab610e7ea2c2", + "metadata": {}, + "source": [ + "The same six organs, once in each dataset, show how different the two views\n", + "are. The network has to carry what it learned on the top row over to the bottom\n", + "row:" + ] + }, + { + "cell_type": "code", + "id": "893cfbae0e53", + "metadata": {}, + "source": [ + "organs = (\n", + " \"bladder\",\n", + " \"femur-left\",\n", + " \"femur-right\",\n", + " \"heart\",\n", + " \"kidney-left\",\n", + " \"kidney-right\",\n", + " \"liver\",\n", + " \"lung-left\",\n", + " \"lung-right\",\n", + " \"pancreas\",\n", + " \"spleen\",\n", + ")\n", + "shown = (0, 3, 4, 6, 7, 10)\n", + "with plt.rc_context(rc_params(theme=\"light\")):\n", + " fig, axes = plt.subplots(2, 6, figsize=(9, 3.6))\n", + " for row, (name, data) in zip(axes, ((\"axial\", source), (\"coronal\", target))):\n", + " X, y = data[\"train\"]\n", + " for ax, organ in zip(row, shown):\n", + " ax.imshow(\n", + " X[np.flatnonzero(y == organ)[0]].reshape(32, 32),\n", + " cmap=\"gray\",\n", + " vmin=0,\n", + " vmax=1,\n", + " )\n", + " ax.set_axis_off()\n", + " if name == \"axial\":\n", + " ax.set_title(organs[organ], fontsize=10)\n", + " row[0].text(-4, 16, name, rotation=90, ha=\"right\", va=\"center\", fontsize=10)\n", + " fig.tight_layout()\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "c7fa6d52abf8", + "metadata": {}, + "source": [ + "![png](../../docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_1_0_light.png)\n", + "\n", + "## The pretrained certified network\n", + "\n", + "The pretrained network is the butterfly network of the previous example, eight\n", + "blocks deep, now with eleven outputs:\n", + "\n", + "\\[\n", + "x \\in \\mathbb{R}^{1024}\n", + "\\;\\to\\; 8 \\times \\big[\\, \\text{butterfly}(1024) \\to \\mathrm{MaxMin} \\,\\big]\n", + "\\;\\to\\; \\text{head}(1024 \\to 11).\n", + "\\]\n", + "\n", + "It is trained on OrganAMNIST by `GenericClassifier`, as before: Adam with a\n", + "learning rate of \\(10^{-3}\\), batches of 128, cross-entropy, 30 epochs.\n", + "\n", + "A pretrained network usually reaches us as plain weight matrices, not as\n", + "rotation angles. To start from that situation, we turn every trained butterfly\n", + "into an ordinary `nn.Linear` layer that holds its \\(1024 \\times 1024\\) matrix. The\n", + "matrices are orthogonal because of how they were trained, but nothing in an\n", + "`nn.Linear` keeps them so, and that is exactly the situation of fine-tuning.\n", + "The bound of the result, \\(L_0\\), is the product of their largest singular\n", + "values." + ] + }, + { + "cell_type": "code", + "id": "cf432178da34", + "metadata": {}, + "source": [ + "def make_network(depth, n_classes):\n", + " blocks = []\n", + " for _ in range(depth):\n", + " blocks += [Orthogonal(1024, \"butterfly\"), MaxMin()]\n", + " return nn.Sequential(*blocks, LLNHead(1024, n_classes))\n", + "\n", + "\n", + "start = time.time()\n", + "pretrained = GenericClassifier(\n", + " make_network(8, 11).to(device),\n", + " in_features=1024,\n", + " lr=1e-3,\n", + " epochs=30,\n", + " batch_size=128,\n", + " show_progress=False,\n", + " random_state=0,\n", + ").fit(*source[\"train\"])\n", + "source_accuracy = (pretrained.predict(source[\"test\"][0]) == source[\"test\"][1]).mean()\n", + "print(\n", + " f\"pretrained on OrganAMNIST in {time.time() - start:.0f} s, \"\n", + " f\"test accuracy {source_accuracy:.3f}\"\n", + ")\n", + "\n", + "layers = []\n", + "for layer in pretrained.model_[:-1]: # every block, without the head\n", + " if isinstance(layer, Orthogonal):\n", + " linear = nn.Linear(1024, 1024, bias=False)\n", + " with torch.no_grad():\n", + " linear.weight.copy_(layer.matrix())\n", + " layer = linear\n", + " layers.append(layer)\n", + "backbone = nn.Sequential(*layers).to(device)\n", + "L0 = lipschitz_bound(backbone)\n", + "print(f\"bound of the pretrained features: L0 = {L0:.6f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "12591ee67308", + "metadata": {}, + "source": [ + "*Output recorded in the documentation:*\n", + "\n", + "```text\n", + "pretrained on OrganAMNIST in 680 s, test accuracy 0.727\n", + "bound of the pretrained features: L0 = 1.000002\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "452cd6c22583", + "metadata": {}, + "source": [ + "## Four ways to adapt it\n", + "\n", + "Every strategy gets a copy of the frozen backbone and a new head,\n", + "`LLNHead(1024, 11)`, which is always trained.\n", + "\n", + "- **Head only** leaves the backbone as it is.\n", + "- **Butterfly** calls `apply_orthogonal_adapters`, which replaces every\n", + " `nn.Linear` it selects by an `OrthogonalAdapter`: the frozen weight times a\n", + " butterfly rotation whose angles start at zero. It freezes everything else.\n", + "- **LoRA** has no module in the library, so a few lines define it: the frozen\n", + " weight plus \\(BA\\), with \\(A\\) of shape \\(4 \\times 1024\\), and \\(B\\) of shape\n", + " \\(1024 \\times 4\\) starting at zero.\n", + "- **Full** makes every backbone weight trainable.\n", + "\n", + "In all four, the adapted network at step zero computes exactly the pretrained\n", + "features." + ] + }, + { + "cell_type": "code", + "id": "950f35561281", + "metadata": {}, + "source": [ + "class LoRA(nn.Module):\n", + " \"\"\"A frozen linear layer plus a trainable update B @ A of low rank.\"\"\"\n", + "\n", + " def __init__(self, base, rank=4):\n", + " super().__init__()\n", + " self.base = base\n", + " self.A = nn.Parameter(torch.randn(rank, base.in_features) * 0.01)\n", + " self.B = nn.Parameter(torch.zeros(base.out_features, rank))\n", + "\n", + " @property\n", + " def weight(self):\n", + " return self.base.weight + self.B @ self.A\n", + "\n", + " def forward(self, x):\n", + " return F.linear(x, self.weight)\n", + "\n", + "\n", + "def adapt(strategy):\n", + " torch.manual_seed(0) # the LoRA matrices A and the new head are drawn below\n", + " body = copy.deepcopy(backbone)\n", + " for p in body.parameters():\n", + " p.requires_grad_(strategy == \"full\")\n", + " if strategy == \"butterfly\":\n", + " apply_orthogonal_adapters(body, lambda name, m: isinstance(m, nn.Linear))\n", + " if strategy == \"LoRA\":\n", + " body = nn.Sequential(*[LoRA(m) if isinstance(m, nn.Linear) else m for m in body])\n", + " return nn.Sequential(body, LLNHead(1024, 11)).to(device)\n", + "\n", + "\n", + "strategies = (\"head only\", \"butterfly\", \"LoRA\", \"full\")\n", + "pd.DataFrame(\n", + " {\n", + " \"strategy\": strategies,\n", + " \"trainable parameters\": [\n", + " sum(p.numel() for p in adapt(s).parameters() if p.requires_grad)\n", + " for s in strategies\n", + " ],\n", + " }\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "e69026489d5f", + "metadata": {}, + "source": [ + "| strategy | trainable parameters |\n", + "|:---|---:|\n", + "| head only | 11,275 |\n", + "| butterfly | 52,235 |\n", + "| LoRA | 76,811 |\n", + "| full | 8,399,883 |\n", + "\n", + "A butterfly adapter on 1024 channels has \\(5{,}120\\) angles, so the eight of them\n", + "train \\(40{,}960\\) parameters, fewer than the \\(65{,}536\\) of LoRA and 200 times\n", + "fewer than the \\(8{,}388{,}608\\) of full fine-tuning. The counts in the table add\n", + "the \\(11{,}275\\) parameters of the head to each.\n", + "\n", + "## Training\n", + "\n", + "`GenericClassifier` starts every fit by initialising the network again, which\n", + "is right for training from scratch but would throw the pretrained weights away;\n", + "an `OrthogonalAdapter` refuses to be re-initialised for this reason. Fine-tuning\n", + "therefore uses a short loop of its own. It is the same for every strategy: Adam\n", + "on the trainable parameters, batches of 128, cross-entropy, and the model after\n", + "the last epoch is the one we evaluate.\n", + "\n", + "The learning rate and the number of epochs differ between the strategies. Both\n", + "were chosen on the validation split of OrganCMNIST, by the highest validation\n", + "accuracy; the test set was not used. The learning rate came first, from\n", + "\\(\\{10^{-3}, 10^{-2}\\}\\) for the head, \\(\\{3 \\cdot 10^{-3}, 10^{-2}, 3 \\cdot 10^{-2}\\}\\) for\n", + "butterfly, \\(\\{10^{-4}, 10^{-3}, 10^{-2}\\}\\) for LoRA and\n", + "\\(\\{3 \\cdot 10^{-5}, 10^{-4}, 3 \\cdot 10^{-4}, 10^{-3}\\}\\) for full fine-tuning. The number\n", + "of epochs came next, from \\(\\{30, 60, 120, 200\\}\\). Full fine-tuning is best after\n", + "30 epochs and then starts to overfit the 1,000 images; the other three are best\n", + "after 120. The angles of a rotation need a larger step than the entries of a\n", + "weight matrix: a change of one angle turns a whole pair of rows." + ] + }, + { + "cell_type": "code", + "id": "a8e234691005", + "metadata": {}, + "source": [ + "def fine_tune(model, X, y, lr, epochs, batch_size=128):\n", + " params = [p for p in model.parameters() if p.requires_grad]\n", + " optimizer = torch.optim.Adam(params, lr=lr)\n", + " X = torch.tensor(X, device=device)\n", + " y = torch.tensor(y, device=device, dtype=torch.long)\n", + " generator = torch.Generator().manual_seed(0)\n", + " model.train()\n", + " for _ in range(epochs):\n", + " for batch in torch.randperm(len(X), generator=generator).split(batch_size):\n", + " optimizer.zero_grad()\n", + " F.cross_entropy(model(X[batch]), y[batch]).backward()\n", + " optimizer.step()\n", + " return model.eval()\n", + "\n", + "\n", + "def bound(body):\n", + " \"\"\"L of the adapted features; LoRA layers are bounded by their weight.\"\"\"\n", + " if any(isinstance(m, LoRA) for m in body):\n", + " b = 1.0\n", + " for m in body:\n", + " if isinstance(m, LoRA):\n", + " b *= float(torch.linalg.matrix_norm(m.weight.detach().double(), 2))\n", + " return b\n", + " return lipschitz_bound(body)\n", + "\n", + "\n", + "def evaluate(model, X, y):\n", + " with torch.no_grad():\n", + " logits = model(torch.tensor(X, device=device))\n", + " L = bound(model[0])\n", + " cert = certified_radius(logits, model[1].get_weight(), L)\n", + " correct = cert.pred == torch.as_tensor(y)\n", + " return L, cert, correct\n", + "\n", + "\n", + "learning_rates = {\"head only\": 1e-3, \"butterfly\": 1e-2, \"LoRA\": 1e-4, \"full\": 3e-5}\n", + "epochs = {\"head only\": 120, \"butterfly\": 120, \"LoRA\": 120, \"full\": 30}\n", + "radii = (0.25, 0.5, 1.0)\n", + "models, results, rows = {}, {}, []\n", + "for strategy in strategies:\n", + " start = time.time()\n", + " model = fine_tune(\n", + " adapt(strategy), X_few, y_few, learning_rates[strategy], epochs[strategy]\n", + " )\n", + " L, cert, correct = evaluate(model, X_test, y_test)\n", + " models[strategy] = model\n", + " results[strategy] = {\n", + " \"L / L0\": L / L0,\n", + " \"accuracy\": certified_accuracy(correct, cert.radius, 0),\n", + " \"certified\": [certified_accuracy(correct, cert.radius, e) for e in radii],\n", + " \"radius\": cert.radius[correct].numpy(),\n", + " }\n", + " rows.append(\n", + " {\n", + " \"strategy\": strategy,\n", + " \"L / L0\": f\"{L / L0:.3g}\",\n", + " \"accuracy\": results[strategy][\"accuracy\"],\n", + " **{\n", + " f\"certified at {e}\": c\n", + " for e, c in zip(radii, results[strategy][\"certified\"])\n", + " },\n", + " \"time, s\": round(time.time() - start),\n", + " }\n", + " )\n", + "\n", + "pd.DataFrame(rows)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "049a7ab29441", + "metadata": {}, + "source": [ + "| strategy | L / L0 | accuracy | certified at 0.25 | certified at 0.5 | certified at 1.0 | time, s |\n", + "|:---|---:|---:|---:|---:|---:|---:|\n", + "| head only | 1 | 0.701 | 0.587 | 0.465 | 0.265 | 2 |\n", + "| butterfly | 1 | 0.753 | 0.654 | 0.531 | 0.305 | 50 |\n", + "| LoRA | 48.6 | 0.685 | 0.000 | 0.000 | 0.000 | 18 |\n", + "| full | 10.4 | 0.703 | 0.274 | 0.045 | 0.000 | 2 |" + ] + }, + { + "cell_type": "code", + "id": "7f395b5f3a2c", + "metadata": {}, + "source": [ + "with plt.rc_context(rc_params(theme=\"light\")):\n", + " fig, axes = plt.subplots(1, 2, figsize=(11, 4), width_ratios=(1.3, 1))\n", + " positions = np.arange(len(strategies))\n", + " colors = [STYLE_COLORS[k] for k in (6, 2, 4, 0)]\n", + " axes[0].bar(\n", + " positions,\n", + " [results[s][\"accuracy\"] for s in strategies],\n", + " 0.6,\n", + " fill=False,\n", + " edgecolor=colors,\n", + " linewidth=1.5,\n", + " label=\"accuracy\",\n", + " )\n", + " axes[0].bar(\n", + " positions,\n", + " [results[s][\"certified\"][1] for s in strategies],\n", + " 0.6,\n", + " color=colors,\n", + " label=r\"certified accuracy at $\\varepsilon = 0.5$\",\n", + " )\n", + " for k, s in enumerate(strategies):\n", + " axes[0].text(\n", + " k,\n", + " results[s][\"certified\"][1] + 0.01,\n", + " f\"{results[s]['certified'][1]:.2f}\",\n", + " ha=\"center\",\n", + " va=\"bottom\",\n", + " )\n", + " axes[0].set_xticks(positions, strategies)\n", + " axes[0].set_ylim(0, 0.85)\n", + " axes[0].legend(loc=\"upper right\", fontsize=9)\n", + " axes[0].set_title(\"OrganCMNIST, 1,000 training labels\")\n", + " grid = np.linspace(0, 1.5, 151)\n", + " for s, c in zip(strategies, colors):\n", + " radius = np.sort(results[s][\"radius\"])\n", + " n_test = len(y_test)\n", + " axes[1].plot(grid, [(radius > e).sum() / n_test for e in grid], color=c, label=s)\n", + " axes[1].set_xlabel(r\"radius $\\varepsilon$\")\n", + " axes[1].set_ylabel(\"certified accuracy\")\n", + " axes[1].set_title(\"Certified accuracy against the radius\")\n", + " axes[1].legend(fontsize=9)\n", + " fig.tight_layout()\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "f20e17696b8c", + "metadata": {}, + "source": [ + "![png](../../docs/examples/orthogonal_certified_fine_tuning_files/orthogonal_certified_fine_tuning_5_0_light.png)\n", + "\n", + "Butterfly is the most accurate strategy, 0.753 against 0.701 for the head alone,\n", + "0.685 for LoRA and 0.703 for full fine-tuning, which train more parameters. It\n", + "also certifies the most test images at every radius in the table, 0.531 at\n", + "\\(\\varepsilon = 0.5\\) against 0.465 for the head alone. Butterfly and head only\n", + "keep \\(L / L_0 = 1\\), so their certificates mean what they meant before the\n", + "adaptation.\n", + "\n", + "LoRA and full fine-tuning raise the bound 49 and 10 times. Their accuracy is\n", + "close to that of the head alone, but at 0.5 they certify 0% and 4.5% of the test\n", + "images. The right panel shows the whole range of radii. The curve of LoRA falls\n", + "to zero before a radius of 0.2, and that of full fine-tuning before 0.8.\n", + "Butterfly stays above head only at every radius up to 1.5.\n", + "\n", + "## Where the guarantee goes\n", + "\n", + "The certificate of LoRA and of full fine-tuning is lost through \\(L\\), and \\(L\\)\n", + "is a product over the eight matrices. The next cell prints the largest\n", + "singular value of every adapted matrix: it is 1 for the pretrained network, and\n", + "it stays 1, to rounding, in every butterfly-adapted layer." + ] + }, + { + "cell_type": "code", + "id": "d4352fc0a843", + "metadata": {}, + "source": [ + "def adapted_matrices(body):\n", + " for m in body:\n", + " if isinstance(m, (nn.Linear, OrthogonalAdapter, LoRA)):\n", + " yield m.weight.detach().double()\n", + "\n", + "\n", + "pd.DataFrame(\n", + " {\n", + " strategy: [\n", + " f\"{float(torch.linalg.matrix_norm(w, 2)):.4g}\"\n", + " for w in adapted_matrices(models[strategy][0])\n", + " ]\n", + " for strategy in (\"butterfly\", \"LoRA\", \"full\")\n", + " },\n", + " index=pd.Index(range(1, 9), name=\"layer\"),\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "7d0ba516d588", + "metadata": {}, + "source": [ + "| layer | butterfly | LoRA | full |\n", + "|---:|---:|---:|---:|\n", + "| 1 | 1 | 1.24 | 1.165 |\n", + "| 2 | 1 | 1.246 | 1.259 |\n", + "| 3 | 1 | 1.327 | 1.31 |\n", + "| 4 | 1 | 1.497 | 1.372 |\n", + "| 5 | 1 | 1.564 | 1.393 |\n", + "| 6 | 1 | 1.778 | 1.411 |\n", + "| 7 | 1 | 2.396 | 1.412 |\n", + "| 8 | 1 | 2.376 | 1.415 |\n", + "\n", + "Every butterfly-adapted layer keeps the largest singular value of its\n", + "pretrained matrix, 1, to the four digits printed. LoRA raises it to between 1.24\n", + "and 2.40 per layer, and full fine-tuning to between 1.17 and 1.42. Each factor is\n", + "modest, but they multiply: their products are the 48.6 and 10.4 of the table,\n", + "and every certified radius is divided by them.\n", + "\n", + "## With all the labels\n", + "\n", + "The comparison above uses 1,000 labels, a setting with few labels. The cell below\n", + "repeats it with all 12,975 training images of OrganCMNIST and the same learning\n", + "rates. The numbers of epochs were chosen on the validation split again, from\n", + "\\(\\{15, 30, 60\\}\\): 30 for the head and LoRA, 60 for butterfly and full\n", + "fine-tuning." + ] + }, + { + "cell_type": "code", + "id": "cca36e9c6c12", + "metadata": {}, + "source": [ + "epochs_all_labels = {\"head only\": 30, \"butterfly\": 60, \"LoRA\": 30, \"full\": 60}\n", + "rows = []\n", + "for strategy in strategies:\n", + " start = time.time()\n", + " model = fine_tune(\n", + " adapt(strategy),\n", + " *target[\"train\"],\n", + " learning_rates[strategy],\n", + " epochs_all_labels[strategy],\n", + " )\n", + " L, cert, correct = evaluate(model, X_test, y_test)\n", + " rows.append(\n", + " {\n", + " \"strategy\": strategy,\n", + " \"L / L0\": f\"{L / L0:.3g}\",\n", + " \"accuracy\": certified_accuracy(correct, cert.radius, 0),\n", + " \"certified at 0.5\": certified_accuracy(correct, cert.radius, 0.5),\n", + " \"time, s\": round(time.time() - start),\n", + " }\n", + " )\n", + "\n", + "pd.DataFrame(rows)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "f2a3965c25e2", + "metadata": {}, + "source": [ + "| strategy | L / L0 | accuracy | certified at 0.5 | time, s |\n", + "|:---|---:|---:|---:|---:|\n", + "| head only | 1 | 0.743 | 0.511 | 5 |\n", + "| butterfly | 1 | 0.778 | 0.602 | 318 |\n", + "| LoRA | 171 | 0.741 | 0.000 | 29 |\n", + "| full | 181 | 0.812 | 0.000 | 42 |\n", + "\n", + "With all the labels, full fine-tuning is the most accurate strategy, 0.812\n", + "against 0.778 for butterfly, but its bound grows 181 times and it certifies\n", + "nothing at 0.5; LoRA certifies nothing either. Butterfly keeps \\(L_0\\), is the\n", + "most accurate of the strategies that keep the certificate, and certifies 0.602\n", + "of the test images, more than the 0.511 of the head alone. With more data an\n", + "unconstrained update finds a better accuracy, but only the orthogonal update\n", + "keeps a guarantee.\n", + "\n", + "## Takeaway\n", + "\n", + "A certified network adapted with butterfly adapters stays certified. Its bound is\n", + "exactly the pretrained one, by construction, so its certificates keep their\n", + "meaning. On OrganCMNIST with 1,000 labels, butterfly is both the most accurate\n", + "strategy and the one that certifies the most test images, with 52,235 trainable\n", + "parameters. LoRA and full fine-tuning train more parameters, reach a lower\n", + "accuracy, and lose the certificate through a bound that grows layer by layer.\n", + "With all the labels, full fine-tuning becomes more accurate by about 0.03, at\n", + "the price of every guarantee.\n", + "\n", + "## Citation\n", + "\n", + "This example follows *Quantum-inspired orthogonal adapters for certifiably robust\n", + "medical image classification* ([arXiv:2611.18775](https://arxiv.org/abs/2611.18775)),\n", + "which studies butterfly layers and butterfly adapters in certified classifiers of\n", + "medical images. The code of the paper is in\n", + "[eigenorbit/quantum-inspired-fine-tuning](https://github.com/eigenorbit/quantum-inspired-fine-tuning).\n", + "If you use these methods in your research, please cite the paper:\n", + "\n", + "```bibtex\n", + "@misc{tsurkan2026quantum,\n", + " title = {Quantum-inspired orthogonal adapters for certifiably robust medical image classification},\n", + " author = {Tsurkan, Olga and Domingo, Laia and Orlova, Victoria and Sagingalieva, Asel and Zalaudek, Iris and Caposiena Caro, Raffaele Dante},\n", + " year = {2026},\n", + " eprint = {2611.18775},\n", + " archivePrefix = {arXiv},\n", + " primaryClass = {cs.CV},\n", + " doi = {10.48550/arXiv.2611.18775},\n", + " url = {https://arxiv.org/abs/2611.18775}\n", + "}\n", + "```" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/examples/notebooks/orthogonal-certified-training.ipynb b/examples/notebooks/orthogonal-certified-training.ipynb new file mode 100644 index 0000000..eb99757 --- /dev/null +++ b/examples/notebooks/orthogonal-certified-training.ipynb @@ -0,0 +1,630 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "c80f4503373f", + "metadata": {}, + "source": [ + "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/eigenorbit/eigenkit/blob/main/examples/notebooks/orthogonal-certified-training.ipynb)" + ] + }, + { + "cell_type": "code", + "id": "ad7c65127d2b", + "metadata": {}, + "source": [ + "%pip install -q \"eigenkit[torch,viz,benchmark]\"" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "e8bba70711e8", + "metadata": {}, + "source": [ + "# Certified Classifier from Orthogonal Layers\n", + "\n", + "## Why a prediction needs more than accuracy\n", + "\n", + "A classifier is usually judged by one number: how often it is right on a test\n", + "set. For a model that is going to inform a real decision, that is not enough. A\n", + "model can be right on almost every test image and still change its answer when\n", + "the image changes by an amount nobody would notice — another camera, a\n", + "re-encoding, a handful of pixels. Accuracy on a fixed test set cannot see this,\n", + "because it only ever asks about the images in the set, never about the images\n", + "next to them.\n", + "\n", + "So there is a second question to ask of a prediction, next to whether it is\n", + "right: how much can the input change before the prediction changes?\n", + "\n", + "One way to answer it is to attack the model — search for a small change that\n", + "flips the prediction, and report the smallest one found. That is useful, but it\n", + "only bounds the robustness from above: a better search may find a smaller change\n", + "tomorrow, and the answer depends on the attack. The guarantee we want points the\n", + "other way. Around each image we want a radius inside which *no* change at all can\n", + "flip the prediction: not \"no attack we tried succeeded\", but \"no attack can\n", + "succeed\". A prediction that comes with such a radius is *certifiably robust*, and\n", + "the radius is a proof about the network, not the result of one search.\n", + "\n", + "This example builds classifiers whose predictions carry such a radius, where the\n", + "radius follows from the way the network is constructed rather than from anything\n", + "done to it after training.\n", + "\n", + "## The certificate\n", + "\n", + "Let \\(h\\) be the part of the network that maps the image to the features in front\n", + "of the last linear layer. The one thing the proof needs about \\(h\\) is how much it\n", + "can stretch a change of its input: a number \\(L\\) with\n", + "\n", + "\\[\n", + "\\lVert h(x) - h(x') \\rVert_2 \\le L \\, \\lVert x - x' \\rVert_2 \\quad \\text{for all } x, x'.\n", + "\\]\n", + "\n", + "Such an \\(L\\) is a *Lipschitz bound* of \\(h\\). It is a worst case over every pair of\n", + "inputs and every direction, which is what makes it strong enough to prove\n", + "something rather than merely to describe the data at hand.\n", + "\n", + "The rest follows from the last layer. If the logits are\n", + "\\(z_k = w_k^\\top h(x) + b_k\\) and \\(p\\) is the predicted class, class \\(j\\) can\n", + "overtake class \\(p\\) only by closing the gap \\(z_p - z_j\\), and a change \\(\\delta\\)\n", + "of the image closes it by at most\n", + "\\(L \\lVert w_p - w_j \\rVert \\, \\lVert \\delta \\rVert\\). The prediction therefore\n", + "cannot change while \\(\\lVert \\delta \\rVert\\) stays below the *certified radius*\n", + "\n", + "\\[\n", + "r(x) = \\min_{j \\ne p} \\frac{z_p(x) - z_j(x)}{L \\, \\lVert w_p - w_j \\rVert_2}.\n", + "\\]\n", + "\n", + "The radius comes from one forward pass, with no attack and no sampling. Two\n", + "things have to hold for it to be worth anything. \\(L\\) must be small, and \\(L\\) of\n", + "a deep network is the product of the bounds of its layers, so every layer has to\n", + "be controlled. The margins \\(z_p - z_j\\) must also stay large — which, as the rest\n", + "of this example shows, is where networks built for a small \\(L\\) tend to fail.\n", + "\n", + "## What this example shows\n", + "\n", + "This example trains the same small network with three kinds of linear layer and\n", + "watches what happens to accuracy and to the certificate as the network gets\n", + "deeper:\n", + "\n", + "- **butterfly**: an orthogonal matrix built from RBS (Givens) rotations, the\n", + " classical form of a quantum orthogonal layer. Every singular value is exactly 1,\n", + " for every value of the angles;\n", + "- **dense-sn**: an ordinary dense matrix divided by its largest singular value\n", + " (spectral normalisation). Its largest singular value is 1, but the others are\n", + " free to be smaller;\n", + "- **dense**: an ordinary dense matrix with no constraint.\n", + "\n", + "All three are trained with the library's\n", + "[`GenericClassifier`](../../docs/user-guide/estimators.md), with the same loss, optimiser\n", + "and number of epochs. See the [user guide](../../docs/user-guide/orthogonal.md) for the\n", + "orthogonal modules and [Orthogonal networks](../../docs/algorithms/orthogonal-networks.md)\n", + "for the theory of RBS circuits.\n", + "\n", + "## The data\n", + "\n", + "[PneumoniaMNIST](https://medmnist.com/) (Yang et al., *Scientific Data* 10, 41,\n", + "2023) holds paediatric chest X-rays of \\(28 \\times 28\\) pixels, labelled normal or\n", + "pneumonia: 4,708 training images and 624 test images. The file comes from the\n", + "MedMNIST record on Zenodo (CC BY 4.0) and is downloaded once, about 4 MB, into\n", + "`~/.cache/medmnist`.\n", + "\n", + "Every image is padded with zeros to \\(32 \\times 32\\) and flattened into a vector of\n", + "1024 pixels in \\([0, 1]\\). The padding only adds zeros and the flattening only\n", + "reorders the pixels, so the distance between two images does not change: a\n", + "certificate for the vector is a certificate for the image. The width 1024 is a\n", + "power of two, which the butterfly layout needs." + ] + }, + { + "cell_type": "code", + "id": "236c2aaa5427", + "metadata": {}, + "source": [ + "import time\n", + "import urllib.request\n", + "from pathlib import Path\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.nn.utils import parametrize\n", + "\n", + "from eigenkit import GenericClassifier\n", + "from eigenkit.datasets import STYLE_COLORS, rc_params\n", + "from eigenkit.orthogonal.torch import (\n", + " LLNHead,\n", + " MaxMin,\n", + " Orthogonal,\n", + " certified_accuracy,\n", + " certified_radius,\n", + " lipschitz_bound,\n", + " sigma_max,\n", + ")\n", + "\n", + "URL = \"https://zenodo.org/records/10519652/files/{}.npz?download=1\"\n", + "FOLDER = Path.home() / \".cache\" / \"medmnist\"\n", + "\n", + "\n", + "def load_medmnist(name):\n", + " \"\"\"Images padded to 32 x 32 and flattened to 1024 values in [0, 1].\"\"\"\n", + " path = FOLDER / f\"{name}.npz\"\n", + " if not path.exists():\n", + " FOLDER.mkdir(parents=True, exist_ok=True)\n", + " urllib.request.urlretrieve(URL.format(name), path)\n", + " out = {}\n", + " with np.load(path) as data:\n", + " for split in (\"train\", \"test\"):\n", + " images = data[f\"{split}_images\"].astype(np.float32) / 255\n", + " images = np.pad(images, ((0, 0), (2, 2), (2, 2)))\n", + " out[split] = (images.reshape(len(images), -1), data[f\"{split}_labels\"][:, 0])\n", + " return out\n", + "\n", + "\n", + "data = load_medmnist(\"pneumoniamnist\")\n", + "X_train, y_train = data[\"train\"]\n", + "X_test, y_test = data[\"test\"]\n", + "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "\n", + "print(f\"train {X_train.shape}, labels {np.bincount(y_train).tolist()}\")\n", + "print(f\"test {X_test.shape}, labels {np.bincount(y_test).tolist()}\")\n", + "print(f\"median norm of a test image: {np.median(np.linalg.norm(X_test, axis=1)):.1f}\")\n", + "print(f\"norm of a change of 1/255 in every one of the 784 pixels: {28 / 255:.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "90ded88de930", + "metadata": {}, + "source": [ + "*Output recorded in the documentation:*\n", + "\n", + "```text\n", + "train (4708, 1024), labels [1214, 3494]\n", + "test (624, 1024), labels [234, 390]\n", + "median norm of a test image: 16.6\n", + "norm of a change of 1/255 in every one of the 784 pixels: 0.11\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "2468ac5a470c", + "metadata": {}, + "source": [ + "The last two lines give a scale for the radii below. A radius of 0.5 is about 3%\n", + "of the norm of a typical image, or a change of about four grey levels in every\n", + "pixel at once.\n", + "\n", + "Here are six training images of each class, as the network receives them,\n", + "padding included:" + ] + }, + { + "cell_type": "code", + "id": "4e0d9d05b62c", + "metadata": {}, + "source": [ + "classes = (\"normal\", \"pneumonia\")\n", + "with plt.rc_context(rc_params(theme=\"light\")):\n", + " fig, axes = plt.subplots(2, 6, figsize=(9, 3.4))\n", + " for label, row in zip((0, 1), axes):\n", + " for ax, i in zip(row, np.flatnonzero(y_train == label)[:6]):\n", + " ax.imshow(X_train[i].reshape(32, 32), cmap=\"gray\", vmin=0, vmax=1)\n", + " ax.set_axis_off()\n", + " row[0].set_title(classes[label], loc=\"left\", fontsize=11)\n", + " fig.tight_layout()\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "6dbc563a068d", + "metadata": {}, + "source": [ + "![png](../../docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_1_0_light.png)\n", + "\n", + "## The network\n", + "\n", + "The network is a stack of \\(D\\) identical blocks, followed by a linear head:\n", + "\n", + "\\[\n", + "x \\in \\mathbb{R}^{1024}\n", + "\\;\\to\\; \\big[\\, W_1 \\to \\mathrm{MaxMin} \\,\\big]\n", + "\\;\\to\\; \\cdots\n", + "\\;\\to\\; \\big[\\, W_D \\to \\mathrm{MaxMin} \\,\\big]\n", + "\\;\\to\\; \\text{head} \\;\\to\\; (z_0, z_1).\n", + "\\]\n", + "\n", + "The matrices carry no bias and there is no normalisation layer. Only the \\(W_i\\)\n", + "change between the three variants. The other two pieces are the same in all of\n", + "them, and both are chosen so that they never stretch a change of their input.\n", + "\n", + "`MaxMin` splits the 1024 features into the 512 disjoint pairs\n", + "\\((u_{2k}, u_{2k+1})\\) and sorts each pair on its own, smaller value first:\n", + "\n", + "\\[\n", + "\\mathrm{MaxMin}(u)_{2k} = \\min(u_{2k},\\, u_{2k+1}), \\qquad\n", + "\\mathrm{MaxMin}(u)_{2k+1} = \\max(u_{2k},\\, u_{2k+1}).\n", + "\\]\n", + "\n", + "It either leaves a pair as it is or swaps its two entries, so on any given input\n", + "it is a permutation of the 1024 coordinates: it keeps the norm of its input and\n", + "is 1-Lipschitz (Anil, Lucas and Grosse, ICML 2019). *Which* permutation it\n", + "applies depends on the input, and that is what makes it non-linear.\n", + "\n", + "`LLNHead` is a linear head whose rows are normalised to unit length at every\n", + "call, so the distances \\(\\lVert w_p - w_j \\rVert\\) in the radius depend only on\n", + "the directions of the rows.\n", + "\n", + "Because `MaxMin` is 1-Lipschitz, each block contributes exactly the bound of its\n", + "matrix, and the bound of the features is their product,\n", + "\\(L = \\prod_{i=1}^{D} \\sigma_{\\max}(W_i)\\); `lipschitz_bound` computes it for any\n", + "stack of these layers. For the butterfly variant \\(L = 1\\) by construction. For\n", + "dense-sn every factor is 1 too, through a parametrisation that divides the weight\n", + "by its largest singular value at every call (`sigma_max` computes it exactly). For\n", + "dense nothing holds \\(L\\) down." + ] + }, + { + "cell_type": "code", + "id": "afcc13926ada", + "metadata": {}, + "source": [ + "class UnitSpectralNorm(nn.Module):\n", + " \"\"\"Divide a weight by its largest singular value.\"\"\"\n", + "\n", + " def forward(self, weight):\n", + " return weight / sigma_max(weight)\n", + "\n", + "\n", + "def mixer(kind):\n", + " if kind == \"butterfly\":\n", + " return Orthogonal(1024, \"butterfly\")\n", + " layer = nn.Linear(1024, 1024, bias=False)\n", + " if kind == \"dense-sn\":\n", + " parametrize.register_parametrization(layer, \"weight\", UnitSpectralNorm())\n", + " return layer\n", + "\n", + "\n", + "def make_network(kind, depth, n_classes=2):\n", + " blocks = []\n", + " for _ in range(depth):\n", + " blocks += [mixer(kind), MaxMin()]\n", + " return nn.Sequential(*blocks, LLNHead(1024, n_classes))\n", + "\n", + "\n", + "for kind in (\"butterfly\", \"dense-sn\", \"dense\"):\n", + " n = sum(p.numel() for p in mixer(kind).parameters())\n", + " print(f\"{kind:10s} {n:9,d} parameters per block\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "778f50488e58", + "metadata": {}, + "source": [ + "*Output recorded in the documentation:*\n", + "\n", + "```text\n", + "butterfly 5,120 parameters per block\n", + "dense-sn 1,048,576 parameters per block\n", + "dense 1,048,576 parameters per block\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "658bef9c5ba3", + "metadata": {}, + "source": [ + "A butterfly on \\(n = 1024\\) wires has \\(\\log_2 n = 10\\) layers of \\(n/2 = 512\\)\n", + "rotations, so \\(5{,}120\\) angles instead of the \\(1{,}048{,}576\\) entries of a dense\n", + "matrix. The angles start at zero, so an untrained butterfly block is the\n", + "identity.\n", + "\n", + "## Training\n", + "\n", + "Each network is trained by `GenericClassifier`, which wraps any `nn.Module` in the\n", + "`fit` / `predict` interface of scikit-learn and runs the standard training loop of\n", + "the library: Adam with a learning rate of \\(10^{-3}\\), batches of 128, the\n", + "cross-entropy loss, and 10 epochs, the same for every model. We train every\n", + "variant at depths 2, 8 and 32. The fitted network is `clf.model_`. The time\n", + "column of the output was measured on a GPU; on a CPU the deepest networks take\n", + "longest.\n", + "\n", + "After training we compute, on the 624 test images:\n", + "\n", + "- the accuracy;\n", + "- the bound \\(L\\) of the features, with `lipschitz_bound`;\n", + "- the certified radius of every image, with `certified_radius`, from the logits,\n", + " the normalised head weights and \\(L\\);\n", + "- the *certified accuracy* at radius \\(\\varepsilon\\) with `certified_accuracy`: the\n", + " share of test images that are classified correctly *and* have\n", + " \\(r(x) > \\varepsilon\\). It is the accuracy that is guaranteed against every change\n", + " of norm up to \\(\\varepsilon\\), whatever its direction." + ] + }, + { + "cell_type": "code", + "id": "dd4413f7afa3", + "metadata": {}, + "source": [ + "def certify(model, X, y):\n", + " \"\"\"Logits, bound, certificate and correctness on a test set.\"\"\"\n", + " model.eval()\n", + " with torch.no_grad():\n", + " logits = model(torch.tensor(X, device=device))\n", + " L = lipschitz_bound(model[:-1]) # every block, without the head\n", + " cert = certified_radius(logits, model[-1].get_weight(), L)\n", + " correct = cert.pred == torch.as_tensor(y)\n", + " return L, cert, correct\n", + "\n", + "\n", + "depths = (2, 8, 32)\n", + "kinds = (\"butterfly\", \"dense-sn\", \"dense\")\n", + "radii = (0.25, 0.5, 1.0)\n", + "models, results, rows = {}, {}, []\n", + "for depth in depths:\n", + " for kind in kinds:\n", + " start = time.time()\n", + " torch.manual_seed(0) # the dense weights are drawn when the network is built\n", + " clf = GenericClassifier(\n", + " make_network(kind, depth).to(device),\n", + " in_features=1024,\n", + " lr=1e-3,\n", + " epochs=10,\n", + " batch_size=128,\n", + " show_progress=False,\n", + " random_state=0,\n", + " )\n", + " clf.fit(X_train, y_train)\n", + " L, cert, correct = certify(clf.model_, X_test, y_test)\n", + " models[kind, depth] = clf.model_\n", + " results[kind, depth] = {\n", + " \"L\": L,\n", + " \"accuracy\": certified_accuracy(correct, cert.radius, 0),\n", + " \"certified\": [certified_accuracy(correct, cert.radius, e) for e in radii],\n", + " }\n", + " rows.append(\n", + " {\n", + " \"depth\": depth,\n", + " \"mixer\": kind,\n", + " \"L\": f\"{L:.3g}\",\n", + " \"accuracy\": results[kind, depth][\"accuracy\"],\n", + " **{\n", + " f\"certified at {e}\": c\n", + " for e, c in zip(radii, results[kind, depth][\"certified\"])\n", + " },\n", + " \"time, s\": round(time.time() - start),\n", + " }\n", + " )\n", + "\n", + "pd.DataFrame(rows)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "4253d6f4f4ba", + "metadata": {}, + "source": [ + "| depth | mixer | L | accuracy | certified at 0.25 | certified at 0.5 | certified at 1.0 | time, s |\n", + "|---:|:---|---:|---:|---:|---:|---:|---:|\n", + "| 2 | butterfly | 1 | 0.853 | 0.772 | 0.675 | 0.426 | 9 |\n", + "| 2 | dense-sn | 1 | 0.822 | 0.763 | 0.663 | 0.460 | 12 |\n", + "| 2 | dense | 9.44 | 0.830 | 0.673 | 0.458 | 0.043 | 1 |\n", + "| 8 | butterfly | 1 | 0.854 | 0.769 | 0.683 | 0.421 | 25 |\n", + "| 8 | dense-sn | 1 | 0.822 | 0.590 | 0.551 | 0.417 | 47 |\n", + "| 8 | dense | 2.27e+03 | 0.771 | 0.000 | 0.000 | 0.000 | 3 |\n", + "| 32 | butterfly | 1 | 0.790 | 0.708 | 0.657 | 0.527 | 82 |\n", + "| 32 | dense-sn | 1 | 0.625 | 0.625 | 0.000 | 0.000 | 188 |\n", + "| 32 | dense | 8.15e+20 | 0.625 | 0.000 | 0.000 | 0.000 | 12 |" + ] + }, + { + "cell_type": "code", + "id": "f0071c1f98d9", + "metadata": {}, + "source": [ + "with plt.rc_context(rc_params(theme=\"light\")):\n", + " fig, axes = plt.subplots(1, 3, figsize=(12, 3.8))\n", + " lines = {\"butterfly\": (\"o\", \"-\"), \"dense-sn\": (\"s\", \"--\"), \"dense\": (\"^\", \":\")}\n", + " for k, kind in enumerate(kinds):\n", + " marker, linestyle = lines[kind]\n", + " style = dict(\n", + " marker=marker, linestyle=linestyle, color=STYLE_COLORS[2 * k], label=kind\n", + " )\n", + " axes[0].plot(depths, [results[kind, d][\"accuracy\"] for d in depths], **style)\n", + " axes[1].plot(depths, [results[kind, d][\"certified\"][1] for d in depths], **style)\n", + " axes[2].plot(depths, [results[kind, d][\"L\"] for d in depths], **style)\n", + " majority = np.bincount(y_test).max() / len(y_test)\n", + " axes[0].axhline(majority, color=\"grey\", linestyle=\":\", label=\"always 'pneumonia'\")\n", + " axes[0].set_title(\"Accuracy\")\n", + " axes[1].set_title(r\"Certified accuracy at $\\varepsilon = 0.5$\")\n", + " axes[2].set_title(\"Bound $L$ of the features\")\n", + " axes[2].set_yscale(\"log\")\n", + " for ax in axes:\n", + " ax.set_xscale(\"log\", base=2)\n", + " ax.set_xticks(depths, [str(d) for d in depths])\n", + " ax.set_xlabel(\"depth $D$\")\n", + " axes[0].set_ylim(0.3, 0.9)\n", + " axes[1].set_ylim(-0.03, 0.8)\n", + " handles, labels = axes[0].get_legend_handles_labels()\n", + " fig.legend(handles, labels, loc=\"upper center\", ncol=4)\n", + " fig.tight_layout(rect=(0, 0, 1, 0.88))\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "0571c496bfcd", + "metadata": {}, + "source": [ + "![png](../../docs/examples/orthogonal_certified_training_files/orthogonal_certified_training_4_0_light.png)\n", + "\n", + "At depth 2 the three variants are close. Their accuracy is 0.82 to 0.85, and the\n", + "two constrained ones certify about two thirds of the test images at\n", + "\\(\\varepsilon = 0.5\\). The unconstrained network already has \\(L \\approx 9\\), which\n", + "divides every radius by 9, and it certifies less, 0.458.\n", + "\n", + "With depth they part ways. The bound of the dense network grows with every\n", + "layer, to \\(2.3 \\cdot 10^{3}\\) at depth 8 and \\(8 \\cdot 10^{20}\\) at depth 32. At depth\n", + "8 its predictions are still often right, 0.771, but not one of them is certified\n", + "at any radius in the table. Spectral normalisation keeps \\(L = 1\\), but at depth 32\n", + "the network answers \"pneumonia\" for every image: its accuracy, 0.625, is the share\n", + "of that class in the test set, and it certifies nothing at 0.5. The butterfly\n", + "network keeps \\(L = 1\\) at every depth and still certifies 0.657 of the test images\n", + "at depth 32, almost as many as at depth 2. Its accuracy goes down from 0.853 to\n", + "0.790 with the same 10 epochs, but it never collapses to one class.\n", + "\n", + "## Why spectral normalisation fails at depth\n", + "\n", + "Both constrained variants have \\(L = 1\\), so the difference between them is not in\n", + "the bound. It is in what the layers do to the signal. A layer with\n", + "\\(\\sigma_{\\max} = 1\\) cannot enlarge any input, but if its other singular values\n", + "are smaller than one it shrinks the inputs along those directions, and a stack of\n", + "such layers shrinks them again and again. The logits are then small, and so are\n", + "the margins \\(z_p - z_j\\) that the radius is made of. An orthogonal layer keeps\n", + "the norm of every input, \\(\\lVert Wx \\rVert = \\lVert x \\rVert\\), and `MaxMin` keeps it\n", + "too, so the features of the butterfly network have exactly the norm of the image,\n", + "at any depth.\n", + "\n", + "The next cell measures this: the median of \\(\\lVert h(x) \\rVert / \\lVert x \\rVert\\) over\n", + "the test images, and the smallest singular value of the matrices of each\n", + "network." + ] + }, + { + "cell_type": "code", + "id": "cbdd5c8194d4", + "metadata": {}, + "source": [ + "def norm_kept(model, X):\n", + " with torch.no_grad():\n", + " x = torch.tensor(X, device=device)\n", + " h = model[:-1](x)\n", + " return float((h.norm(dim=1) / x.norm(dim=1)).median())\n", + "\n", + "\n", + "def smallest_singular_value(model):\n", + " \"\"\"The smallest singular value over the matrices of a network.\"\"\"\n", + " values = []\n", + " for layer in model[:-1]:\n", + " if isinstance(layer, nn.Linear):\n", + " weight = layer.weight\n", + " elif isinstance(layer, Orthogonal):\n", + " weight = layer.matrix() # a butterfly builds its matrix from the angles\n", + " else:\n", + " continue # MaxMin has no matrix\n", + " values.append(torch.linalg.svdvals(weight.detach().double()).min())\n", + " return float(min(values))\n", + "\n", + "\n", + "pd.DataFrame(\n", + " [\n", + " {\n", + " \"depth\": depth,\n", + " \"mixer\": kind,\n", + " \"‖h(x)‖ / ‖x‖\": f\"{norm_kept(models[kind, depth], X_test):.4f}\",\n", + " \"smallest singular value\": f\"{smallest_singular_value(models[kind, depth]):.2e}\",\n", + " }\n", + " for depth in depths\n", + " for kind in (\"butterfly\", \"dense-sn\")\n", + " ]\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "40d510d6cc33", + "metadata": {}, + "source": [ + "| depth | mixer | ‖h(x)‖ / ‖x‖ | smallest singular value |\n", + "|---:|:---|---:|---:|\n", + "| 2 | butterfly | 1.0000 | 1.00e+00 |\n", + "| 2 | dense-sn | 0.0988 | 3.51e-05 |\n", + "| 8 | butterfly | 1.0000 | 1.00e+00 |\n", + "| 8 | dense-sn | 0.0644 | 1.99e-05 |\n", + "| 32 | butterfly | 1.0000 | 1.00e+00 |\n", + "| 32 | dense-sn | 0.0000 | 1.04e-06 |\n", + "\n", + "The butterfly networks keep the norm of every image exactly, and the smallest\n", + "singular value of their matrices is 1; since \\(L = 1\\) bounds the largest, every\n", + "singular value is 1. The dense-sn networks have singular values down to\n", + "\\(10^{-5}\\) even at depth 2, and their features keep about 10% of the norm of the\n", + "image at depth 2, 6% at depth 8, and nothing measurable at depth 32. With unit\n", + "rows in the head, the gap between two logits is at most\n", + "\\(\\lVert w_p - w_j \\rVert \\, \\lVert h(x) \\rVert\\) plus the difference of the biases.\n", + "When \\(h(x)\\) is almost zero, only the biases are left: they pick one class for\n", + "every image, and the margin no longer depends on the image at all. That is the\n", + "collapse in the plot. A bound \\(L = 1\\) is therefore not enough. The layers must\n", + "also not lose the signal, and orthogonal layers are the linear layers that lose\n", + "none.\n", + "\n", + "## Takeaway\n", + "\n", + "On PneumoniaMNIST, a network built from butterfly layers keeps its Lipschitz\n", + "bound at exactly 1 and keeps the norm of the signal through 32 layers. It\n", + "certifies about two thirds of the test images at a radius of 0.5 at every depth\n", + "we tried. A dense network of the same shape loses its certificate as its bound\n", + "grows. A spectrally normalised one keeps the bound but loses the signal, and at\n", + "depth 32 it predicts one class. Each butterfly layer has 5,120 parameters instead\n", + "of more than a million, and the whole network is trained with\n", + "`GenericClassifier` like any other model of the library.\n", + "\n", + "The next example, [Certified Fine-Tuning with Butterfly\n", + "Adapters](orthogonal-certified-fine-tuning.md), starts from such a network and\n", + "adapts it to a new task without losing the certificate.\n", + "\n", + "## Citation\n", + "\n", + "This example follows *Quantum-inspired orthogonal adapters for certifiably robust\n", + "medical image classification* ([arXiv:2611.18775](https://arxiv.org/abs/2611.18775)),\n", + "which studies butterfly layers and butterfly adapters in certified classifiers of\n", + "medical images. The code of the paper is in\n", + "[eigenorbit/quantum-inspired-fine-tuning](https://github.com/eigenorbit/quantum-inspired-fine-tuning).\n", + "If you use these methods in your research, please cite the paper:\n", + "\n", + "```bibtex\n", + "@misc{tsurkan2026quantum,\n", + " title = {Quantum-inspired orthogonal adapters for certifiably robust medical image classification},\n", + " author = {Tsurkan, Olga and Domingo, Laia and Orlova, Victoria and Sagingalieva, Asel and Zalaudek, Iris and Caposiena Caro, Raffaele Dante},\n", + " year = {2026},\n", + " eprint = {2611.18775},\n", + " archivePrefix = {arXiv},\n", + " primaryClass = {cs.CV},\n", + " doi = {10.48550/arXiv.2611.18775},\n", + " url = {https://arxiv.org/abs/2611.18775}\n", + "}\n", + "```" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/examples/notebooks/orthogonal-qnn-classifier.ipynb b/examples/notebooks/orthogonal-qnn-classifier.ipynb new file mode 100644 index 0000000..323a124 --- /dev/null +++ b/examples/notebooks/orthogonal-qnn-classifier.ipynb @@ -0,0 +1,647 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0e692061c610", + "metadata": {}, + "source": [ + "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/eigenorbit/eigenkit/blob/main/examples/notebooks/orthogonal-qnn-classifier.ipynb)" + ] + }, + { + "cell_type": "code", + "id": "80b51eb17502", + "metadata": {}, + "source": [ + "%pip install -q \"eigenkit[torch,pennylane,viz]\"" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "69626de227ea", + "metadata": {}, + "source": [ + "# Orthogonal QNN as a Compact Classifier\n", + "\n", + "## What this example shows\n", + "\n", + "A quantum orthogonal neural network (Landman et al., *Quantum* 6, 881, 2022)\n", + "classifies data with three parts:\n", + "\n", + "1. a **unary loader** puts the input \\(x \\in \\mathbb{R}^n\\) into the amplitudes of\n", + " \\(n\\) qubits, one amplitude per qubit:\n", + " \\(\\lvert x \\rangle = \\sum_i \\frac{x_i}{\\lVert x \\rVert} \\lvert e_i \\rangle\\), where\n", + " \\(\\lvert e_i \\rangle\\) has a single 1 on qubit \\(i\\);\n", + "2. a network of **RBS gates** rotates the state. RBS gates keep the number of 1s\n", + " fixed, so the state stays a combination of the \\(n\\) unary states, and the\n", + " network acts on its amplitudes as an \\(n \\times n\\) orthogonal matrix \\(W\\);\n", + "3. a **measurement** finds the single 1 on qubit \\(i\\) with probability\n", + " \\(p_i = (Wx)_i^2 / \\lVert x \\rVert^2\\). The \\(p_i\\) are a probability distribution\n", + " over the qubits by construction.\n", + "\n", + "This example uses such a network as a binary classifier on medical images, and\n", + "compares it with three other models that see the same inputs: logistic\n", + "regression, a small classical network (MLP) and the variational quantum\n", + "classifier of the library, `HQNC`. Every model is trained by an estimator of the\n", + "library: `GenericClassifier` for the classical models and the orthogonal network,\n", + "`HQNC` for the variational one. See [Orthogonal\n", + "networks](../algorithms/orthogonal-networks.md) for the theory of RBS circuits and\n", + "the [user guide](../../docs/user-guide/orthogonal.md#from-trained-angles-to-a-circuit) for\n", + "exporting trained angles to a circuit.\n", + "\n", + "## The data\n", + "\n", + "[PneumoniaMNIST](https://medmnist.com/) (Yang et al., *Scientific Data* 10, 41,\n", + "2023) holds paediatric chest X-rays of \\(28 \\times 28\\) pixels, labelled normal or\n", + "pneumonia: 4,708 training images and 624 test images. The file comes from the\n", + "MedMNIST record on Zenodo (CC BY 4.0) and is downloaded once, about 4 MB, into\n", + "`~/.cache/medmnist`.\n", + "\n", + "A circuit of 8 qubits loads 8 numbers, so every image is reduced to 8 features\n", + "by a principal component analysis (PCA) fitted on the training images. Every\n", + "feature is then scaled to \\([0, 1]\\) over the training set, and test values are\n", + "clipped to stay non-negative.\n", + "\n", + "The scaling matters for the orthogonal network. The loader keeps only the\n", + "direction \\(x / \\lVert x \\rVert\\), and the measurement returns squares\n", + "\\((Wx)_i^2\\), so the network cannot tell \\(x\\) from \\(-x\\). Centred PCA features\n", + "carry much of the class in their signs, which would be lost. On \\([0, 1]\\) every\n", + "feature is non-negative, and the direction keeps what the classes need. `HQNC`\n", + "scales its inputs to \\([0, 1]\\) by itself, so all models see the same values." + ] + }, + { + "cell_type": "code", + "id": "cdb55d3e27d0", + "metadata": {}, + "source": [ + "import time\n", + "import urllib.request\n", + "from pathlib import Path\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.metrics import roc_auc_score\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "from eigenkit import HQNC, Circuit, GenericClassifier, OrthogonalQNN, PennyLaneConfig\n", + "from eigenkit.datasets import STYLE_COLORS, rc_params\n", + "from eigenkit.orthogonal import Topology, to_block, topology\n", + "from eigenkit.orthogonal.torch import Orthogonal\n", + "\n", + "URL = \"https://zenodo.org/records/10519652/files/{}.npz?download=1\"\n", + "FOLDER = Path.home() / \".cache\" / \"medmnist\"\n", + "\n", + "\n", + "def load_medmnist(name):\n", + " path = FOLDER / f\"{name}.npz\"\n", + " if not path.exists():\n", + " FOLDER.mkdir(parents=True, exist_ok=True)\n", + " urllib.request.urlretrieve(URL.format(name), path)\n", + " with np.load(path) as data:\n", + " return {\n", + " split: (\n", + " data[f\"{split}_images\"].reshape(len(data[f\"{split}_images\"]), -1) / 255,\n", + " data[f\"{split}_labels\"][:, 0],\n", + " )\n", + " for split in (\"train\", \"test\")\n", + " }\n", + "\n", + "\n", + "data = load_medmnist(\"pneumoniamnist\")\n", + "images_train, y_train = data[\"train\"]\n", + "images_test, y_test = data[\"test\"]\n", + "\n", + "n = 8\n", + "pca = PCA(n_components=n, random_state=0).fit(images_train)\n", + "scaler = MinMaxScaler().fit(pca.transform(images_train))\n", + "X_train = scaler.transform(pca.transform(images_train)).astype(np.float32)\n", + "X_test = np.clip(scaler.transform(pca.transform(images_test)), 0, None).astype(np.float32)\n", + "\n", + "print(f\"train {X_train.shape}, labels {np.bincount(y_train).tolist()}\")\n", + "print(f\"test {X_test.shape}, labels {np.bincount(y_test).tolist()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "4940e4f92378", + "metadata": {}, + "source": [ + "*Output recorded in the documentation:*\n", + "\n", + "```text\n", + "train (4708, 8), labels [1214, 3494]\n", + "test (624, 8), labels [234, 390]\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "82004dcfae78", + "metadata": {}, + "source": [ + "The images below are six training X-rays of each class (top), and the same\n", + "images rebuilt from their 8 principal components alone (bottom). The 8 numbers\n", + "keep the overall shape and brightness of the chest, not its details; this is all\n", + "that every model of the example sees." + ] + }, + { + "cell_type": "code", + "id": "3df9cdcf4fad", + "metadata": {}, + "source": [ + "classes = (\"normal\", \"pneumonia\")\n", + "shown = np.concatenate([np.flatnonzero(y_train == c)[:3] for c in (0, 1)])\n", + "rebuilt = pca.inverse_transform(pca.transform(images_train[shown]))\n", + "with plt.rc_context(rc_params(theme=\"light\")):\n", + " fig, axes = plt.subplots(2, 6, figsize=(9, 3.6))\n", + " for k, i in enumerate(shown):\n", + " axes[0, k].imshow(images_train[i].reshape(28, 28), cmap=\"gray\", vmin=0, vmax=1)\n", + " axes[1, k].imshow(rebuilt[k].reshape(28, 28), cmap=\"gray\", vmin=0, vmax=1)\n", + " axes[0, k].set_title(classes[y_train[i]], fontsize=10)\n", + " for ax in axes.flat:\n", + " ax.set_axis_off()\n", + " fig.tight_layout()\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "466d747ca1f1", + "metadata": {}, + "source": [ + "![png](../../docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_1_0_light.png)\n", + "\n", + "## The orthogonal classifier\n", + "\n", + "With \\(n = 8\\) qubits and two classes, the class is read from the two halves of\n", + "the qubits:\n", + "\n", + "\\[\n", + "P(\\text{pneumonia} \\mid x) = \\sum_{i=4}^{7} p_i = \\sum_{i=4}^{7} \\frac{(Wx)_i^2}{\\lVert x \\rVert^2},\n", + "\\]\n", + "\n", + "so every measurement of the circuit is one vote for a class.\n", + "\n", + "The circuit computes exactly \\((Wx)_i^2 / \\lVert x \\rVert^2\\), so the network can be\n", + "trained in this *matrix form*: the module `Orthogonal` holds the angles of the RBS\n", + "gates and builds \\(W\\) from them. Training then works with an \\(8 \\times 8\\) matrix\n", + "instead of simulating the \\(2^8 = 256\\) amplitudes of the circuit, and the trained\n", + "angles are copied into the circuit afterwards.\n", + "\n", + "The probability has no bias, and the classes are not balanced: 74% of the\n", + "training images show pneumonia. Two classical numbers, a scale \\(a\\) and an offset\n", + "\\(b\\), turn the probability into the logit that the cross-entropy needs,\n", + "\\(z = a \\, (P - \\tfrac{1}{2}) + b\\). They only move and sharpen the decision\n", + "threshold on \\(P\\); the ranking of the images, and so the AUC, comes from the\n", + "circuit alone.\n", + "\n", + "We use two layouts of the RBS gates on 8 qubits: the **butterfly**, 12 gates in\n", + "3 layers, and the **pyramid**, 28 gates, which connects every pair of qubits and\n", + "is the layout of Landman et al.\n", + "\n", + "Both are drawn below. Each link joins the two qubits that one RBS gate acts on,\n", + "and the gates in a column act at the same time, so the number of columns is the\n", + "depth of the circuit. The butterfly pairs qubits at distance 1, then 2, then 4,\n", + "which is why 3 layers reach every qubit from every other. The pyramid walks a\n", + "single pair across the register and back. The bottom panel is what one of those\n", + "links becomes on hardware." + ] + }, + { + "cell_type": "code", + "id": "7f6e4e23f26e", + "metadata": {}, + "source": [ + "def draw_layout(ax, name, title):\n", + " \"\"\"The RBS gates of a topology: one line per qubit, one link per gate.\n", + "\n", + " Gates of the same layer act at the same time; they are drawn a little apart\n", + " so that links which span the same wires stay readable.\n", + " \"\"\"\n", + " layers = topology(name, n).layers\n", + " width = len(layers) - 0.4\n", + " for q in range(n):\n", + " ax.plot([-0.45, width], [q, q], color=STYLE_COLORS[7], lw=1, zorder=0)\n", + " ax.text(-0.65, q, f\"$q_{q}$\", ha=\"right\", va=\"center\", fontsize=9)\n", + " for depth, layer in enumerate(layers):\n", + " spread = 0.13 * (len(layer) - 1)\n", + " for k, (a, b) in enumerate(sorted(layer)):\n", + " x = depth - spread / 2 + 0.13 * k if len(layer) > 1 else depth\n", + " ax.plot([x, x], [a, b], color=STYLE_COLORS[2], lw=2.2, zorder=1)\n", + " ax.plot([x, x], [a, b], \"o\", color=STYLE_COLORS[2], ms=5.5, zorder=2)\n", + " gates = sum(len(layer) for layer in layers)\n", + " ax.set_title(f\"{title} — {gates} RBS gates in {len(layers)} layers\", fontsize=10)\n", + " ax.set_xlim(-1.1, width + 0.2)\n", + " ax.set_ylim(n - 0.4, -0.9)\n", + " ax.set_axis_off()\n", + "\n", + "\n", + "with plt.rc_context(rc_params(theme=\"light\")):\n", + " fig, axes = plt.subplots(3, 1, figsize=(9.5, 8.0), height_ratios=(1.1, 1.1, 0.8))\n", + " draw_layout(axes[0], \"butterfly\", \"butterfly\")\n", + " draw_layout(axes[1], \"pyramid\", \"pyramid\")\n", + " one_gate = Circuit([to_block(Topology(2, (((0, 1),),)), [0.3])])\n", + " one_gate.draw_mpl(style=\"eigen-universal\", ax=axes[2])\n", + " axes[2].set_title(\"one RBS gate, as a backend runs it\", fontsize=10)\n", + " fig.tight_layout()\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "05726860800d", + "metadata": {}, + "source": [ + "![png](../../docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_2_0_light.png)" + ] + }, + { + "cell_type": "code", + "id": "e11f6114900d", + "metadata": {}, + "source": [ + "class OrthogonalClassifier(nn.Module):\n", + " \"\"\"P(class 1) from the second half of the qubits, then a scale and an offset.\"\"\"\n", + "\n", + " def __init__(self, n, topology):\n", + " super().__init__()\n", + " self.n = n\n", + " self.rotation = Orthogonal(n, topology, init=\"random\", std=1.0)\n", + " self.scale = nn.Parameter(torch.tensor(4.0))\n", + " self.offset = nn.Parameter(torch.tensor(0.0))\n", + "\n", + " def probability(self, x):\n", + " p = self.rotation(x) ** 2 / (x**2).sum(dim=1, keepdim=True).clamp_min(1e-12)\n", + " return p[:, self.n // 2 :].sum(dim=1)\n", + "\n", + " def forward(self, x):\n", + " z = self.scale * (self.probability(x) - 0.5) + self.offset\n", + " return torch.stack([-z / 2, z / 2], dim=1)\n", + "\n", + "\n", + "def make(name, seed):\n", + " common = dict(\n", + " epochs=30, batch_size=64, lr=0.02, show_progress=False, random_state=seed\n", + " )\n", + " if name == \"logistic regression\":\n", + " return GenericClassifier(nn.Linear(n, 2), in_features=n, **common)\n", + " if name == \"MLP [8, 4, 2]\":\n", + " mlp = nn.Sequential(nn.Linear(n, 4), nn.Sigmoid(), nn.Linear(4, 2))\n", + " return GenericClassifier(mlp, in_features=n, **common)\n", + " if name == \"HQNC\":\n", + " return HQNC(in_features=n, n_qubits=n, depth=2, n_classes=2, **common)\n", + " topology = name.split()[1]\n", + " return GenericClassifier(OrthogonalClassifier(n, topology), in_features=n, **common)\n", + "\n", + "\n", + "names = (\n", + " \"logistic regression\",\n", + " \"MLP [8, 4, 2]\",\n", + " \"HQNC\",\n", + " \"orthogonal butterfly\",\n", + " \"orthogonal pyramid\",\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "1234292a3b96", + "metadata": {}, + "source": [ + "## Size of every model\n", + "\n", + "The next cell counts the trainable parameters of every model and, for the quantum\n", + "ones, the gates of the circuit. Each RBS gate is compiled to two CNOTs, and the\n", + "loader adds \\(n - 1 = 7\\) more RBS gates. The butterfly uses the parallel loader,\n", + "which needs a power of two and is 3 layers deep; the pyramid uses the diagonal\n", + "loader, which works for any \\(n\\)." + ] + }, + { + "cell_type": "code", + "id": "3c531842e8ff", + "metadata": {}, + "source": [ + "def count(model):\n", + " return sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "\n", + "\n", + "probe = HQNC(\n", + " in_features=n, n_qubits=n, depth=2, n_classes=2, epochs=1, show_progress=False\n", + ")\n", + "probe.fit(X_train[:8], np.arange(8) % 2)\n", + "circuits = {\n", + " \"HQNC\": probe.model_[1].circuit.spec,\n", + " \"orthogonal butterfly\": OrthogonalQNN(n, \"butterfly\", loader=\"parallel\").circuit.spec,\n", + " \"orthogonal pyramid\": OrthogonalQNN(n, \"pyramid\", loader=\"diagonal\").circuit.spec,\n", + "}\n", + "print(\"model parameters gates CNOTs\")\n", + "for name in names:\n", + " if name == \"HQNC\":\n", + " size = count(probe.model_)\n", + " else:\n", + " size = count(make(name, 0).model)\n", + " spec = circuits.get(name)\n", + " gates = (\n", + " f\"{len(spec.gates):6d} {sum(g.name == 'CNOT' for g in spec.gates):6d}\"\n", + " if spec\n", + " else \" - -\"\n", + " )\n", + " print(f\"{name:22s} {size:10d} {gates}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "7717e2a48bb9", + "metadata": {}, + "source": [ + "*Output recorded in the documentation:*\n", + "\n", + "```text\n", + "model parameters gates CNOTs\n", + "logistic regression 18 - -\n", + "MLP [8, 4, 2] 46 - -\n", + "HQNC 34 38 14\n", + "orthogonal butterfly 14 153 38\n", + "orthogonal pyramid 30 281 70\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "e4ed92398fd9", + "metadata": {}, + "source": [ + "The orthogonal butterfly is the smallest model: 12 angles, plus the scale and\n", + "the offset. The pyramid has 28 angles, the variational classifier `HQNC` has 16\n", + "circuit weights and a linear layer of 18 after the circuit, and the MLP has 46\n", + "weights. In gates the order is reversed. Every RBS gate is compiled into two\n", + "CNOTs and single-qubit rotations, and the loader adds its own RBS gates, so the\n", + "orthogonal circuits are deeper than the circuit of `HQNC`. The butterfly needs\n", + "about half the CNOTs of the pyramid.\n", + "\n", + "`HQNC` builds a circuit of a different kind. It writes each of the 8 features\n", + "into the angle of an `RX` rotation, follows them with trainable `RY` rotations\n", + "and a ladder of CNOTs, and measures every qubit; a linear layer then turns those\n", + "expectations into the two logits." + ] + }, + { + "cell_type": "code", + "id": "fcd59e6f9aba", + "metadata": {}, + "source": [ + "with plt.rc_context(rc_params(theme=\"light\")):\n", + " fig, ax = plt.subplots(figsize=(11, 4.2))\n", + " probe.model_[1].circuit.draw_mpl(style=\"eigen-universal\", ax=ax)\n", + " ax.set_title(\"HQNC — two variational layers on 8 qubits\", fontsize=10)\n", + " fig.tight_layout()\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "711b6f4bbb40", + "metadata": {}, + "source": [ + "![png](../../docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_5_0_light.png)\n", + "\n", + "The encoded features (`x_0` to `x_7`) and the 16 trainable weights (`w_0` to\n", + "`w_15`) are visible in the boxes. Nothing here keeps the number of 1s fixed, so\n", + "the state leaves the unary subspace and the circuit has to be simulated over all\n", + "\\(2^8\\) amplitudes, which is why it is the slowest model to train.\n", + "\n", + "## Training and results\n", + "\n", + "Every model is trained with the same settings: Adam with a learning rate of\n", + "0.02, batches of 64, 30 epochs, cross-entropy, and three seeds. We report the\n", + "area under the ROC curve (AUC), which measures how well the model ranks the\n", + "images, and the accuracy, on the test set, after the last epoch." + ] + }, + { + "cell_type": "code", + "id": "6efb087548c1", + "metadata": {}, + "source": [ + "results, fitted = {}, {}\n", + "for name in names:\n", + " start = time.time()\n", + " scores = []\n", + " for seed in range(3):\n", + " clf = make(name, seed).fit(X_train, y_train)\n", + " probability = clf.predict_proba(X_test)[:, 1]\n", + " scores.append(\n", + " (roc_auc_score(y_test, probability), (clf.predict(X_test) == y_test).mean())\n", + " )\n", + " fitted[name, seed] = clf\n", + " results[name] = np.array(scores)\n", + " seconds = (time.time() - start) / 3\n", + " auc, acc = results[name].mean(axis=0)\n", + " auc_sd, acc_sd = results[name].std(axis=0)\n", + " print(\n", + " f\"{name:22s} AUC {auc:.3f} ± {auc_sd:.3f} accuracy {acc:.3f} ± {acc_sd:.3f}\"\n", + " f\" {seconds:5.0f} s per fit\"\n", + " )" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "cebd9fe05e35", + "metadata": {}, + "source": [ + "*Output recorded in the documentation:*\n", + "\n", + "```text\n", + "logistic regression AUC 0.887 ± 0.000 accuracy 0.796 ± 0.003 2 s per fit\n", + "MLP [8, 4, 2] AUC 0.889 ± 0.001 accuracy 0.781 ± 0.010 3 s per fit\n", + "HQNC AUC 0.908 ± 0.006 accuracy 0.823 ± 0.017 180 s per fit\n", + "orthogonal butterfly AUC 0.886 ± 0.001 accuracy 0.800 ± 0.011 5 s per fit\n", + "orthogonal pyramid AUC 0.894 ± 0.008 accuracy 0.818 ± 0.016 11 s per fit\n", + "```" + ] + }, + { + "cell_type": "code", + "id": "93afb67dc86a", + "metadata": {}, + "source": [ + "with plt.rc_context(rc_params(theme=\"light\")):\n", + " fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))\n", + " positions = np.arange(len(names))\n", + " colors = [STYLE_COLORS[k] for k in (6, 4, 0, 2, 3)]\n", + " for ax, column, title in zip(axes, (0, 1), (\"Test AUC\", \"Test accuracy\")):\n", + " means = [results[name][:, column].mean() for name in names]\n", + " errors = [results[name][:, column].std() for name in names]\n", + " ax.bar(positions, means, 0.6, yerr=errors, capsize=3, color=colors)\n", + " for k, (m, e) in enumerate(zip(means, errors)):\n", + " ax.text(k, m + e + 0.006, f\"{m:.3f}\", ha=\"center\", va=\"bottom\", fontsize=9)\n", + " ax.set_xticks(\n", + " positions, [name.replace(\" \", \"\\n\", 1) for name in names], fontsize=9\n", + " )\n", + " ax.set_ylim(0.6, 0.97)\n", + " ax.set_title(title)\n", + " fig.tight_layout()\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "fdb414653c7e", + "metadata": {}, + "source": [ + "![png](../../docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_7_0_light.png)\n", + "\n", + "The orthogonal pyramid ranks the images better than the two classical models,\n", + "with an AUC of 0.894 against 0.887 and 0.889. It is also more accurate, 0.818\n", + "against 0.796 and 0.781. The butterfly matches logistic regression, AUC 0.886\n", + "and accuracy 0.800 against 0.887 and 0.796, with 14 parameters, fewer than any\n", + "other model.\n", + "\n", + "`HQNC` is the best model here, with an AUC of 0.908 and an accuracy of 0.823. Its\n", + "accuracy is that of the pyramid within the spread over the seeds (±0.017 and\n", + "±0.016). It is also the most expensive to train: minutes per fit, against seconds for\n", + "the orthogonal networks (the last column; the times depend on the machine).\n", + "`HQNC` is trained by simulating its circuit, while the orthogonal network is\n", + "trained in its matrix form, which gives the output of the circuit exactly\n", + "without simulating the quantum state.\n", + "\n", + "## From infinite shots to a real device\n", + "\n", + "The orthogonal networks were trained in their matrix form, which returns\n", + "\\((Wx)_i^2 / \\lVert x \\rVert^2\\) exactly. Those are the probabilities a circuit\n", + "would give if every image were measured infinitely many times. A real device\n", + "returns samples instead. Each shot of the orthogonal circuit finds the single 1\n", + "on one qubit, and the share of shots that land on the second half of the qubits\n", + "estimates \\(P(\\text{pneumonia})\\).\n", + "\n", + "The cell below copies the trained angles of the pyramid of seed 0 into\n", + "`OrthogonalQNN`, runs it on PennyLane's simulator with a finite number of shots,\n", + "which samples as a noiseless device would, and applies the same scale and offset.\n", + "The dashed line is the exact probability, the infinite-shot limit that the matrix\n", + "form computes." + ] + }, + { + "cell_type": "code", + "id": "5d90b4c36719", + "metadata": {}, + "source": [ + "def with_shots(model, shots):\n", + " \"\"\"AUC and accuracy when P is estimated from a finite number of shots.\"\"\"\n", + " config = PennyLaneConfig(device_name=\"default.qubit\", shots=shots)\n", + " sampled = OrthogonalQNN(n, \"pyramid\", loader=\"diagonal\", provider=config)\n", + " with torch.no_grad():\n", + " sampled.circuit.weights.copy_(model.rotation.theta.double())\n", + " p = sampled(torch.tensor(X_test, dtype=torch.float64))[:, n // 2 :].sum(dim=1)\n", + " z = model.scale * (p.float() - 0.5) + model.offset\n", + " predictions = (z > 0).numpy().astype(int)\n", + " return roc_auc_score(y_test, p.numpy()), (predictions == y_test).mean()\n", + "\n", + "\n", + "model = fitted[\"orthogonal pyramid\", 0].model_\n", + "exact = results[\"orthogonal pyramid\"][0]\n", + "np.random.seed(0) # PennyLane's default.qubit samples from NumPy's global generator\n", + "shot_counts = (10, 30, 100, 300, 1000, 3000)\n", + "measured = np.array([with_shots(model, s) for s in shot_counts])\n", + "\n", + "with plt.rc_context(rc_params(theme=\"light\")):\n", + " fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))\n", + " for ax, column, title, value in zip(\n", + " axes, (0, 1), (\"Test AUC\", \"Test accuracy\"), exact\n", + " ):\n", + " ax.axhline(\n", + " value, color=STYLE_COLORS[7], linestyle=\"--\", label=\"exact (infinite shots)\"\n", + " )\n", + " ax.plot(\n", + " shot_counts,\n", + " measured[:, column],\n", + " marker=\"o\",\n", + " color=STYLE_COLORS[2],\n", + " label=\"sampled\",\n", + " )\n", + " ax.set_xscale(\"log\")\n", + " ax.set_xticks(shot_counts, [str(s) for s in shot_counts])\n", + " ax.set_xlabel(\"shots per image\")\n", + " ax.set_title(title)\n", + " axes[0].legend(fontsize=9, loc=\"lower right\")\n", + " fig.tight_layout()\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "93b2220cad29", + "metadata": {}, + "source": [ + "![png](../../docs/examples/orthogonal_qnn_classifier_files/orthogonal_qnn_classifier_8_0_light.png)\n", + "\n", + "Both curves climb towards the dashed line and are close to it by a thousand\n", + "shots: an AUC of 0.888 and an accuracy of 0.793, against 0.895 and 0.806 exactly,\n", + "and 0.893 and 0.800 with three thousand. Below a hundred shots the estimate of\n", + "\\(P\\) is too noisy for the images near the threshold, and both fall away quickly\n", + "— at ten shots the AUC is 0.727.\n", + "\n", + "That the curves converge to the dashed line is also the check that the circuit\n", + "computes what was trained: the matrix form and the sampled circuit agree once\n", + "enough shots are taken, so training on the matrix and running on a device are the\n", + "same model. The shots are random, and `np.random.seed(0)` fixes them because\n", + "PennyLane's `default.qubit` draws its samples from NumPy's global generator;\n", + "another seed moves the points slightly. Each shot is a vote for one class, so how\n", + "many are needed depends on how close \\(P\\) is to the threshold, not on the number\n", + "of qubits.\n", + "\n", + "## Takeaway\n", + "\n", + "On PneumoniaMNIST reduced to 8 features, an orthogonal network of RBS gates,\n", + "trained with `GenericClassifier` like any other model, is as good as or better\n", + "than logistic regression and an MLP with the same inputs. It needs only 14 to 30\n", + "parameters. The pyramid reaches the accuracy of the variational classifier\n", + "`HQNC` within the spread over the seeds, in a fraction of its training time,\n", + "because its matrix form gives the output of the circuit exactly, without\n", + "simulating the quantum state. Its output is a probability distribution over the\n", + "qubits by construction, so each shot is a vote for a class: measured on a\n", + "simulator, 1,000 shots per image come within about 0.01 of the exact AUC and\n", + "accuracy, and 3,000 within 0.006. The price is the depth of the circuit: 38 to\n", + "70 CNOTs against 14 for `HQNC`." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/mkdocs.yml b/mkdocs.yml index f8c8f4c..9bbee3a 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -157,6 +157,10 @@ nav: - Benchmark on Iris: examples/benchmark-iris.md - Reservoir Computing: - Quantum Reservoir Memory: examples/reservoir-memory.md + - Orthogonal Networks: + - Certified Classifier from Orthogonal Layers: examples/orthogonal-certified-training.md + - Certified Fine-Tuning with Butterfly Adapters: examples/orthogonal-certified-fine-tuning.md + - Orthogonal QNN as a Compact Classifier: examples/orthogonal-qnn-classifier.md - Quantum Algorithms: - MaxCut with QAOA: examples/qaoa-max-cut.md - Ground-State Energy with VQE: examples/vqe-fermi-hubbard.md diff --git a/tools/docs-checks/README.md b/tools/docs-checks/README.md index ce61be1..4037e79 100644 --- a/tools/docs-checks/README.md +++ b/tools/docs-checks/README.md @@ -34,7 +34,7 @@ dashes end up mid-sentence on the page. `find_unfenced_code.py` also checks markdown structure and catches this, so run both after using the rewrapper. `build_example_notebooks.py` is the other tool. It rebuilds -`examples/notebooks/*.ipynb` from the sixteen pages in `docs/examples/`, one +`examples/notebooks/*.ipynb` from the nineteen pages in `docs/examples/`, one notebook per page, prose as markdown cells and every ```` ```python ```` block as an empty code cell ready to run. The pages are the source of truth — they are what the site publishes and what the checks above run against — so the notebooks