brittorch 0.1.0__py3-none-any.whl

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.
brittorch/__init__.py ADDED
@@ -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
brittorch/_errors.py ADDED
@@ -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,14 @@
1
+ brittorch/__init__.py,sha256=wIIR2IAkIcPuE_uWAX9NWVc3Jlus4hZgOkNmsyJAtyw,883
2
+ brittorch/_architecture.py,sha256=icupJK9E9VrlED66VEKyFQu3DgGEj7QgShT5Tw4wqjc,1775
3
+ brittorch/_errors.py,sha256=ilp4S7uQNWUFCy5iaK2idBr06TGWDVJzXdIFwHSnI5s,887
4
+ brittorch/british_museum.py,sha256=uL83MqW86OquWr3hTOZKa5ivDLk2dhRdzdMaOaqodMQ,86
5
+ brittorch/east_india_company.py,sha256=U1ZISgllnQChN1_jlTQ-PUL59q8Ewj_au9gDK6odRsE,108
6
+ brittorch/royal_archive.py,sha256=FT81WqoKLJfdpjooAQdUjx46dDbJJkA6kfCpv8Mfqxo,88
7
+ brittorch/nn/__init__.py,sha256=iIVP9G5NlE6siFLpxEGWLXBtH8b0pIigjbnsPeyMDF0,512
8
+ brittorch/nn/functional.py,sha256=dUJhiJLn_-8L0GTwswES_yRHsILpLfMEm63K3n2buHs,291
9
+ brittorch/optimise/__init__.py,sha256=KztEGqc5s26RQUpN1xjme3guCRA9689q55P-vTfsB4U,905
10
+ brittorch-0.1.0.dist-info/licenses/LICENSE,sha256=h5tBbhx_eEpEmLxskTfGoI4p34fFdDFwmwQIM-SiqWs,1079
11
+ brittorch-0.1.0.dist-info/METADATA,sha256=5tqJzOdJMQywgPxyAzwVvwEBd-R3tVWkBeCINUKnS6A,8011
12
+ brittorch-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
13
+ brittorch-0.1.0.dist-info/top_level.txt,sha256=lDh3HmFZSZaVj2my3J2coyXp7_XdAxSsUdy9Y3a45rY,10
14
+ brittorch-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ brittorch