nn (Neural Networks)
Neural Network classes¤
BatchNorm
¤
BatchNorm(
sz: int,
eps=1e-05,
affine=True,
track_running_stats=True,
momentum=0.1,
)
Applies Batch Normalization over a 2D or 3D input.
- Described: https://paperswithcode.com/method/batch-normalization
- Paper: https://arxiv.org/abs/1502.03167v3
See: Tensor.batchnorm
norm = nn.BatchNorm(3)
t = Tensor.rand(2, 3, 4, 4)
print(t.mean().item(), t.std().item())
0.48813503980636597 0.26766568422317505
t = norm(t)
print(t.mean().item(), t.std().item())
0.48813265562057495 0.2676643133163452
Source code in tinygrad/nn/__init__.py
33 34 35 36 37 38 39 40 |
|
Conv1d
¤
Conv1d(
in_channels: int,
out_channels: int,
kernel_size: int,
stride=1,
padding: Union[int, str] = 0,
dilation=1,
groups=1,
bias=True,
) -> Conv2d
Applies a 1D convolution over an input signal composed of several input planes.
See: https://pytorch.org/docs/stable/generated/torch.nn.Conv1d
conv = nn.Conv1d(1, 1, 3)
t = Tensor.rand(1, 1, 4)
print(t.numpy())
[[[0.1333 0.21 0.5996 0.7089]]]
t = conv(t)
print(t.numpy())
[[[0.6909 0.8119]]]
Source code in tinygrad/nn/__init__.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
|
Conv2d
¤
Conv2d(
in_channels: int,
out_channels: int,
kernel_size: Union[int, Tuple[int, ...]],
stride=1,
padding: Union[int, Tuple[int, ...], str] = 0,
dilation=1,
groups=1,
bias=True,
)
Applies a 2D convolution over an input signal composed of several input planes.
See: https://pytorch.org/docs/stable/generated/torch.nn.Conv2d
conv = nn.Conv2d(1, 1, 3)
t = Tensor.rand(1, 1, 4, 4)
print(t.numpy())
[[[[0.5637 0.9418 0.1501 0.0721]
[0.5351 0.9291 0.9645 0.4105]
[0.6076 0.4562 0.3145 0.0646]
[0.1334 0.8011 0.5923 0.7519]]]]
t = conv(t)
print(t.numpy())
[[[[-0.0954 0.1449]
[-0.4339 -0.1308]]]]
Source code in tinygrad/nn/__init__.py
97 98 99 100 101 102 103 104 105 106 107 108 |
|
ConvTranspose1d
¤
ConvTranspose1d(
in_channels: int,
out_channels: int,
kernel_size: int,
stride=1,
padding=0,
output_padding=0,
dilation=1,
groups=1,
bias=True,
) -> ConvTranspose2d
Applies a 1D transposed convolution operator over an input signal composed of several input planes.
See: https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose1d
conv = nn.ConvTranspose1d(1, 1, 3)
t = Tensor.rand(1, 1, 4)
print(t.numpy())
[[[0.407 0.1677 0.6421 0.1428]]]
t = conv(t)
print(t.numpy())
[[[-0.1249 0.0191 -0.2948 0.0105 -0.34 -0.146 ]]]
Source code in tinygrad/nn/__init__.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
|
ConvTranspose2d
¤
ConvTranspose2d(
in_channels: int,
out_channels: int,
kernel_size: Union[int, Tuple[int, ...]],
stride=1,
padding=0,
output_padding=0,
dilation=1,
groups=1,
bias=True,
)
Bases: Conv2d
Applies a 2D transposed convolution operator over an input image.
See: https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d
conv = nn.ConvTranspose2d(1, 1, 3)
t = Tensor.rand(1, 1, 4, 4)
print(t.numpy())
[[[[0.2271 0.4946 0.8946 0.9734]
[0.4705 0.7959 0.1621 0.2005]
[0.7979 0.778 0.4659 0.8091]
[0.207 0.7506 0.3738 0.7326]]]]
t = conv(t)
print(t.numpy())
[[[[-5.9595e-02 -8.1108e-02 -1.1829e-01 -1.4059e-01 -9.5944e-02
-7.4882e-02]
[-6.5152e-02 -7.6131e-02 -4.4778e-02 -3.5914e-02 -6.2154e-02
-1.0195e-01]
[-8.7509e-02 -1.0108e-01 -1.5585e-01 -2.0912e-01 -4.3880e-02
1.9019e-02]
[-5.2298e-02 -1.0309e-01 -8.9908e-02 -4.9092e-02 -6.0791e-02
-8.8851e-02]
[-8.1335e-02 -9.5845e-02 1.3680e-04 -3.1695e-02 -3.4261e-02
-1.0519e-03]
[-5.7283e-02 -9.8847e-02 -8.8231e-02 -3.0809e-02 -4.9739e-02
2.8787e-02]]]]
Source code in tinygrad/nn/__init__.py
148 149 150 151 152 153 |
|
Linear
¤
Applies a linear transformation to the incoming data.
See: https://pytorch.org/docs/stable/generated/torch.nn.Linear
lin = nn.Linear(3, 4)
t = Tensor.rand(2, 3)
print(t.numpy())
[[0.8387 0.9282 0.4717]
[0.3353 0.7305 0.4038]]
t = lin(t)
print(t.numpy())
[[-0.2899 -0.1599 0.2025 0.0913]
[-0.081 -0.0185 0.0257 -0.0395]]
Source code in tinygrad/nn/__init__.py
175 176 177 178 |
|
GroupNorm
¤
Applies Group Normalization over a mini-batch of inputs.
- Described: https://paperswithcode.com/method/group-normalization
- Paper: https://arxiv.org/abs/1803.08494v3
norm = nn.GroupNorm(2, 12)
t = Tensor.rand(2, 12, 4, 4) * 2 + 1
print(t.mean().item(), t.std().item())
2.043626308441162 0.5761982798576355
t = norm(t)
print(t.mean().item(), t.std().item())
-4.575579168886179e-07 1.0012890100479126
Source code in tinygrad/nn/__init__.py
200 201 202 203 |
|
InstanceNorm
¤
InstanceNorm(num_features: int, eps=1e-05, affine=True)
Applies Instance Normalization over a mini-batch of inputs.
- Described: https://paperswithcode.com/method/instance-normalization
- Paper: https://arxiv.org/abs/1607.08022v3
norm = nn.InstanceNorm(3)
t = Tensor.rand(2, 3, 4, 4) * 2 + 1
print(t.mean().item(), t.std().item())
1.9982223510742188 0.5817040801048279
t = norm(t)
print(t.mean().item(), t.std().item())
-5.724819729380215e-08 1.005231261253357
Source code in tinygrad/nn/__init__.py
231 232 233 234 |
|
LayerNorm
¤
Applies Layer Normalization over a mini-batch of inputs.
- Described: https://paperswithcode.com/method/layer-normalization
- Paper: https://arxiv.org/abs/1607.06450v1
norm = nn.LayerNorm(3)
t = Tensor.rand(2, 5, 3) * 2 + 1
print(t.mean().item(), t.std().item())
2.0154693126678467 0.5521928668022156
t = norm(t)
print(t.mean().item(), t.std().item())
-4.6472601411551295e-07 1.0168763399124146
Source code in tinygrad/nn/__init__.py
258 259 260 261 |
|
LayerNorm2d
¤
Bases: LayerNorm
Applies Layer Normalization over a mini-batch of 2D inputs.
See: LayerNorm
norm = nn.LayerNorm2d(3)
t = Tensor.rand(2, 3, 4, 4) * 2 + 1
print(t.mean().item(), t.std().item())
1.998945713043213 0.5820763111114502
t = norm(t)
print(t.mean().item(), t.std().item())
-1.9154032315782388e-07 1.0051758289337158
Source code in tinygrad/nn/__init__.py
258 259 260 261 |
|
RMSNorm
¤
RMSNorm(dim: int, eps=1e-06)
Applies Root Mean Square Normalization to input.
- Described: https://paperswithcode.com/method/rmsnorm
- Paper: https://arxiv.org/abs/1910.07467
norm = nn.RMSNorm(4)
t = Tensor.arange(12, dtype=dtypes.float).reshape(3, 4)
print(t.numpy())
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]]
print(norm(t).numpy())
[[0. 0.5345 1.069 1.6036]
[0.7127 0.8909 1.069 1.2472]
[0.8363 0.9409 1.0454 1.15 ]]
Source code in tinygrad/nn/__init__.py
303 |
|
Embedding
¤
A simple lookup table that stores embeddings of a fixed dictionary and size.
See: https://pytorch.org/docs/stable/generated/torch.nn.Embedding
emb = nn.Embedding(10, 3)
print(emb(Tensor([1, 2, 3, 1])).numpy())
[[-0.1384 -0.5158 -0.2992]
[ 0.6021 -0.5924 -0.5033]
[-0.5763 -0.5539 -0.4381]
[-0.1384 -0.5158 -0.2992]]
Source code in tinygrad/nn/__init__.py
320 321 |
|
LSTMCell
¤
A long short-term memory (LSTM) cell.
Parameters:
-
input_size
(int
) –The number of expected features in the input
x
-
hidden_size
(int
) –The number of features in the hidden state
h
-
bias
(bool
, default:True
) –If
False
, then the layer does not use bias weightsb_ih
andb_hh
Source code in tinygrad/nn/__init__.py
339 340 341 342 343 |
|
Optimizers¤
SGD
¤
SGD(
params: List[Tensor],
lr=0.001,
momentum=0.0,
weight_decay=0.0,
nesterov=False,
classic=False,
)
Stochastic Gradient Descent (SGD) optimizer with optional momentum and weight decay.
classic
is a boolean flag that determines whether to use the popular momentum update rule or the classic momentum update rule.
- Described: https://paperswithcode.com/method/sgd
Source code in tinygrad/nn/optim.py
57 58 59 60 61 62 63 64 65 |
|
LARS
¤
LARS(
params: List[Tensor],
lr=0.001,
momentum=0.9,
weight_decay=0.0001,
nesterov=False,
classic=True,
tcoef=0.001,
)
Bases: Optimizer
Layer-wise Adaptive Rate Scaling (LARS) optimizer with optional momentum and weight decay.
- Described: https://paperswithcode.com/method/lars
- Paper: https://arxiv.org/abs/1708.03888v3
Source code in tinygrad/nn/optim.py
74 75 76 77 |
|
AdamW
¤
AdamW optimizer with optional weight decay.
- Described: https://paperswithcode.com/method/adamw
- Paper: https://arxiv.org/abs/1711.05101v3
Source code in tinygrad/nn/optim.py
102 103 104 105 106 107 108 109 |
|
Adam
¤
Adam optimizer.
- Described: https://paperswithcode.com/method/adam
- Paper: https://arxiv.org/abs/1412.6980
Source code in tinygrad/nn/optim.py
110 111 112 113 114 115 116 117 |
|
LAMB
¤
Bases: Optimizer
LAMB optimizer with optional weight decay.
- Described: https://paperswithcode.com/method/lamb
- Paper: https://arxiv.org/abs/1904.00962
Source code in tinygrad/nn/optim.py
126 127 128 129 130 131 |
|
Load/Save¤
safe_load
¤
Loads a .safetensor file from disk, returning the state_dict.
state_dict = nn.state.safe_load("test.safetensor")
Source code in tinygrad/nn/state.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
safe_save
¤
Saves a state_dict to disk in a .safetensor file with optional metadata.
t = Tensor([1, 2, 3])
nn.state.safe_save({'t':t}, "test.safetensor")
Source code in tinygrad/nn/state.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|
get_state_dict
¤
Returns a state_dict of the object, with optional prefix.
class Net:
def __init__(self):
self.l1 = nn.Linear(4, 5)
self.l2 = nn.Linear(5, 6)
net = Net()
print(nn.state.get_state_dict(net).keys())
dict_keys(['l1.weight', 'l1.bias', 'l2.weight', 'l2.bias'])
Source code in tinygrad/nn/state.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
|
get_parameters
¤
class Net:
def __init__(self):
self.l1 = nn.Linear(4, 5)
self.l2 = nn.Linear(5, 6)
net = Net()
print(len(nn.state.get_parameters(net)))
4
Source code in tinygrad/nn/state.py
87 88 89 90 91 92 93 94 95 96 97 98 99 |
|
load_state_dict
¤
load_state_dict(
model,
state_dict: Dict[str, Tensor],
strict=True,
verbose=True,
consume=False,
) -> None
Loads a state_dict into a model.
class Net:
def __init__(self):
self.l1 = nn.Linear(4, 5)
self.l2 = nn.Linear(5, 6)
net = Net()
state_dict = nn.state.get_state_dict(net)
nn.state.load_state_dict(net, state_dict)
Source code in tinygrad/nn/state.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
|
torch_load
¤
Loads a torch .pth file from disk.
state_dict = nn.state.torch_load("test.pth")
Source code in tinygrad/nn/state.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
|