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.
See: Tensor.batchnorm
norm = nn.BatchNorm(3)
t = Tensor.rand(2, 3, 4, 4)
print(t.mean().item(), t.std().item())
0.5637954473495483 0.2746226191520691
t = norm(t)
print(t.mean().item(), t.std().item())
0.5637925863265991 0.27462121844291687
Source code in tinygrad/nn/__init__.py
32 33 34 35 36 37 38 39 | |
Conv1d
¤
Conv1d(
in_channels: int,
out_channels: int,
kernel_size: int,
stride=1,
padding: 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.9976 0.7907 0.259 0.6945]]]
t = conv(t)
print(t.numpy())
[[[0.6321 0.8225]]]
Source code in tinygrad/nn/__init__.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |
Conv2d
¤
Conv2d(
in_channels: int,
out_channels: int,
kernel_size: int | tuple[int, ...],
stride=1,
padding: 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.0757 0.8883 0.0217 0.8138]
[0.5258 0.8617 0.5675 0.8134]
[0.6212 0.444 0.7248 0.8333]
[0.5865 0.333 0.2491 0.2921]]]]
t = conv(t)
print(t.numpy())
[[[[-0.4562 -0.6897]
[-0.4155 -0.5447]]]]
Source code in tinygrad/nn/__init__.py
96 97 98 99 100 101 102 103 104 105 106 107 | |
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.4502 0.8436 0.16 0.5108]]]
t = conv(t)
print(t.numpy())
[[[0.6609 0.8448 0.6035 0.7054 0.5158 0.4887]]]
Source code in tinygrad/nn/__init__.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
ConvTranspose2d
¤
ConvTranspose2d(
in_channels: int,
out_channels: int,
kernel_size: 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.4952 0.9488 0.6573 0.8941]
[0.5037 0.0963 0.6511 0.26 ]
[0.5433 0.0289 0.9932 0.615 ]
[0.1001 0.8292 0.7317 0.831 ]]]]
t = conv(t)
print(t.numpy())
[[[[-0.0021 -0.1133 -0.1806 -0.1092 -0.1486 0.0428]
[ 0.0585 -0.0172 0.1394 0.196 0.0944 0.266 ]
[ 0.0449 -0.2152 0.0477 -0.3644 -0.0702 0.0448]
[ 0.0594 -0.1311 0.0339 -0.2116 0.0204 0.1932]
[ 0.0061 0.0367 -0.0037 0.1457 0.008 0.1979]
[ 0.0062 -0.0262 -0.1181 -0.1575 -0.1399 -0.0462]]]]
Source code in tinygrad/nn/__init__.py
146 147 148 149 150 151 | |
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.7369 0.357 0.552 ]
[0.7649 0.8311 0.6705]]
t = lin(t)
print(t.numpy())
[[-0.1068 0.76 0.755 -0.323 ]
[-0.3972 0.974 0.6014 -0.2679]]
Source code in tinygrad/nn/__init__.py
172 173 174 175 | |
GroupNorm
¤
Applies Group Normalization over a mini-batch of inputs.
norm = nn.GroupNorm(2, 12)
t = Tensor.rand(2, 12, 4, 4) * 2 + 1
print(t.mean().item(), t.std().item())
2.0552477836608887 0.5583968162536621
t = norm(t)
print(t.mean().item(), t.std().item())
-1.584819386835079e-07 1.0012880563735962
Source code in tinygrad/nn/__init__.py
195 196 197 198 | |
InstanceNorm
¤
Applies Instance Normalization over a mini-batch of inputs.
norm = nn.InstanceNorm(3)
t = Tensor.rand(2, 3, 4, 4) * 2 + 1
print(t.mean().item(), t.std().item())
1.9553427696228027 0.5989101529121399
t = norm(t)
print(t.mean().item(), t.std().item())
-2.892409156629583e-08 1.0052343606948853
Source code in tinygrad/nn/__init__.py
225 226 227 228 | |
LayerNorm
¤
LayerNorm(
normalized_shape: int | tuple[int, ...],
eps: float = 1e-05,
elementwise_affine: bool = True,
)
Applies Layer Normalization over a mini-batch of inputs.
norm = nn.LayerNorm(3)
t = Tensor.rand(2, 5, 3) * 2 + 1
print(t.mean().item(), t.std().item())
2.1495094299316406 0.5331981778144836
t = norm(t)
print(t.mean().item(), t.std().item())
-4.4447091340771294e-07 1.01702880859375
Source code in tinygrad/nn/__init__.py
251 252 253 254 255 | |
LayerNorm2d
¤
LayerNorm2d(
normalized_shape: int | tuple[int, ...],
eps: float = 1e-05,
elementwise_affine: bool = True,
)
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.995133638381958 0.5704997181892395
t = norm(t)
print(t.mean().item(), t.std().item())
-2.039905950823595e-07 1.0051875114440918
Source code in tinygrad/nn/__init__.py
251 252 253 254 255 | |
RMSNorm
¤
RMSNorm(dim: int, eps=1e-06, elementwise_affine=True)
Applies Root Mean Square Normalization to input.
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
296 297 298 | |
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.3989 0.0204 0.2396]
[ 0.0843 0.4843 0.5914]
[-0.1359 -0.6479 0.6577]
[ 0.3989 0.0204 0.2396]]
Source code in tinygrad/nn/__init__.py
357 358 | |
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_ihandb_hh
Source code in tinygrad/nn/__init__.py
374 375 376 377 378 379 | |
Optimizers¤
SGD
¤
SGD(
params: list[Tensor],
lr=0.001,
momentum=0.0,
weight_decay=0.0,
nesterov=False,
classic=False,
device=None,
fused=FUSE_OPTIM,
)
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.
Source code in tinygrad/nn/optim.py
77 78 79 80 81 82 83 | |
LARS
¤
LARS(
params: list[Tensor],
lr=0.001,
momentum=0.9,
weight_decay=0.0001,
ns_steps=0,
ns_coefficients=None,
nesterov=False,
classic=True,
pre_wd=True,
tcoef=0.001,
device=None,
fused=FUSE_OPTIM,
)
Bases: Optimizer
Layer-wise Adaptive Rate Scaling (LARS) optimizer with optional momentum and weight decay.
Source code in tinygrad/nn/optim.py
104 105 106 107 108 109 | |
AdamW
¤
AdamW(
params: list[Tensor],
lr=0.001,
b1=0.9,
b2=0.999,
eps=1e-08,
weight_decay=0.01,
device=None,
fused=FUSE_OPTIM,
)
AdamW optimizer with optional weight decay.
Source code in tinygrad/nn/optim.py
134 135 136 137 138 139 140 | |
Adam
¤
Adam optimizer.
Source code in tinygrad/nn/optim.py
141 142 143 144 145 146 147 | |
LAMB
¤
LAMB(
params: list[Tensor],
lr=0.001,
b1=0.9,
b2=0.999,
eps=1e-06,
weight_decay=0.0,
adam=False,
device=None,
fused=FUSE_OPTIM,
)
Bases: Optimizer
LAMB optimizer with optional weight decay.
Source code in tinygrad/nn/optim.py
155 156 157 158 159 160 | |
Load/Save¤
safe_load
¤
Loads a .safetensor file, returning the state_dict.
state_dict = nn.state.safe_load("test.safetensor")
Source code in tinygrad/nn/state.py
50 51 52 53 54 55 56 57 58 59 60 61 | |
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
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
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
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
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
112 113 114 115 116 117 118 119 120 121 122 123 124 | |
load_state_dict
¤
load_state_dict(
model,
state_dict: dict[str, Tensor],
strict=True,
verbose=True,
consume=False,
realize=True,
) -> list[Tensor]
Loads a state_dict into a model. Return the loaded Tensors.
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
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
tar_extract
¤
tar_extract(fn: Tensor | str | Path) -> dict[str, Tensor]
Extracts files from a tar archive and returns them as a dictionary of names (keys) and tensors (values).
tensors = nn.state.tar_extract(Tensor(pathlib.Path("archive.tar")))
Source code in tinygrad/nn/state.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
torch_load
¤
torch_load(fn: Tensor | str | Path) -> dict[str, Tensor]
Loads a torch .pth file, returning the state_dict.
state_dict = nn.state.torch_load("test.pth")
Source code in tinygrad/nn/state.py
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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | |
gguf_load
¤
Loads a .gguf file, returning the kv_data and state_dict.
gguf_tensor = Tensor(pathlib.Path("Meta-Llama-3-8B-Instruct.Q4_0.gguf")).to(Device.DEFAULT)
kv_data, state_dict = nn.state.gguf_load(gguf_tensor)
Note
The provided tensor must be on a device that supports execution.
Source code in tinygrad/nn/state.py
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | |