ARotting commited on
Commit
c33f5fa
·
verified ·
1 Parent(s): b70571b

Publish Held-out digits for capsule robustness evaluation

Browse files
Files changed (6) hide show
  1. README.md +31 -0
  2. source/app.py +99 -0
  3. source/model.py +55 -0
  4. source/requirements.txt +9 -0
  5. source/train.py +212 -0
  6. test.parquet +3 -0
README.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Capsule Pocket
3
+ emoji: 💊
4
+ colorFrom: purple
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: "6.5.1"
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # Capsule Pocket
13
+
14
+ Capsule Pocket trains seven primary capsules and ten eight-dimensional digit
15
+ capsules with three rounds of routing by agreement. An ordinary MLP with exactly
16
+ the same 4,060 trainable parameters is the control.
17
+
18
+ The benchmark separates clean accuracy from one-pixel translation and center
19
+ occlusion robustness. The Space exposes the ten digit-capsule vector lengths for
20
+ each transformed input.
21
+
22
+ ## Verified local result
23
+
24
+ At exactly 4,060 parameters, capsules reached 97.04% clean accuracy versus 97.41%
25
+ for the MLP. They improved one-pixel translation accuracy from 44.72% to 46.20%
26
+ and center-occlusion accuracy from 79.63% to 82.22%.
27
+
28
+ ```bash
29
+ uv run python projects/capsule-pocket/train.py
30
+ uv run pytest tests/test_capsule_pocket.py
31
+ ```
source/app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import gradio as gr
7
+ import numpy as np
8
+ import pandas as pd
9
+ import plotly.graph_objects as go
10
+ import torch
11
+ from model import DynamicRoutingCapsuleNet, MatchedMLP
12
+ from PIL import Image
13
+ from safetensors.torch import load_file
14
+
15
+ PROJECT_DIR = Path(__file__).resolve().parent
16
+ ARTIFACT_DIR = PROJECT_DIR / "artifacts" / "capsule-pocket"
17
+ FRAME = pd.read_parquet(PROJECT_DIR / "data" / "test.parquet")
18
+ REPORT = json.loads((ARTIFACT_DIR / "evaluation.json").read_text(encoding="utf-8"))
19
+ CAPSULE = DynamicRoutingCapsuleNet()
20
+ CAPSULE.load_state_dict(load_file(ARTIFACT_DIR / "capsule.safetensors"))
21
+ CAPSULE.eval()
22
+ MLP = MatchedMLP()
23
+ MLP.load_state_dict(load_file(ARTIFACT_DIR / "matched_mlp.safetensors"))
24
+ MLP.eval()
25
+
26
+
27
+ @torch.inference_mode()
28
+ def inspect_capsules(
29
+ index: int,
30
+ vertical: int,
31
+ horizontal: int,
32
+ occlude: bool,
33
+ ) -> tuple[Image.Image, go.Figure, dict]:
34
+ row = FRAME.iloc[int(index) % len(FRAME)]
35
+ image = torch.from_numpy(np.asarray(row["image"], dtype=np.float32) / 16).reshape(
36
+ 8, 8
37
+ )
38
+ image = torch.roll(image, (int(vertical), int(horizontal)), (0, 1))
39
+ if vertical > 0:
40
+ image[: int(vertical)] = 0
41
+ elif vertical < 0:
42
+ image[int(vertical) :] = 0
43
+ if horizontal > 0:
44
+ image[:, : int(horizontal)] = 0
45
+ elif horizontal < 0:
46
+ image[:, int(horizontal) :] = 0
47
+ if occlude:
48
+ image[3:5, 3:5] = 0
49
+ pixels = image.reshape(1, 64)
50
+ _, lengths = CAPSULE(pixels)
51
+ mlp_logits = MLP(pixels)
52
+ figure = go.Figure(go.Bar(x=list(range(10)), y=lengths[0].numpy()))
53
+ figure.update_layout(
54
+ template="plotly_dark",
55
+ title="Digit-capsule vector lengths",
56
+ xaxis_title="Class",
57
+ yaxis_title="Length",
58
+ )
59
+ rendered = Image.fromarray(
60
+ image.mul(255).to(torch.uint8).numpy(), mode="L"
61
+ ).resize((512, 512), Image.Resampling.NEAREST)
62
+ metrics = {
63
+ "true_label": int(row["label"]),
64
+ "capsule_prediction": int(lengths.argmax(1)),
65
+ "mlp_prediction": int(mlp_logits.argmax(1)),
66
+ "verified_capsule_translation_accuracy": REPORT["results"][
67
+ "dynamic_routing_capsule"
68
+ ]["one_pixel_translation"]["accuracy"],
69
+ }
70
+ return rendered, figure, metrics
71
+
72
+
73
+ with gr.Blocks(title="Capsule Pocket") as demo:
74
+ gr.Markdown(
75
+ "# Capsule Pocket\n"
76
+ "Inspect dynamic-routing capsule lengths beside an exactly parameter-matched "
77
+ "MLP under translation and occlusion."
78
+ )
79
+ with gr.Row():
80
+ index = gr.Slider(0, len(FRAME) - 1, value=8, step=1, label="Test digit")
81
+ vertical = gr.Slider(-1, 1, value=0, step=1, label="Vertical shift")
82
+ horizontal = gr.Slider(-1, 1, value=0, step=1, label="Horizontal shift")
83
+ occlude = gr.Checkbox(False, label="Center occlusion")
84
+ initial = inspect_capsules(8, 0, 0, False)
85
+ with gr.Row():
86
+ image = gr.Image(value=initial[0], label="Input")
87
+ chart = gr.Plot(value=initial[1], label="Capsule lengths")
88
+ metrics = gr.JSON(value=initial[2], label="Matched prediction")
89
+ button = gr.Button("Route capsules", variant="primary")
90
+ button.click(
91
+ inspect_capsules,
92
+ inputs=[index, vertical, horizontal, occlude],
93
+ outputs=[image, chart, metrics],
94
+ )
95
+
96
+
97
+ if __name__ == "__main__":
98
+ demo.launch()
99
+
source/model.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+
7
+ def squash(vectors: torch.Tensor) -> torch.Tensor:
8
+ squared_norm = vectors.square().sum(dim=-1, keepdim=True)
9
+ scale = squared_norm / (1 + squared_norm)
10
+ return scale * vectors / torch.sqrt(squared_norm + 1e-8)
11
+
12
+
13
+ class DynamicRoutingCapsuleNet(nn.Module):
14
+ def __init__(self, routing_iterations: int = 3) -> None:
15
+ super().__init__()
16
+ self.routing_iterations = routing_iterations
17
+ self.primary = nn.Linear(64, 28)
18
+ self.transforms = nn.Parameter(torch.randn(7, 10, 4, 8) * 0.08)
19
+
20
+ def forward(self, pixels: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
21
+ primary = squash(torch.tanh(self.primary(pixels)).reshape(-1, 7, 4))
22
+ votes = torch.einsum("bpd,pcde->bpce", primary, self.transforms)
23
+ routing_logits = torch.zeros(
24
+ len(pixels),
25
+ 7,
26
+ 10,
27
+ device=pixels.device,
28
+ )
29
+ digit_capsules = None
30
+ for iteration in range(self.routing_iterations):
31
+ coupling = torch.softmax(routing_logits, dim=2)
32
+ digit_capsules = squash((coupling[..., None] * votes).sum(dim=1))
33
+ if iteration + 1 < self.routing_iterations:
34
+ agreement = (votes * digit_capsules[:, None]).sum(dim=-1)
35
+ routing_logits = routing_logits + agreement
36
+ assert digit_capsules is not None
37
+ return digit_capsules, digit_capsules.norm(dim=-1)
38
+
39
+
40
+ class MatchedMLP(nn.Module):
41
+ def __init__(self) -> None:
42
+ super().__init__()
43
+ self.network = nn.Sequential(
44
+ nn.Linear(64, 54),
45
+ nn.GELU(),
46
+ nn.Linear(54, 10),
47
+ )
48
+
49
+ def forward(self, pixels: torch.Tensor) -> torch.Tensor:
50
+ return self.network(pixels)
51
+
52
+
53
+ def parameter_count(model: nn.Module) -> int:
54
+ return sum(parameter.numel() for parameter in model.parameters())
55
+
source/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=5,<7
2
+ numpy>=2,<3
3
+ pandas>=2.3,<4
4
+ pillow>=11,<13
5
+ plotly>=6,<7
6
+ pyarrow>=21,<24
7
+ safetensors>=0.6,<1
8
+ torch>=2.7,<3
9
+
source/train.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import random
5
+ import shutil
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import torch
11
+ import trackio
12
+ from model import DynamicRoutingCapsuleNet, MatchedMLP, parameter_count
13
+ from safetensors.torch import save_file
14
+ from torch.nn import functional as F
15
+ from torch.utils.data import DataLoader, TensorDataset
16
+
17
+ PROJECT_DIR = Path(__file__).resolve().parent
18
+ ROOT_DIR = PROJECT_DIR.parents[1]
19
+ VISION_DATA = ROOT_DIR / "projects" / "tiny-vision-foundry" / "data"
20
+ ARTIFACT_DIR = PROJECT_DIR / "artifacts" / "capsule-pocket"
21
+ DATA_DIR = PROJECT_DIR / "data"
22
+ SEED = 2179
23
+
24
+
25
+ def load_split(name: str, shuffle: bool) -> DataLoader:
26
+ frame = pd.read_parquet(VISION_DATA / f"{name}.parquet")
27
+ pixels = np.stack(frame["image"].to_numpy()).astype(np.float32) / 16
28
+ labels = frame["label"].to_numpy(dtype=np.int64, copy=True)
29
+ return DataLoader(
30
+ TensorDataset(torch.from_numpy(pixels), torch.from_numpy(labels)),
31
+ batch_size=128,
32
+ shuffle=shuffle,
33
+ generator=torch.Generator().manual_seed(SEED),
34
+ )
35
+
36
+
37
+ def margin_loss(lengths: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
38
+ targets = F.one_hot(labels, 10).float()
39
+ positive = targets * F.relu(0.9 - lengths).square()
40
+ negative = 0.5 * (1 - targets) * F.relu(lengths - 0.1).square()
41
+ return (positive + negative).sum(dim=1).mean()
42
+
43
+
44
+ def translate(pixels: torch.Tensor, vertical: int, horizontal: int) -> torch.Tensor:
45
+ images = pixels.reshape(-1, 8, 8)
46
+ shifted = torch.roll(images, shifts=(vertical, horizontal), dims=(1, 2))
47
+ if vertical > 0:
48
+ shifted[:, :vertical] = 0
49
+ elif vertical < 0:
50
+ shifted[:, vertical:] = 0
51
+ if horizontal > 0:
52
+ shifted[:, :, :horizontal] = 0
53
+ elif horizontal < 0:
54
+ shifted[:, :, horizontal:] = 0
55
+ return shifted.reshape(-1, 64)
56
+
57
+
58
+ @torch.inference_mode()
59
+ def evaluate(
60
+ model: torch.nn.Module,
61
+ loader: DataLoader,
62
+ *,
63
+ capsule: bool,
64
+ corruption: str,
65
+ ) -> dict:
66
+ model.eval()
67
+ correct = 0
68
+ total = 0
69
+ for pixels, labels in loader:
70
+ if corruption == "translation":
71
+ variants = [
72
+ translate(pixels, 1, 0),
73
+ translate(pixels, -1, 0),
74
+ translate(pixels, 0, 1),
75
+ translate(pixels, 0, -1),
76
+ ]
77
+ pixels = torch.cat(variants)
78
+ labels = labels.repeat(4)
79
+ elif corruption == "occlusion":
80
+ images = pixels.reshape(-1, 8, 8).clone()
81
+ images[:, 3:5, 3:5] = 0
82
+ pixels = images.reshape(-1, 64)
83
+ scores = model(pixels)[1] if capsule else model(pixels)
84
+ correct += int((scores.argmax(1) == labels).sum())
85
+ total += len(labels)
86
+ return {"accuracy": correct / total, "examples": total}
87
+
88
+
89
+ def train_variant(
90
+ model: torch.nn.Module,
91
+ train_loader: DataLoader,
92
+ validation_loader: DataLoader,
93
+ *,
94
+ capsule: bool,
95
+ ) -> tuple[dict[str, torch.Tensor], int]:
96
+ optimizer = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-4)
97
+ best = -1.0
98
+ best_epoch = 0
99
+ best_state = None
100
+ for epoch in range(1, 121):
101
+ model.train()
102
+ for pixels, labels in train_loader:
103
+ if capsule:
104
+ _, lengths = model(pixels)
105
+ loss = margin_loss(lengths, labels)
106
+ else:
107
+ loss = F.cross_entropy(model(pixels), labels)
108
+ optimizer.zero_grad(set_to_none=True)
109
+ loss.backward()
110
+ optimizer.step()
111
+ validation = evaluate(
112
+ model,
113
+ validation_loader,
114
+ capsule=capsule,
115
+ corruption="clean",
116
+ )
117
+ if validation["accuracy"] > best:
118
+ best = validation["accuracy"]
119
+ best_epoch = epoch
120
+ best_state = {
121
+ name: value.detach().cpu().clone()
122
+ for name, value in model.state_dict().items()
123
+ }
124
+ if epoch == 1 or epoch % 10 == 0:
125
+ trackio.log(
126
+ {
127
+ "variant": "capsule" if capsule else "mlp",
128
+ "epoch": epoch,
129
+ "validation_accuracy": validation["accuracy"],
130
+ }
131
+ )
132
+ assert best_state is not None
133
+ return best_state, best_epoch
134
+
135
+
136
+ def main() -> None:
137
+ random.seed(SEED)
138
+ np.random.seed(SEED)
139
+ torch.manual_seed(SEED)
140
+ torch.set_num_threads(1)
141
+ train_loader = load_split("train", True)
142
+ validation_loader = load_split("validation", False)
143
+ test_loader = load_split("test", False)
144
+ capsule = DynamicRoutingCapsuleNet()
145
+ mlp = MatchedMLP()
146
+ assert parameter_count(capsule) == parameter_count(mlp) == 4_060
147
+ trackio.init(
148
+ project="capsule-pocket",
149
+ name="dynamic-routing-digits-v1",
150
+ config={
151
+ "parameters_per_model": 4_060,
152
+ "routing_iterations": capsule.routing_iterations,
153
+ "training_epochs": 120,
154
+ },
155
+ )
156
+ capsule_state, capsule_epoch = train_variant(
157
+ capsule, train_loader, validation_loader, capsule=True
158
+ )
159
+ mlp_state, mlp_epoch = train_variant(
160
+ mlp, train_loader, validation_loader, capsule=False
161
+ )
162
+ capsule.load_state_dict(capsule_state)
163
+ mlp.load_state_dict(mlp_state)
164
+ results = {}
165
+ for name, model, is_capsule, epoch in [
166
+ ("dynamic_routing_capsule", capsule, True, capsule_epoch),
167
+ ("matched_mlp", mlp, False, mlp_epoch),
168
+ ]:
169
+ results[name] = {
170
+ "parameters": parameter_count(model),
171
+ "best_epoch": epoch,
172
+ "clean": evaluate(model, test_loader, capsule=is_capsule, corruption="clean"),
173
+ "one_pixel_translation": evaluate(
174
+ model, test_loader, capsule=is_capsule, corruption="translation"
175
+ ),
176
+ "center_occlusion": evaluate(
177
+ model, test_loader, capsule=is_capsule, corruption="occlusion"
178
+ ),
179
+ }
180
+ report = {
181
+ "experiment": "Dynamic-routing capsule network versus matched MLP",
182
+ "results": results,
183
+ }
184
+ ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
185
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
186
+ save_file(capsule.state_dict(), ARTIFACT_DIR / "capsule.safetensors")
187
+ save_file(mlp.state_dict(), ARTIFACT_DIR / "matched_mlp.safetensors")
188
+ (ARTIFACT_DIR / "evaluation.json").write_text(
189
+ json.dumps(report, indent=2), encoding="utf-8"
190
+ )
191
+ shutil.copy2(VISION_DATA / "test.parquet", DATA_DIR / "test.parquet")
192
+ trackio.log(
193
+ {
194
+ "capsule_clean_accuracy": results["dynamic_routing_capsule"]["clean"][
195
+ "accuracy"
196
+ ],
197
+ "capsule_translation_accuracy": results["dynamic_routing_capsule"][
198
+ "one_pixel_translation"
199
+ ]["accuracy"],
200
+ "mlp_clean_accuracy": results["matched_mlp"]["clean"]["accuracy"],
201
+ "mlp_translation_accuracy": results["matched_mlp"][
202
+ "one_pixel_translation"
203
+ ]["accuracy"],
204
+ }
205
+ )
206
+ trackio.finish()
207
+ print(json.dumps(report, indent=2))
208
+
209
+
210
+ if __name__ == "__main__":
211
+ main()
212
+
test.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da32d63eead51a422f2a4584a823d9bb3c7e9e492de17a1a0c048ef0e2490bd1
3
+ size 140968