brittorch 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BritTorch contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include examples/train.py
2
+ include scripts/check_wheel.py
3
+ recursive-include tests *.py
@@ -0,0 +1,200 @@
1
+ Metadata-Version: 2.4
2
+ Name: brittorch
3
+ Version: 0.1.0
4
+ Summary: Deep Learning for His Majesty: a British-themed PyTorch wrapper
5
+ Author: BritTorch contributors
6
+ License-Expression: MIT
7
+ Keywords: pytorch,deep-learning,british,parody
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: torch>=2.1
19
+ Provides-Extra: dev
20
+ Requires-Dist: build>=1.0; extra == "dev"
21
+ Requires-Dist: pytest>=8.0; extra == "dev"
22
+ Requires-Dist: ruff>=0.6; extra == "dev"
23
+ Requires-Dist: twine>=5.0; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # BritTorch 🇬🇧
27
+
28
+ **Deep Learning for His Majesty.**
29
+ *All the power of PyTorch, none of the American spelling.*
30
+
31
+ BritTorch is a lightweight, humorous wrapper around PyTorch. It provides a few
32
+ British spellings and cultural aliases while PyTorch performs every tensor
33
+ operation, gradient calculation and optimiser update. The same gradients.
34
+ Better manners. No additional CUDA kernels were colonised during development.
35
+
36
+ BritTorch is an unofficial parody project. It is not affiliated with PyTorch,
37
+ Arm, Neuro-sama or the British government. It is not a separate deep learning
38
+ framework and does not improve numerical performance.
39
+
40
+ ## Installation
41
+
42
+ Python 3.10 or newer and a compatible PyTorch installation are required.
43
+
44
+ ```bash
45
+ uv venv
46
+ uv pip install brittorch
47
+ ```
48
+
49
+ For a local checkout, install the development dependencies with:
50
+
51
+ ```bash
52
+ uv sync --extra dev
53
+ ```
54
+
55
+ This resolves PyTorch as a runtime dependency. Follow the official PyTorch
56
+ installation guidance if your platform needs a particular CUDA or accelerator
57
+ build.
58
+
59
+ ## Keep Calm and Carry On Training
60
+
61
+ ```python
62
+ import brittorch as torch
63
+ from brittorch import nn, optimise, royal_archive
64
+ import brittorch.nn.functional as F
65
+
66
+ torch.royal_decree(42)
67
+ inputs = torch.british_weather(64, 8)
68
+ targets = (inputs[:, 0] > 0).long()
69
+
70
+ model = nn.Sequential(nn.Linear(8, 16), nn.StiffUpperLip(), nn.Linear(16, 2))
71
+ optimiser = optimise.AdamSmith(model.parameters(), lr=1e-2)
72
+
73
+ for _ in range(20):
74
+ optimiser.forgive_and_forget()
75
+ loss = F.cross_entropy(model(inputs), targets)
76
+ loss.backward()
77
+ optimiser.carry_on()
78
+
79
+ with torch.tea_break():
80
+ prediction = model(inputs).argmax(dim=1)
81
+
82
+ royal_archive.preserve(model.state_dict(), "his_majesty.pt")
83
+ ```
84
+
85
+ The full [synthetic training example](examples/train.py) prints its starting
86
+ and final loss, training accuracy and checkpoint path. It requires no dataset
87
+ download. Run it with `uv run --extra dev python examples/train.py`.
88
+
89
+ ## API guide
90
+
91
+ All ordinary PyTorch names remain available through the corresponding
92
+ BritTorch module. The British names below are direct aliases unless otherwise
93
+ noted; their arguments, return values, tensor types, devices, dtypes and
94
+ autograd behaviour come from PyTorch.
95
+
96
+ | PyTorch | BritTorch | Reference |
97
+ | --- | --- | --- |
98
+ | `torch.cat` | `torch.unite` | United Kingdom |
99
+ | `torch.clone` | `torch.dolly` | Dolly the sheep |
100
+ | `torch.roll` | `torch.sausage_roll` | British cuisine |
101
+ | `torch.sort` | `torch.queue` | Queuing culture |
102
+ | `torch.randn` | `torch.british_weather` | Unpredictable weather |
103
+ | `torch.no_grad` | `torch.tea_break` | A short pause for tea |
104
+ | `torch.manual_seed` | `torch.royal_decree` | Royal decrees |
105
+ | `torch.quantize_per_tensor` | `torch.quantise_per_tensor` | British spelling |
106
+ | `torch.quantize_per_channel` | `torch.quantise_per_channel` | British spelling |
107
+ | `torch.optim` | `torch.optimise` | British spelling |
108
+ | `torch.optim.Optimizer` | `optimise.Optimiser` | British spelling |
109
+ | `nn.Module` | `nn.NeuroSama` | A nod to Neuro-sama |
110
+ | `nn.Dropout` | `nn.Brexit` | A departure during training |
111
+ | `nn.ReLU` | `nn.StiffUpperLip` | Keep calm |
112
+ | `nn.BatchNorm1d/2d/3d` | `nn.BatchNormalisation1d/2d/3d` | British spelling |
113
+ | `nn.LayerNorm` | `nn.LayerNormalisation` | British spelling |
114
+ | `nn.GroupNorm` | `nn.GroupNormalisation` | British spelling |
115
+ | `F.normalize` | `F.normalise` | British spelling |
116
+ | `torch.load` | `british_museum.acquire` | Checkpoint loading |
117
+ | `torch.save` | `royal_archive.preserve` | Checkpoint saving |
118
+ | `torch.hub.load` | `east_india_company.import_goods` | Explicit Hub loading |
119
+
120
+ `optimise.AdamSmith` subclasses PyTorch's `Adam`. Its `carry_on()` calls
121
+ `step()` and `forgive_and_forget()` calls `zero_grad()`, including PyTorch's
122
+ normal hooks. The original methods and state dictionaries still work.
123
+
124
+ > AdamSmith uses the invisible hand to guide your gradients towards the minimum.
125
+ >
126
+ > Global convergence is not guaranteed, much like the British economy.
127
+
128
+ Adam actually stands for **Adaptive Moment Estimation** and has no historical
129
+ relationship with Adam Smith.
130
+
131
+ > Acquired artefacts are compatible with PyTorch, although the British Museum
132
+ > may be reluctant to return them.
133
+
134
+ The checkpoint and Hub names use PyTorch's functions directly. They do not
135
+ perform extra file access, start downloads on import or alter PyTorch's loading
136
+ defaults. Hub downloads occur only when you explicitly call `import_goods()`
137
+ with a source that requires them. Follow PyTorch's usual guidance for loading
138
+ checkpoints from untrusted sources.
139
+
140
+ ## Architecture greeting
141
+
142
+ On first import, BritTorch reads `platform.machine()` and writes a brief
143
+ greeting to standard error. ARM is preferred. x86 is tolerated. ARM, ARM64,
144
+ AArch64, x86, x86-64, AMD64, RISC-V and unfamiliar machines all use precisely
145
+ the same PyTorch computation. Set `BRITTORCH_QUIET=1` to suppress the greeting.
146
+ It is also suppressed in recognised multiprocessing workers and non-zero
147
+ distributed ranks. Rank detection uses common launcher environment variables;
148
+ unusual launchers may need the quiet setting.
149
+
150
+ Exceptions are passed through unchanged. If you explicitly want a humorous
151
+ aside while showing an error, call `brittorch.format_british_error(error)`.
152
+ For example, a missing file still begins with the original
153
+ `FileNotFoundError` and message.
154
+
155
+ ## Compatibility and testing
156
+
157
+ BritTorch is intended for ordinary PyTorch tensor and model code. It forwards
158
+ unknown attributes to PyTorch and exposes unchanged `nn` and `optimise`
159
+ attributes, including `Transformer`, `Embedding` and `MultiheadAttention`.
160
+ Python submodule imports are provided for the documented BritTorch modules;
161
+ arbitrary nested `torch.*` import paths are not mirrored. Third-party tools
162
+ that inspect module identity or depend on a particular PyTorch import path may
163
+ need the original `torch` import. Complete ecosystem compatibility has not
164
+ been established.
165
+
166
+ ```bash
167
+ uv run --extra dev pytest
168
+ uv run --extra dev ruff check .
169
+ ```
170
+
171
+ CPU tests cover aliases, gradients, optimisers, checkpoints and import paths.
172
+ The CUDA preservation test runs only when CUDA is available.
173
+
174
+ ## Build and release
175
+
176
+ ```bash
177
+ uv build --no-sources
178
+ uv run --extra dev python -m twine check dist/*
179
+ uv venv .venv-wheel
180
+ uv pip install --python .venv-wheel/bin/python dist/*.whl
181
+ BRITTORCH_QUIET=1 .venv-wheel/bin/python scripts/check_wheel.py
182
+ ```
183
+
184
+ The isolated wheel check installs PyTorch and may involve a substantial
185
+ download. Run it yourself when preparing a release.
186
+ Publishing is manual and requires your own PyPI credentials:
187
+
188
+ ```bash
189
+ UV_PUBLISH_TOKEN="<testpypi-token>" uv publish --publish-url https://test.pypi.org/legacy/ dist/*
190
+ UV_PUBLISH_TOKEN="<pypi-token>" uv publish dist/*
191
+ ```
192
+
193
+ Check the package name and version before publishing. The initial version is
194
+ `0.1.0`; subsequent releases should follow semantic versioning.
195
+
196
+ ## Contributing
197
+
198
+ Please keep additions small, test them against the corresponding PyTorch API,
199
+ and use British English in documentation and custom messages. Bugs, focused
200
+ improvements and tasteful jokes are welcome. Make Britain differentiate again.
@@ -0,0 +1,175 @@
1
+ # BritTorch 🇬🇧
2
+
3
+ **Deep Learning for His Majesty.**
4
+ *All the power of PyTorch, none of the American spelling.*
5
+
6
+ BritTorch is a lightweight, humorous wrapper around PyTorch. It provides a few
7
+ British spellings and cultural aliases while PyTorch performs every tensor
8
+ operation, gradient calculation and optimiser update. The same gradients.
9
+ Better manners. No additional CUDA kernels were colonised during development.
10
+
11
+ BritTorch is an unofficial parody project. It is not affiliated with PyTorch,
12
+ Arm, Neuro-sama or the British government. It is not a separate deep learning
13
+ framework and does not improve numerical performance.
14
+
15
+ ## Installation
16
+
17
+ Python 3.10 or newer and a compatible PyTorch installation are required.
18
+
19
+ ```bash
20
+ uv venv
21
+ uv pip install brittorch
22
+ ```
23
+
24
+ For a local checkout, install the development dependencies with:
25
+
26
+ ```bash
27
+ uv sync --extra dev
28
+ ```
29
+
30
+ This resolves PyTorch as a runtime dependency. Follow the official PyTorch
31
+ installation guidance if your platform needs a particular CUDA or accelerator
32
+ build.
33
+
34
+ ## Keep Calm and Carry On Training
35
+
36
+ ```python
37
+ import brittorch as torch
38
+ from brittorch import nn, optimise, royal_archive
39
+ import brittorch.nn.functional as F
40
+
41
+ torch.royal_decree(42)
42
+ inputs = torch.british_weather(64, 8)
43
+ targets = (inputs[:, 0] > 0).long()
44
+
45
+ model = nn.Sequential(nn.Linear(8, 16), nn.StiffUpperLip(), nn.Linear(16, 2))
46
+ optimiser = optimise.AdamSmith(model.parameters(), lr=1e-2)
47
+
48
+ for _ in range(20):
49
+ optimiser.forgive_and_forget()
50
+ loss = F.cross_entropy(model(inputs), targets)
51
+ loss.backward()
52
+ optimiser.carry_on()
53
+
54
+ with torch.tea_break():
55
+ prediction = model(inputs).argmax(dim=1)
56
+
57
+ royal_archive.preserve(model.state_dict(), "his_majesty.pt")
58
+ ```
59
+
60
+ The full [synthetic training example](examples/train.py) prints its starting
61
+ and final loss, training accuracy and checkpoint path. It requires no dataset
62
+ download. Run it with `uv run --extra dev python examples/train.py`.
63
+
64
+ ## API guide
65
+
66
+ All ordinary PyTorch names remain available through the corresponding
67
+ BritTorch module. The British names below are direct aliases unless otherwise
68
+ noted; their arguments, return values, tensor types, devices, dtypes and
69
+ autograd behaviour come from PyTorch.
70
+
71
+ | PyTorch | BritTorch | Reference |
72
+ | --- | --- | --- |
73
+ | `torch.cat` | `torch.unite` | United Kingdom |
74
+ | `torch.clone` | `torch.dolly` | Dolly the sheep |
75
+ | `torch.roll` | `torch.sausage_roll` | British cuisine |
76
+ | `torch.sort` | `torch.queue` | Queuing culture |
77
+ | `torch.randn` | `torch.british_weather` | Unpredictable weather |
78
+ | `torch.no_grad` | `torch.tea_break` | A short pause for tea |
79
+ | `torch.manual_seed` | `torch.royal_decree` | Royal decrees |
80
+ | `torch.quantize_per_tensor` | `torch.quantise_per_tensor` | British spelling |
81
+ | `torch.quantize_per_channel` | `torch.quantise_per_channel` | British spelling |
82
+ | `torch.optim` | `torch.optimise` | British spelling |
83
+ | `torch.optim.Optimizer` | `optimise.Optimiser` | British spelling |
84
+ | `nn.Module` | `nn.NeuroSama` | A nod to Neuro-sama |
85
+ | `nn.Dropout` | `nn.Brexit` | A departure during training |
86
+ | `nn.ReLU` | `nn.StiffUpperLip` | Keep calm |
87
+ | `nn.BatchNorm1d/2d/3d` | `nn.BatchNormalisation1d/2d/3d` | British spelling |
88
+ | `nn.LayerNorm` | `nn.LayerNormalisation` | British spelling |
89
+ | `nn.GroupNorm` | `nn.GroupNormalisation` | British spelling |
90
+ | `F.normalize` | `F.normalise` | British spelling |
91
+ | `torch.load` | `british_museum.acquire` | Checkpoint loading |
92
+ | `torch.save` | `royal_archive.preserve` | Checkpoint saving |
93
+ | `torch.hub.load` | `east_india_company.import_goods` | Explicit Hub loading |
94
+
95
+ `optimise.AdamSmith` subclasses PyTorch's `Adam`. Its `carry_on()` calls
96
+ `step()` and `forgive_and_forget()` calls `zero_grad()`, including PyTorch's
97
+ normal hooks. The original methods and state dictionaries still work.
98
+
99
+ > AdamSmith uses the invisible hand to guide your gradients towards the minimum.
100
+ >
101
+ > Global convergence is not guaranteed, much like the British economy.
102
+
103
+ Adam actually stands for **Adaptive Moment Estimation** and has no historical
104
+ relationship with Adam Smith.
105
+
106
+ > Acquired artefacts are compatible with PyTorch, although the British Museum
107
+ > may be reluctant to return them.
108
+
109
+ The checkpoint and Hub names use PyTorch's functions directly. They do not
110
+ perform extra file access, start downloads on import or alter PyTorch's loading
111
+ defaults. Hub downloads occur only when you explicitly call `import_goods()`
112
+ with a source that requires them. Follow PyTorch's usual guidance for loading
113
+ checkpoints from untrusted sources.
114
+
115
+ ## Architecture greeting
116
+
117
+ On first import, BritTorch reads `platform.machine()` and writes a brief
118
+ greeting to standard error. ARM is preferred. x86 is tolerated. ARM, ARM64,
119
+ AArch64, x86, x86-64, AMD64, RISC-V and unfamiliar machines all use precisely
120
+ the same PyTorch computation. Set `BRITTORCH_QUIET=1` to suppress the greeting.
121
+ It is also suppressed in recognised multiprocessing workers and non-zero
122
+ distributed ranks. Rank detection uses common launcher environment variables;
123
+ unusual launchers may need the quiet setting.
124
+
125
+ Exceptions are passed through unchanged. If you explicitly want a humorous
126
+ aside while showing an error, call `brittorch.format_british_error(error)`.
127
+ For example, a missing file still begins with the original
128
+ `FileNotFoundError` and message.
129
+
130
+ ## Compatibility and testing
131
+
132
+ BritTorch is intended for ordinary PyTorch tensor and model code. It forwards
133
+ unknown attributes to PyTorch and exposes unchanged `nn` and `optimise`
134
+ attributes, including `Transformer`, `Embedding` and `MultiheadAttention`.
135
+ Python submodule imports are provided for the documented BritTorch modules;
136
+ arbitrary nested `torch.*` import paths are not mirrored. Third-party tools
137
+ that inspect module identity or depend on a particular PyTorch import path may
138
+ need the original `torch` import. Complete ecosystem compatibility has not
139
+ been established.
140
+
141
+ ```bash
142
+ uv run --extra dev pytest
143
+ uv run --extra dev ruff check .
144
+ ```
145
+
146
+ CPU tests cover aliases, gradients, optimisers, checkpoints and import paths.
147
+ The CUDA preservation test runs only when CUDA is available.
148
+
149
+ ## Build and release
150
+
151
+ ```bash
152
+ uv build --no-sources
153
+ uv run --extra dev python -m twine check dist/*
154
+ uv venv .venv-wheel
155
+ uv pip install --python .venv-wheel/bin/python dist/*.whl
156
+ BRITTORCH_QUIET=1 .venv-wheel/bin/python scripts/check_wheel.py
157
+ ```
158
+
159
+ The isolated wheel check installs PyTorch and may involve a substantial
160
+ download. Run it yourself when preparing a release.
161
+ Publishing is manual and requires your own PyPI credentials:
162
+
163
+ ```bash
164
+ UV_PUBLISH_TOKEN="<testpypi-token>" uv publish --publish-url https://test.pypi.org/legacy/ dist/*
165
+ UV_PUBLISH_TOKEN="<pypi-token>" uv publish dist/*
166
+ ```
167
+
168
+ Check the package name and version before publishing. The initial version is
169
+ `0.1.0`; subsequent releases should follow semantic versioning.
170
+
171
+ ## Contributing
172
+
173
+ Please keep additions small, test them against the corresponding PyTorch API,
174
+ and use British English in documentation and custom messages. Bugs, focused
175
+ improvements and tasteful jokes are welcome. Make Britain differentiate again.
@@ -0,0 +1,55 @@
1
+ """Train a small classifier on synthetic data, without downloading a dataset."""
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+
6
+ import brittorch as torch
7
+ from brittorch import nn, optimise, royal_archive
8
+
9
+
10
+ def main() -> None:
11
+ parser = argparse.ArgumentParser(description="Keep Calm and Carry On Training")
12
+ parser.add_argument("--epochs", type=int, default=40)
13
+ parser.add_argument("--checkpoint", type=Path, default=Path("his_majesty.pt"))
14
+ args = parser.parse_args()
15
+
16
+ torch.royal_decree(42)
17
+ inputs = torch.british_weather(96, 128)
18
+ teacher = torch.british_weather(128, 10)
19
+ targets = (inputs @ teacher).argmax(dim=1)
20
+
21
+ model = nn.Sequential(
22
+ nn.Linear(128, 256),
23
+ nn.StiffUpperLip(),
24
+ nn.Brexit(0.2),
25
+ nn.Linear(256, 10),
26
+ )
27
+ optimiser = optimise.AdamSmith(model.parameters(), lr=1e-2)
28
+ criterion = nn.CrossEntropyLoss()
29
+
30
+ model.eval()
31
+ with torch.tea_break():
32
+ initial_loss = criterion(model(inputs), targets).item()
33
+
34
+ for _ in range(args.epochs):
35
+ model.train()
36
+ optimiser.forgive_and_forget()
37
+ prediction = model(inputs)
38
+ loss = criterion(prediction, targets)
39
+ loss.backward()
40
+ optimiser.carry_on()
41
+
42
+ model.eval()
43
+ with torch.tea_break():
44
+ prediction = model(inputs)
45
+ final_loss = criterion(prediction, targets).item()
46
+ accuracy = (prediction.argmax(dim=1) == targets).float().mean().item()
47
+
48
+ royal_archive.preserve(model.state_dict(), args.checkpoint)
49
+ print(f"Loss: {initial_loss:.4f} -> {final_loss:.4f}")
50
+ print(f"Training accuracy: {accuracy:.1%}")
51
+ print(f"Checkpoint: {args.checkpoint}")
52
+
53
+
54
+ if __name__ == "__main__":
55
+ main()
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "brittorch"
7
+ version = "0.1.0"
8
+ description = "Deep Learning for His Majesty: a British-themed PyTorch wrapper"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "BritTorch contributors" }]
13
+ keywords = ["pytorch", "deep-learning", "british", "parody"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ ]
23
+ dependencies = ["torch>=2.1"]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["build>=1.0", "pytest>=8.0", "ruff>=0.6", "twine>=5.0"]
27
+
28
+ [tool.setuptools.packages.find]
29
+ where = ["src"]
30
+
31
+ [tool.pytest.ini_options]
32
+ testpaths = ["tests"]
33
+ addopts = "-q"
34
+
35
+ [tool.ruff]
36
+ target-version = "py310"
37
+ line-length = 88
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "F", "I"]
@@ -0,0 +1,16 @@
1
+ """Smoke-test a BritTorch wheel installed in this Python environment."""
2
+
3
+ import importlib.metadata
4
+ from pathlib import Path
5
+
6
+ import brittorch as torch
7
+ from brittorch import nn, optimise
8
+ from brittorch.nn import functional as f
9
+
10
+ assert importlib.metadata.version("brittorch") == torch.__version__
11
+ assert "site-packages" in Path(torch.__file__).parts
12
+ assert torch.tensor([1, 2]).sum().item() == 3
13
+ assert nn.Linear(2, 1)(torch.ones(1, 2)).shape == (1, 1)
14
+ assert f.normalise is not None
15
+ assert optimise.AdamSmith is not None
16
+ print(f"Installed BritTorch {torch.__version__}: imports and tensor smoke test passed")
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,32 @@
1
+ """Deep Learning for His Majesty, with PyTorch doing the actual work."""
2
+
3
+ import torch as _torch
4
+
5
+ from . import british_museum, east_india_company, nn, optimise, royal_archive
6
+ from ._architecture import announce_architecture
7
+ from ._errors import format_british_error
8
+
9
+ __version__ = "0.1.0"
10
+
11
+ # Direct aliases keep PyTorch's signatures, return types and autograd behaviour.
12
+ unite = _torch.cat
13
+ dolly = _torch.clone
14
+ sausage_roll = _torch.roll
15
+ queue = _torch.sort
16
+ british_weather = _torch.randn
17
+ tea_break = _torch.no_grad
18
+ royal_decree = _torch.manual_seed
19
+ quantise_per_tensor = _torch.quantize_per_tensor
20
+ quantise_per_channel = _torch.quantize_per_channel
21
+
22
+
23
+ def __getattr__(name: str):
24
+ """Expose the ordinary PyTorch API alongside the British aliases."""
25
+ return getattr(_torch, name)
26
+
27
+
28
+ def __dir__():
29
+ return sorted(set(globals()) | set(dir(_torch)))
30
+
31
+
32
+ announce_architecture()
@@ -0,0 +1,57 @@
1
+ """A small, optional greeting for the host architecture."""
2
+
3
+ import multiprocessing
4
+ import os
5
+ import platform
6
+ import sys
7
+
8
+ _announced_pid: int | None = None
9
+ _RANK_VARIABLES = (
10
+ "RANK",
11
+ "LOCAL_RANK",
12
+ "SLURM_PROCID",
13
+ "OMPI_COMM_WORLD_RANK",
14
+ "PMI_RANK",
15
+ "MV2_COMM_WORLD_RANK",
16
+ )
17
+
18
+
19
+ def architecture_message(machine: str) -> str:
20
+ """Return the greeting for a machine name reported by the platform."""
21
+ name = machine.casefold().replace("-", "_")
22
+ if name.startswith(("aarch64", "arm64", "arm")):
23
+ return (
24
+ "🇬🇧 GOD SAVE THE KING!\n"
25
+ "ARM architecture detected.\n"
26
+ "Your hardware is properly British."
27
+ )
28
+ if name in {"x86", "x86_64", "amd64", "i386", "i486", "i586", "i686"}:
29
+ return "American architecture detected.\nHow unfortunate."
30
+ if name.startswith("riscv") or name.startswith("risc_v"):
31
+ return "Parliament recognises your independence."
32
+ return "Your territory has not yet been charted."
33
+
34
+
35
+ def _is_worker_or_nonzero_rank() -> bool:
36
+ if multiprocessing.current_process().name != "MainProcess":
37
+ return True
38
+ for variable in _RANK_VARIABLES:
39
+ value = os.environ.get(variable)
40
+ if value is not None and value.strip().lstrip("+").isdigit():
41
+ if int(value) != 0:
42
+ return True
43
+ return False
44
+
45
+
46
+ def announce_architecture() -> None:
47
+ """Write at most one greeting per eligible process to standard error."""
48
+ global _announced_pid
49
+ if os.environ.get("BRITTORCH_QUIET") == "1":
50
+ return
51
+ if _is_worker_or_nonzero_rank():
52
+ return
53
+ pid = os.getpid()
54
+ if _announced_pid == pid:
55
+ return
56
+ print(architecture_message(platform.machine()), file=sys.stderr)
57
+ _announced_pid = pid
@@ -0,0 +1,21 @@
1
+ """Optional humour for callers who explicitly request it."""
2
+
3
+
4
+ def format_british_error(error: BaseException) -> str:
5
+ """Add a gentle aside while keeping the original error text visible."""
6
+ original = f"{type(error).__name__}: {error}"
7
+ if "CUDA out of memory" in str(error):
8
+ aside = "The Empire is overstretched."
9
+ elif isinstance(error, FileNotFoundError):
10
+ aside = "Perhaps it is in the British Museum."
11
+ elif isinstance(error, NotImplementedError):
12
+ aside = "Parliament is still debating the matter."
13
+ elif isinstance(error, TimeoutError):
14
+ aside = "Apologies, we were having tea."
15
+ elif isinstance(error, KeyboardInterrupt):
16
+ aside = "The Prime Minister has resigned."
17
+ elif isinstance(error, ValueError):
18
+ aside = "That is simply not cricket."
19
+ else:
20
+ return original
21
+ return f"{original}\n{aside}"
@@ -0,0 +1,3 @@
1
+ """Checkpoint acquisition, courtesy of PyTorch."""
2
+
3
+ from torch import load as acquire
@@ -0,0 +1,3 @@
1
+ """An alias for the explicitly requested PyTorch Hub loader."""
2
+
3
+ from torch.hub import load as import_goods
@@ -0,0 +1,22 @@
1
+ """PyTorch neural networks with a restrained selection of British aliases."""
2
+
3
+ import torch.nn as _nn
4
+
5
+ from . import functional
6
+
7
+ NeuroSama = _nn.Module
8
+ Brexit = _nn.Dropout
9
+ StiffUpperLip = _nn.ReLU
10
+ BatchNormalisation1d = _nn.BatchNorm1d
11
+ BatchNormalisation2d = _nn.BatchNorm2d
12
+ BatchNormalisation3d = _nn.BatchNorm3d
13
+ LayerNormalisation = _nn.LayerNorm
14
+ GroupNormalisation = _nn.GroupNorm
15
+
16
+
17
+ def __getattr__(name: str):
18
+ return getattr(_nn, name)
19
+
20
+
21
+ def __dir__():
22
+ return sorted(set(globals()) | set(dir(_nn)))
@@ -0,0 +1,13 @@
1
+ """PyTorch functional operations, including British normalisation."""
2
+
3
+ import torch.nn.functional as _functional
4
+
5
+ normalise = _functional.normalize
6
+
7
+
8
+ def __getattr__(name: str):
9
+ return getattr(_functional, name)
10
+
11
+
12
+ def __dir__():
13
+ return sorted(set(globals()) | set(dir(_functional)))
@@ -0,0 +1,30 @@
1
+ """PyTorch optimisers, including AdamSmith and his invisible hand."""
2
+
3
+ import torch.optim as _optim
4
+
5
+ Optimiser = _optim.Optimizer
6
+
7
+
8
+ class AdamSmith(_optim.Adam):
9
+ """Adam with a pair of polite method names.
10
+
11
+ Adam stands for Adaptive Moment Estimation. It has no historical connection
12
+ to Adam Smith. The invisible hand guides gradients towards a minimum, but
13
+ global convergence is not guaranteed, much like the British economy.
14
+ """
15
+
16
+ def carry_on(self, *args, **kwargs):
17
+ """Call :meth:`step`, including any registered PyTorch hooks."""
18
+ return self.step(*args, **kwargs)
19
+
20
+ def forgive_and_forget(self, *args, **kwargs):
21
+ """Call :meth:`zero_grad` with its original arguments."""
22
+ return self.zero_grad(*args, **kwargs)
23
+
24
+
25
+ def __getattr__(name: str):
26
+ return getattr(_optim, name)
27
+
28
+
29
+ def __dir__():
30
+ return sorted(set(globals()) | set(dir(_optim)))
@@ -0,0 +1,3 @@
1
+ """Checkpoint preservation, courtesy of PyTorch."""
2
+
3
+ from torch import save as preserve
@@ -0,0 +1,200 @@
1
+ Metadata-Version: 2.4
2
+ Name: brittorch
3
+ Version: 0.1.0
4
+ Summary: Deep Learning for His Majesty: a British-themed PyTorch wrapper
5
+ Author: BritTorch contributors
6
+ License-Expression: MIT
7
+ Keywords: pytorch,deep-learning,british,parody
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: torch>=2.1
19
+ Provides-Extra: dev
20
+ Requires-Dist: build>=1.0; extra == "dev"
21
+ Requires-Dist: pytest>=8.0; extra == "dev"
22
+ Requires-Dist: ruff>=0.6; extra == "dev"
23
+ Requires-Dist: twine>=5.0; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # BritTorch 🇬🇧
27
+
28
+ **Deep Learning for His Majesty.**
29
+ *All the power of PyTorch, none of the American spelling.*
30
+
31
+ BritTorch is a lightweight, humorous wrapper around PyTorch. It provides a few
32
+ British spellings and cultural aliases while PyTorch performs every tensor
33
+ operation, gradient calculation and optimiser update. The same gradients.
34
+ Better manners. No additional CUDA kernels were colonised during development.
35
+
36
+ BritTorch is an unofficial parody project. It is not affiliated with PyTorch,
37
+ Arm, Neuro-sama or the British government. It is not a separate deep learning
38
+ framework and does not improve numerical performance.
39
+
40
+ ## Installation
41
+
42
+ Python 3.10 or newer and a compatible PyTorch installation are required.
43
+
44
+ ```bash
45
+ uv venv
46
+ uv pip install brittorch
47
+ ```
48
+
49
+ For a local checkout, install the development dependencies with:
50
+
51
+ ```bash
52
+ uv sync --extra dev
53
+ ```
54
+
55
+ This resolves PyTorch as a runtime dependency. Follow the official PyTorch
56
+ installation guidance if your platform needs a particular CUDA or accelerator
57
+ build.
58
+
59
+ ## Keep Calm and Carry On Training
60
+
61
+ ```python
62
+ import brittorch as torch
63
+ from brittorch import nn, optimise, royal_archive
64
+ import brittorch.nn.functional as F
65
+
66
+ torch.royal_decree(42)
67
+ inputs = torch.british_weather(64, 8)
68
+ targets = (inputs[:, 0] > 0).long()
69
+
70
+ model = nn.Sequential(nn.Linear(8, 16), nn.StiffUpperLip(), nn.Linear(16, 2))
71
+ optimiser = optimise.AdamSmith(model.parameters(), lr=1e-2)
72
+
73
+ for _ in range(20):
74
+ optimiser.forgive_and_forget()
75
+ loss = F.cross_entropy(model(inputs), targets)
76
+ loss.backward()
77
+ optimiser.carry_on()
78
+
79
+ with torch.tea_break():
80
+ prediction = model(inputs).argmax(dim=1)
81
+
82
+ royal_archive.preserve(model.state_dict(), "his_majesty.pt")
83
+ ```
84
+
85
+ The full [synthetic training example](examples/train.py) prints its starting
86
+ and final loss, training accuracy and checkpoint path. It requires no dataset
87
+ download. Run it with `uv run --extra dev python examples/train.py`.
88
+
89
+ ## API guide
90
+
91
+ All ordinary PyTorch names remain available through the corresponding
92
+ BritTorch module. The British names below are direct aliases unless otherwise
93
+ noted; their arguments, return values, tensor types, devices, dtypes and
94
+ autograd behaviour come from PyTorch.
95
+
96
+ | PyTorch | BritTorch | Reference |
97
+ | --- | --- | --- |
98
+ | `torch.cat` | `torch.unite` | United Kingdom |
99
+ | `torch.clone` | `torch.dolly` | Dolly the sheep |
100
+ | `torch.roll` | `torch.sausage_roll` | British cuisine |
101
+ | `torch.sort` | `torch.queue` | Queuing culture |
102
+ | `torch.randn` | `torch.british_weather` | Unpredictable weather |
103
+ | `torch.no_grad` | `torch.tea_break` | A short pause for tea |
104
+ | `torch.manual_seed` | `torch.royal_decree` | Royal decrees |
105
+ | `torch.quantize_per_tensor` | `torch.quantise_per_tensor` | British spelling |
106
+ | `torch.quantize_per_channel` | `torch.quantise_per_channel` | British spelling |
107
+ | `torch.optim` | `torch.optimise` | British spelling |
108
+ | `torch.optim.Optimizer` | `optimise.Optimiser` | British spelling |
109
+ | `nn.Module` | `nn.NeuroSama` | A nod to Neuro-sama |
110
+ | `nn.Dropout` | `nn.Brexit` | A departure during training |
111
+ | `nn.ReLU` | `nn.StiffUpperLip` | Keep calm |
112
+ | `nn.BatchNorm1d/2d/3d` | `nn.BatchNormalisation1d/2d/3d` | British spelling |
113
+ | `nn.LayerNorm` | `nn.LayerNormalisation` | British spelling |
114
+ | `nn.GroupNorm` | `nn.GroupNormalisation` | British spelling |
115
+ | `F.normalize` | `F.normalise` | British spelling |
116
+ | `torch.load` | `british_museum.acquire` | Checkpoint loading |
117
+ | `torch.save` | `royal_archive.preserve` | Checkpoint saving |
118
+ | `torch.hub.load` | `east_india_company.import_goods` | Explicit Hub loading |
119
+
120
+ `optimise.AdamSmith` subclasses PyTorch's `Adam`. Its `carry_on()` calls
121
+ `step()` and `forgive_and_forget()` calls `zero_grad()`, including PyTorch's
122
+ normal hooks. The original methods and state dictionaries still work.
123
+
124
+ > AdamSmith uses the invisible hand to guide your gradients towards the minimum.
125
+ >
126
+ > Global convergence is not guaranteed, much like the British economy.
127
+
128
+ Adam actually stands for **Adaptive Moment Estimation** and has no historical
129
+ relationship with Adam Smith.
130
+
131
+ > Acquired artefacts are compatible with PyTorch, although the British Museum
132
+ > may be reluctant to return them.
133
+
134
+ The checkpoint and Hub names use PyTorch's functions directly. They do not
135
+ perform extra file access, start downloads on import or alter PyTorch's loading
136
+ defaults. Hub downloads occur only when you explicitly call `import_goods()`
137
+ with a source that requires them. Follow PyTorch's usual guidance for loading
138
+ checkpoints from untrusted sources.
139
+
140
+ ## Architecture greeting
141
+
142
+ On first import, BritTorch reads `platform.machine()` and writes a brief
143
+ greeting to standard error. ARM is preferred. x86 is tolerated. ARM, ARM64,
144
+ AArch64, x86, x86-64, AMD64, RISC-V and unfamiliar machines all use precisely
145
+ the same PyTorch computation. Set `BRITTORCH_QUIET=1` to suppress the greeting.
146
+ It is also suppressed in recognised multiprocessing workers and non-zero
147
+ distributed ranks. Rank detection uses common launcher environment variables;
148
+ unusual launchers may need the quiet setting.
149
+
150
+ Exceptions are passed through unchanged. If you explicitly want a humorous
151
+ aside while showing an error, call `brittorch.format_british_error(error)`.
152
+ For example, a missing file still begins with the original
153
+ `FileNotFoundError` and message.
154
+
155
+ ## Compatibility and testing
156
+
157
+ BritTorch is intended for ordinary PyTorch tensor and model code. It forwards
158
+ unknown attributes to PyTorch and exposes unchanged `nn` and `optimise`
159
+ attributes, including `Transformer`, `Embedding` and `MultiheadAttention`.
160
+ Python submodule imports are provided for the documented BritTorch modules;
161
+ arbitrary nested `torch.*` import paths are not mirrored. Third-party tools
162
+ that inspect module identity or depend on a particular PyTorch import path may
163
+ need the original `torch` import. Complete ecosystem compatibility has not
164
+ been established.
165
+
166
+ ```bash
167
+ uv run --extra dev pytest
168
+ uv run --extra dev ruff check .
169
+ ```
170
+
171
+ CPU tests cover aliases, gradients, optimisers, checkpoints and import paths.
172
+ The CUDA preservation test runs only when CUDA is available.
173
+
174
+ ## Build and release
175
+
176
+ ```bash
177
+ uv build --no-sources
178
+ uv run --extra dev python -m twine check dist/*
179
+ uv venv .venv-wheel
180
+ uv pip install --python .venv-wheel/bin/python dist/*.whl
181
+ BRITTORCH_QUIET=1 .venv-wheel/bin/python scripts/check_wheel.py
182
+ ```
183
+
184
+ The isolated wheel check installs PyTorch and may involve a substantial
185
+ download. Run it yourself when preparing a release.
186
+ Publishing is manual and requires your own PyPI credentials:
187
+
188
+ ```bash
189
+ UV_PUBLISH_TOKEN="<testpypi-token>" uv publish --publish-url https://test.pypi.org/legacy/ dist/*
190
+ UV_PUBLISH_TOKEN="<pypi-token>" uv publish dist/*
191
+ ```
192
+
193
+ Check the package name and version before publishing. The initial version is
194
+ `0.1.0`; subsequent releases should follow semantic versioning.
195
+
196
+ ## Contributing
197
+
198
+ Please keep additions small, test them against the corresponding PyTorch API,
199
+ and use British English in documentation and custom messages. Bugs, focused
200
+ improvements and tasteful jokes are welcome. Make Britain differentiate again.
@@ -0,0 +1,23 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ examples/train.py
6
+ scripts/check_wheel.py
7
+ src/brittorch/__init__.py
8
+ src/brittorch/_architecture.py
9
+ src/brittorch/_errors.py
10
+ src/brittorch/british_museum.py
11
+ src/brittorch/east_india_company.py
12
+ src/brittorch/royal_archive.py
13
+ src/brittorch.egg-info/PKG-INFO
14
+ src/brittorch.egg-info/SOURCES.txt
15
+ src/brittorch.egg-info/dependency_links.txt
16
+ src/brittorch.egg-info/requires.txt
17
+ src/brittorch.egg-info/top_level.txt
18
+ src/brittorch/nn/__init__.py
19
+ src/brittorch/nn/functional.py
20
+ src/brittorch/optimise/__init__.py
21
+ tests/test_aliases.py
22
+ tests/test_architecture.py
23
+ tests/test_optimise_and_checkpoints.py
@@ -0,0 +1,7 @@
1
+ torch>=2.1
2
+
3
+ [dev]
4
+ build>=1.0
5
+ pytest>=8.0
6
+ ruff>=0.6
7
+ twine>=5.0
@@ -0,0 +1 @@
1
+ brittorch
@@ -0,0 +1,92 @@
1
+ import importlib
2
+
3
+ import brittorch as bt
4
+ import torch
5
+ import torch.nn.functional as torch_f
6
+ from brittorch import nn, optimise
7
+ from brittorch.nn import functional as f
8
+
9
+
10
+ def test_direct_aliases_and_original_api():
11
+ assert bt.unite is torch.cat
12
+ assert bt.dolly is torch.clone
13
+ assert bt.sausage_roll is torch.roll
14
+ assert bt.queue is torch.sort
15
+ assert bt.british_weather is torch.randn
16
+ assert bt.tea_break is torch.no_grad
17
+ assert bt.royal_decree is torch.manual_seed
18
+ assert bt.quantise_per_tensor is torch.quantize_per_tensor
19
+ assert bt.quantise_per_channel is torch.quantize_per_channel
20
+ assert bt.tensor is torch.tensor
21
+ assert bt.optim is torch.optim
22
+ assert nn.Linear is torch.nn.Linear
23
+ assert nn.Transformer is torch.nn.Transformer
24
+ assert nn.Embedding is torch.nn.Embedding
25
+ assert nn.MultiheadAttention is torch.nn.MultiheadAttention
26
+ assert f.relu is torch_f.relu
27
+ assert optimise.Adam is torch.optim.Adam
28
+
29
+
30
+ def test_british_spellings_and_neural_aliases():
31
+ assert f.normalise is torch_f.normalize
32
+ assert nn.NeuroSama is torch.nn.Module
33
+ assert nn.Brexit is torch.nn.Dropout
34
+ assert nn.StiffUpperLip is torch.nn.ReLU
35
+ assert nn.BatchNormalisation1d is torch.nn.BatchNorm1d
36
+ assert nn.BatchNormalisation2d is torch.nn.BatchNorm2d
37
+ assert nn.BatchNormalisation3d is torch.nn.BatchNorm3d
38
+ assert nn.LayerNormalisation is torch.nn.LayerNorm
39
+ assert nn.GroupNormalisation is torch.nn.GroupNorm
40
+ assert optimise.Optimiser is torch.optim.Optimizer
41
+
42
+
43
+ def test_numerics_gradient_dtype_and_device():
44
+ x = torch.tensor([[-2.0, 1.0], [0.5, 3.0]], dtype=torch.float64)
45
+ original = x.clone().requires_grad_()
46
+ british = x.clone().requires_grad_()
47
+ expected = torch.cat([torch.clone(original), torch.roll(original, 1, 0)]).square()
48
+ actual = bt.unite([bt.dolly(british), bt.sausage_roll(british, 1, 0)]).square()
49
+ torch.testing.assert_close(actual, expected)
50
+ assert actual.dtype == x.dtype
51
+ assert actual.device == x.device
52
+ actual.sum().backward()
53
+ expected.sum().backward()
54
+ torch.testing.assert_close(british.grad, original.grad)
55
+ torch.testing.assert_close(bt.queue(x).values, torch.sort(x).values)
56
+ torch.testing.assert_close(f.normalise(x), torch_f.normalize(x))
57
+
58
+
59
+ def test_seed_and_no_grad():
60
+ bt.royal_decree(123)
61
+ actual = bt.british_weather(3, 4)
62
+ torch.manual_seed(123)
63
+ torch.testing.assert_close(actual, torch.randn(3, 4))
64
+ with bt.tea_break():
65
+ assert not (torch.ones(1, requires_grad=True) * 2).requires_grad
66
+
67
+
68
+ def test_neurosama_subclass_and_nested_imports():
69
+ class MyModel(nn.NeuroSama):
70
+ def __init__(self):
71
+ super().__init__()
72
+ self.layers = nn.Sequential(
73
+ nn.Linear(4, 8), nn.StiffUpperLip(), nn.Brexit(0.2)
74
+ )
75
+
76
+ def forward(self, x):
77
+ return self.layers(x)
78
+
79
+ model = MyModel()
80
+ assert model(torch.ones(2, 4)).shape == (2, 8)
81
+ assert importlib.import_module("brittorch.nn.functional") is f
82
+ assert importlib.import_module("brittorch.optimise") is optimise
83
+ assert importlib.import_module("brittorch.british_museum") is bt.british_museum
84
+
85
+
86
+ def test_cuda_alias_when_available():
87
+ if not torch.cuda.is_available():
88
+ return
89
+ x = torch.randn(3, device="cuda", dtype=torch.float16)
90
+ result = bt.dolly(x)
91
+ assert result.device == x.device
92
+ assert result.dtype == x.dtype
@@ -0,0 +1,69 @@
1
+ from types import SimpleNamespace
2
+
3
+ from brittorch import _architecture as architecture
4
+
5
+
6
+ def _prepare(monkeypatch):
7
+ architecture._announced_pid = None
8
+ monkeypatch.delenv("BRITTORCH_QUIET", raising=False)
9
+ for variable in architecture._RANK_VARIABLES:
10
+ monkeypatch.delenv(variable, raising=False)
11
+ monkeypatch.setattr(
12
+ architecture.multiprocessing,
13
+ "current_process",
14
+ lambda: SimpleNamespace(name="MainProcess"),
15
+ )
16
+
17
+
18
+ def test_machine_messages():
19
+ for machine in ("armv7l", "ARM64", "aarch64"):
20
+ assert "GOD SAVE THE KING" in architecture.architecture_message(machine)
21
+ for machine in ("x86", "i686", "x86-64", "AMD64"):
22
+ assert "American architecture" in architecture.architecture_message(machine)
23
+ assert "independence" in architecture.architecture_message("riscv64")
24
+ assert "not yet been charted" in architecture.architecture_message("mystery-cpu")
25
+
26
+
27
+ def test_announces_once_to_stderr(monkeypatch, capsys):
28
+ _prepare(monkeypatch)
29
+ monkeypatch.setattr(architecture.platform, "machine", lambda: "aarch64")
30
+ architecture.announce_architecture()
31
+ architecture.announce_architecture()
32
+ captured = capsys.readouterr()
33
+ assert captured.out == ""
34
+ assert captured.err.count("GOD SAVE THE KING") == 1
35
+
36
+
37
+ def test_x86_announcement(monkeypatch, capsys):
38
+ _prepare(monkeypatch)
39
+ monkeypatch.setattr(architecture.platform, "machine", lambda: "AMD64")
40
+ architecture.announce_architecture()
41
+ assert capsys.readouterr().err == (
42
+ "American architecture detected.\nHow unfortunate.\n"
43
+ )
44
+
45
+
46
+ def test_quiet_mode(monkeypatch, capsys):
47
+ _prepare(monkeypatch)
48
+ monkeypatch.setenv("BRITTORCH_QUIET", "1")
49
+ architecture.announce_architecture()
50
+ assert capsys.readouterr().err == ""
51
+
52
+
53
+ def test_distributed_rank_suppression(monkeypatch, capsys):
54
+ for variable in architecture._RANK_VARIABLES:
55
+ _prepare(monkeypatch)
56
+ monkeypatch.setenv(variable, "1")
57
+ architecture.announce_architecture()
58
+ assert capsys.readouterr().err == ""
59
+
60
+
61
+ def test_multiprocessing_worker_suppression(monkeypatch, capsys):
62
+ _prepare(monkeypatch)
63
+ monkeypatch.setattr(
64
+ architecture.multiprocessing,
65
+ "current_process",
66
+ lambda: SimpleNamespace(name="SpawnProcess-1"),
67
+ )
68
+ architecture.announce_architecture()
69
+ assert capsys.readouterr().err == ""
@@ -0,0 +1,86 @@
1
+ import io
2
+
3
+ import brittorch as bt
4
+ import torch
5
+ from brittorch import british_museum, east_india_company, nn, optimise, royal_archive
6
+
7
+
8
+ def test_adam_smith_matches_adam_and_state_dict():
9
+ ordinary_parameter = torch.nn.Parameter(torch.tensor([1.0, -2.0]))
10
+ british_parameter = torch.nn.Parameter(ordinary_parameter.detach().clone())
11
+ ordinary = torch.optim.Adam([ordinary_parameter], lr=0.01)
12
+ british = optimise.AdamSmith([british_parameter], lr=0.01)
13
+
14
+ for _ in range(3):
15
+ ordinary.zero_grad()
16
+ british.forgive_and_forget()
17
+ ordinary_parameter.square().sum().backward()
18
+ british_parameter.square().sum().backward()
19
+ ordinary.step()
20
+ british.carry_on()
21
+
22
+ torch.testing.assert_close(british_parameter, ordinary_parameter)
23
+ assert british.state_dict()["param_groups"] == ordinary.state_dict()["param_groups"]
24
+ for british_state, ordinary_state in zip(
25
+ british.state_dict()["state"].values(),
26
+ ordinary.state_dict()["state"].values(),
27
+ ):
28
+ for key in ordinary_state:
29
+ torch.testing.assert_close(british_state[key], ordinary_state[key])
30
+
31
+ restored = torch.optim.Adam([torch.nn.Parameter(torch.zeros(2))], lr=0.5)
32
+ restored.load_state_dict(british.state_dict())
33
+ assert restored.state_dict()["param_groups"] == british.state_dict()["param_groups"]
34
+
35
+
36
+ def test_adam_smith_calls_original_methods_and_hooks():
37
+ parameter = torch.nn.Parameter(torch.ones(1))
38
+ optimiser = optimise.AdamSmith([parameter])
39
+ calls = []
40
+ handle = optimiser.register_step_pre_hook(
41
+ lambda _optim, _args, _kwargs: calls.append("step")
42
+ )
43
+ parameter.sum().backward()
44
+ optimiser.carry_on()
45
+ assert calls == ["step"]
46
+ handle.remove()
47
+ optimiser.forgive_and_forget(set_to_none=True)
48
+ assert parameter.grad is None
49
+
50
+
51
+ def test_checkpoint_round_trip_in_both_directions():
52
+ assert british_museum.acquire is torch.load
53
+ assert royal_archive.preserve is torch.save
54
+ assert east_india_company.import_goods is torch.hub.load
55
+
56
+ model = nn.Linear(3, 2)
57
+ buffer = io.BytesIO()
58
+ royal_archive.preserve(model.state_dict(), buffer)
59
+ buffer.seek(0)
60
+ loaded_by_pytorch = torch.load(buffer, weights_only=True)
61
+ for key, value in model.state_dict().items():
62
+ torch.testing.assert_close(loaded_by_pytorch[key], value)
63
+
64
+ buffer = io.BytesIO()
65
+ torch.save(model.state_dict(), buffer)
66
+ buffer.seek(0)
67
+ restored = nn.Linear(3, 2)
68
+ restored.load_state_dict(british_museum.acquire(buffer, weights_only=True))
69
+ for key, value in model.state_dict().items():
70
+ torch.testing.assert_close(restored.state_dict()[key], value)
71
+
72
+
73
+ def test_original_error_is_not_rewritten():
74
+ try:
75
+ bt.tensor([1, 2, 3]).reshape(2, 2)
76
+ except RuntimeError as error:
77
+ assert "shape" in str(error)
78
+ else:
79
+ raise AssertionError("Expected the original PyTorch RuntimeError")
80
+
81
+
82
+ def test_opt_in_error_formatter():
83
+ error = FileNotFoundError("missing.pt")
84
+ message = bt.format_british_error(error)
85
+ assert "FileNotFoundError: missing.pt" in message
86
+ assert "British Museum" in message