Export PyTorch modules to Scratch sprites
Project description
cattorch
Export PyTorch neural networks to Scratch sprites.
cattorch transpiles a torch.nn.Module into a .sprite3 file that can be
imported directly into any Scratch project. The generated sprite uses only
standard Scratch blocks, so no extensions or modifications are required.
cattorch does not export training scripts, you will need to train your model with torch before exporting to a Scratch sprite.
Install
pip install cattorch
Requires Python 3.10+ and PyTorch 2.0+.
Usage
import torch
import torch.nn as nn
from cattorch import transpile
class TwoLayerNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 8)
self.fc2 = nn.Linear(8, 3)
def forward(self, x):
return self.fc2(torch.relu(self.fc1(x)))
model = TwoLayerNet()
# train your model first! then:
# transpile(model, example input, sprite name)
transpile(model, torch.randn(1, 4), "two_layer_net")
# => two_layer_net.sprite3
# optionally reduce file size by rounding weights
transpile(model, torch.randn(1, 4), "two_layer_net", sig_figs=6)
cattorch uses torch.export under the hood, which requires a single code path
with no data-dependent control flow. If your model has conditional returns
(e.g. returning loss during training), add an inference-only forward method:
# won't work: conditional return
def forward(self, x, targets=None):
logits = self.head(x)
if targets is None:
return logits
return logits, F.cross_entropy(logits, targets)
# will work: single return path
def forward_inference(self, x):
return self.head(x)
model.eval()
model.forward = model.forward_inference
transpile(model, example_input, "my_model")
In Scratch, the sprite reads its input from a list called input and writes
results to a list called output. It is up to you to add logic to fill the
input tensor and run the generated code blocks.
If the model takes multiple input tensors, the additional inputs are named
input_1, input_2, etc.
Supported operations
| Category | Operations |
|---|---|
| Linear layers | nn.Linear (with and without bias) |
| Matrix multiply | @ / torch.matmul |
| Activations | ReLU, Sigmoid, Tanh, GELU (tanh approx. only), SiLU, LeakyReLU, ELU |
| Normalization | nn.LayerNorm, nn.RMSNorm |
| Softmax | F.softmax (any dim) |
| Embedding | nn.Embedding |
| Masking | masked_fill (for causal attention masks via register_buffer) |
| Arithmetic | tensor add, tensor subtract, tensor multiply, scalar multiply, scalar divide, negate |
| Shape | view, reshape, flatten, contiguous, clone (no-ops on flat data) |
| Transpose | transpose, permute, .T (arbitrary dimensions) |
| Split / Chunk | split, split_with_sizes, chunk |
| Concatenation | torch.cat (any dim, any number of inputs) |
| Slice | tensor[:n] style slicing along any dimension |
| Tensor generation | torch.arange (materialised at transpile time) |
These are sufficient for architectures like MLPs and transformer LLMs, including multi-head attention, combined QKV projections, rotary position embeddings (RoPE), causal masking, pre-norm blocks with residual connections, and SwiGLU-style gating. CNN and RNN support is planned for the future.
Scratch limits
- Project size: Scratch limits projects to 5 MB. cattorch warns at 4 MB and errors at 5 MB.
- List length: Scratch lists can hold at most 200,000 items. cattorch raises an error if any weight tensor or intermediate list exceeds this.
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cattorch-0.2.0.tar.gz.
File metadata
- Download URL: cattorch-0.2.0.tar.gz
- Upload date:
- Size: 44.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9861c49bf03e4a5aee3c2bf1e0500ac9099eac6fdd35fda54fc29008cf458fbe
|
|
| MD5 |
c9378471b649ecf22fbdd5b97d59a8e0
|
|
| BLAKE2b-256 |
1dbc02d04bbb3631d9ae48dbd67c84696a32037200ebb2178c6a5a4c9d1ad650
|
Provenance
The following attestation bundles were made for cattorch-0.2.0.tar.gz:
Publisher:
publish.yml on NormallyNormal/cattorch
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cattorch-0.2.0.tar.gz -
Subject digest:
9861c49bf03e4a5aee3c2bf1e0500ac9099eac6fdd35fda54fc29008cf458fbe - Sigstore transparency entry: 1266571989
- Sigstore integration time:
-
Permalink:
NormallyNormal/cattorch@f680d3ed801a8f3a57b62e2f3a44d9bb4436f0ea -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/NormallyNormal
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@f680d3ed801a8f3a57b62e2f3a44d9bb4436f0ea -
Trigger Event:
release
-
Statement type:
File details
Details for the file cattorch-0.2.0-py3-none-any.whl.
File metadata
- Download URL: cattorch-0.2.0-py3-none-any.whl
- Upload date:
- Size: 60.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e4d3e54717bd9024eb0ee8dafd3cf7f9933819b318ecf17cec5f19a19ba09517
|
|
| MD5 |
08602d60deef53834e1f63ec89b119cc
|
|
| BLAKE2b-256 |
fdb0ea29e1aa6ea0f981e4e74829452e218d7bde77621a4d1c85c239093c4076
|
Provenance
The following attestation bundles were made for cattorch-0.2.0-py3-none-any.whl:
Publisher:
publish.yml on NormallyNormal/cattorch
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cattorch-0.2.0-py3-none-any.whl -
Subject digest:
e4d3e54717bd9024eb0ee8dafd3cf7f9933819b318ecf17cec5f19a19ba09517 - Sigstore transparency entry: 1266572067
- Sigstore integration time:
-
Permalink:
NormallyNormal/cattorch@f680d3ed801a8f3a57b62e2f3a44d9bb4436f0ea -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/NormallyNormal
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@f680d3ed801a8f3a57b62e2f3a44d9bb4436f0ea -
Trigger Event:
release
-
Statement type: