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.5503934621810913 0.29583078622817993
t = norm(t)
print(t.mean().item(), t.std().item())
0.5503906011581421 0.2958293557167053
Source code in tinygrad/nn/__init__.py
34 35 36 37 38 39 40 41 |
|
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.6944 0.885 0.0651 0.8116]]]
t = conv(t)
print(t.numpy())
[[[ 0.2012 -0.5826]]]
Source code in tinygrad/nn/__init__.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
|
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.429 0.8286 0.9955 0.9372]
[0.7824 0.5034 0.5371 0.2154]
[0.7706 0.6966 0.6172 0.9011]
[0.2546 0.4914 0.7198 0.4352]]]]
t = conv(t)
print(t.numpy())
[[[[-0.5456 -0.5856]
[-0.422 -0.4364]]]]
Source code in tinygrad/nn/__init__.py
98 99 100 101 102 103 104 105 106 107 108 109 |
|
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.6016 0.7056 0.315 0.83 ]]]
t = conv(t)
print(t.numpy())
[[[ 0.1591 -0.0357 0.0068 0.4761 -0.338 0.245 ]]]
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.4496 0.6639 0.6248 0.0882]
[0.1408 0.3608 0.0165 0.4955]
[0.7588 0.3654 0.1834 0.7262]
[0.3087 0.0625 0.0561 0.2665]]]]
t = conv(t)
print(t.numpy())
[[[[0.2168 0.1076 0.0712 0.1739 0.2734 0.3002]
[0.3153 0.2433 0.3367 0.2862 0.3344 0.306 ]
[0.2234 0.1647 0.0879 0.0178 0.0054 0.3538]
[0.3273 0.2546 0.3318 0.3341 0.1855 0.3134]
[0.419 0.2406 0.1625 0.3132 0.1665 0.1836]
[0.3387 0.2726 0.2304 0.3126 0.2574 0.2411]]]]
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.9726 0.6265 0.8876]
[0.3015 0.8213 0.1333]]
t = lin(t)
print(t.numpy())
[[ 0.9665 0.9826 -0.5089 0.9712]
[ 0.5128 0.2275 -0.2947 0.3601]]
Source code in tinygrad/nn/__init__.py
174 175 176 177 |
|
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.0031216144561768 0.5758187174797058
t = norm(t)
print(t.mean().item(), t.std().item())
4.539322162600001e-08 1.0012893676757812
Source code in tinygrad/nn/__init__.py
198 199 200 201 |
|
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())
2.0593199729919434 0.5625905394554138
t = norm(t)
print(t.mean().item(), t.std().item())
4.370501116568448e-08 1.0052322149276733
Source code in tinygrad/nn/__init__.py
229 230 231 232 |
|
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.2973506450653076 0.5354159474372864
t = norm(t)
print(t.mean().item(), t.std().item())
-4.42120665411494e-07 1.0169609785079956
Source code in tinygrad/nn/__init__.py
256 257 258 259 260 |
|
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())
2.0070536136627197 0.5694392919540405
t = norm(t)
print(t.mean().item(), t.std().item())
-2.434611587887048e-07 1.005044937133789
Source code in tinygrad/nn/__init__.py
256 257 258 259 260 |
|
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
302 |
|
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.5369 -0.4682 0.1494]
[-0.0284 -0.102 -0.3805]
[-0.3976 0.4794 -0.4422]
[-0.5369 -0.4682 0.1494]]
Source code in tinygrad/nn/__init__.py
319 320 |
|
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
337 338 339 340 341 342 |
|
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
101 102 103 104 105 106 107 108 |
|
Adam
¤
Adam optimizer.
- Described: https://paperswithcode.com/method/adam
- Paper: https://arxiv.org/abs/1412.6980
Source code in tinygrad/nn/optim.py
109 110 111 112 113 114 115 116 |
|
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
125 126 127 128 129 130 |
|
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
52 53 54 55 56 57 58 59 60 61 62 63 |
|
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
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
|
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
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
|
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
114 115 116 117 118 119 120 121 122 123 124 125 126 |
|
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
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 |
|
torch_load
¤
Loads a torch .pth file from disk.
state_dict = nn.state.torch_load("test.pth")
Source code in tinygrad/nn/state.py
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 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 |
|
gguf_load
¤
Loads a gguf file from a tensor.
fn = "Meta-Llama-3-8B-Instruct.Q4_0.gguf"
gguf_tensor = Tensor.empty(os.stat(fn).st_size, dtype=dtypes.uint8, device=f"disk:{fn}").to(Device.DEFAULT)
kv_data, state_dict = gguf_load(gguf_tensor)
Source code in tinygrad/nn/state.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
|