nn (神经网络)
神经网络类¤
批量归一化
¤
BatchNorm(
sz: int,
eps=1e-05,
affine=True,
track_running_stats=True,
momentum=0.1,
)
对2D或3D输入应用批量归一化。
参见:Tensor.batchnorm
norm = nn.BatchNorm(3)
t = Tensor.rand(2, 3, 4, 4)
print(t.mean().item(), t.std().item())
0.4998628497123718 0.2808046340942383
t = norm(t)
print(t.mean().item(), t.std().item())
0.49986034631729126 0.28080320358276367
Source code in tinygrad/nn/__init__.py
34 35 36 37 38 39 40 41 | |
一维卷积
¤
Conv1d(
in_channels: int,
out_channels: int,
kernel_size: int,
stride=1,
padding: int | str = 0,
dilation=1,
groups=1,
bias=True,
) -> Conv2d
对由多个输入平面组成的输入信号应用一维卷积。
参见: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.8795 0.4541 0.0097 0.2058]]]
t = conv(t)
print(t.numpy())
[[[-0.4703 -0.4046]]]
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: int | tuple[int, ...],
stride=1,
padding: int | tuple[int, ...] | str = 0,
dilation=1,
groups=1,
bias=True,
)
对由多个输入平面组成的输入信号应用二维卷积。
参见: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.5956 0.5147 0.3872 0.0464]
[0.2841 0.1229 0.127 0.7098]
[0.6705 0.9473 0.0979 0.2868]
[0.0245 0.9172 0.4672 0.1833]]]]
t = conv(t)
print(t.numpy())
[[[[-0.3339 -0.2574]
[-0.6481 -0.3689]]]]
Source code in tinygrad/nn/__init__.py
98 99 100 101 102 103 104 105 106 107 108 109 | |
转置一维卷积
¤
ConvTranspose1d(
in_channels: int,
out_channels: int,
kernel_size: int,
stride=1,
padding=0,
output_padding=0,
dilation=1,
groups=1,
bias=True,
) -> ConvTranspose2d
对由多个输入平面组成的输入信号应用一维转置卷积算子。
参见: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.9025 0.3978 0.601 0.7668]]]
t = conv(t)
print(t.numpy())
[[[ 0.8251 0.248 0.1295 0.3344 -0.1166 0.1377]]]
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 | |
转置卷积2d
¤
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,
)
基类: Conv2d
在输入图像上应用二维转置卷积算子。
参见: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.6829 0.2292 0.1909 0.888 ]
[0.6999 0.8085 0.1654 0.9843]
[0.1998 0.2293 0.091 0.4039]
[0.8206 0.4123 0.0447 0.3923]]]]
t = conv(t)
print(t.numpy())
[[[[-0.2541 -0.3563 -0.0659 -0.2146 -0.3248 0.0389]
[-0.1354 -0.4135 -0.1794 0.0927 -0.4686 0.0287]
[-0.0449 -0.0472 -0.2827 0.0577 -0.2218 -0.2035]
[-0.1392 -0.1152 0.0947 0.0361 -0.1357 -0.1851]
[-0.0776 -0.2038 -0.2736 -0.1436 -0.2096 -0.2815]
[-0.1477 -0.0126 -0.1864 -0.2079 -0.1586 -0.2629]]]]
Source code in tinygrad/nn/__init__.py
148 149 150 151 152 153 | |
线性层
¤
对输入数据应用线性变换。
参见:https://pytorch.org/docs/stable/generated/torch.nn.Linear
lin = nn.Linear(3, 4)
t = Tensor.rand(2, 3)
print(t.numpy())
[[0.8863 0.7761 0.1925]
[0.6193 0.3755 0.0885]]
t = lin(t)
print(t.numpy())
[[ 0.4911 -0.4845 -0.3609 -0.1215]
[ 0.4408 -0.0994 -0.442 -0.3155]]
Source code in tinygrad/nn/__init__.py
174 175 176 177 | |
GroupNorm
¤
在小批量输入上应用组归一化。
norm = nn.GroupNorm(2, 12)
t = Tensor.rand(2, 12, 4, 4) * 2 + 1
print(t.mean().item(), t.std().item())
2.013486385345459 0.5788871645927429
t = norm(t)
print(t.mean().item(), t.std().item())
-3.140890783015493e-07 1.0012893676757812
Source code in tinygrad/nn/__init__.py
198 199 200 201 | |
实例归一化
¤
InstanceNorm(num_features: int, eps=1e-05, affine=True)
对输入的小批量数据应用实例归一化。
norm = nn.InstanceNorm(3)
t = Tensor.rand(2, 3, 4, 4) * 2 + 1
print(t.mean().item(), t.std().item())
1.931043028831482 0.5658571124076843
t = norm(t)
print(t.mean().item(), t.std().item())
4.189885416394645e-08 1.0052311420440674
Source code in tinygrad/nn/__init__.py
229 230 231 232 | |
层归一化
¤
对输入的小批量应用层归一化。
norm = nn.LayerNorm(3)
t = Tensor.rand(2, 5, 3) * 2 + 1
print(t.mean().item(), t.std().item())
2.180391788482666 0.5629109144210815
t = norm(t)
print(t.mean().item(), t.std().item())
-3.212850572253956e-07 1.0170164108276367
Source code in tinygrad/nn/__init__.py
256 257 258 259 260 | |
LayerNorm2d
¤
基类: LayerNorm
对2D输入的小批量应用层归一化。
参见:LayerNorm
norm = nn.LayerNorm2d(3)
t = Tensor.rand(2, 3, 4, 4) * 2 + 1
print(t.mean().item(), t.std().item())
1.9809415340423584 0.5907070636749268
t = norm(t)
print(t.mean().item(), t.std().item())
-1.9173016596596426e-07 1.0051860809326172
Source code in tinygrad/nn/__init__.py
256 257 258 259 260 | |
RMSNorm
¤
RMSNorm(dim: int, eps=1e-06)
对输入应用均方根归一化。
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 | |
嵌入
¤
一个简单的查找表,用于存储固定字典和大小的嵌入向量。
参见:https://pytorch.org/docs/stable/generated/torch.nn.Embedding
emb = nn.Embedding(10, 3)
print(emb(Tensor([1, 2, 3, 1])).numpy())
[[ 0.5506 0.2185 -0.3325]
[-0.1563 0.527 -0.6618]
[ 0.2488 -0.338 -0.4311]
[ 0.5506 0.2185 -0.3325]]
Source code in tinygrad/nn/__init__.py
319 320 | |
LSTMCell
¤
长短期记忆(LSTM)单元。
参数:
-
input_size(int) –输入
x中预期的特征数量 -
hidden_size(int) –隐藏状态
h中的特征数量 -
bias(bool, default:True) –如果设为
False,则该层不使用偏置权重b_ih和b_hh
Source code in tinygrad/nn/__init__.py
337 338 339 340 341 342 | |
优化器¤
SGD
¤
SGD(
params: list[Tensor],
lr=0.001,
momentum=0.0,
weight_decay=0.0,
nesterov=False,
classic=False,
)
随机梯度下降(SGD)优化器,可选动量和权重衰减。
classic 是一个布尔标志,用于确定是使用流行的动量更新规则还是经典动量更新规则。
Source code in tinygrad/nn/optim.py
58 59 60 61 62 63 64 65 66 | |
LARS
¤
LARS(
params: list[Tensor],
lr=0.001,
momentum=0.9,
weight_decay=0.0001,
nesterov=False,
classic=True,
tcoef=0.001,
)
基类: Optimizer
层自适应学习率缩放(LARS)优化器,可选动量和权重衰减。
Source code in tinygrad/nn/optim.py
75 76 77 78 | |
AdamW
¤
带有可选权重衰减的AdamW优化器。
Source code in tinygrad/nn/optim.py
101 102 103 104 105 106 107 108 | |
Adam
¤
Adam优化器。
Source code in tinygrad/nn/optim.py
109 110 111 112 113 114 115 116 | |
LAMB
¤
基类: Optimizer
带有可选权重衰减的LAMB优化器。
Source code in tinygrad/nn/optim.py
125 126 127 128 129 130 | |
加载/保存¤
safe_load
¤
加载一个.safetensor文件,返回state_dict。
state_dict = nn.state.safe_load("test.safetensor")
Source code in tinygrad/nn/state.py
51 52 53 54 55 56 57 58 59 60 61 62 | |
safe_save
¤
将state_dict保存到.safetensor格式的磁盘文件中,可包含可选元数据。
t = Tensor([1, 2, 3])
nn.state.safe_save({'t':t}, "test.safetensor")
Source code in tinygrad/nn/state.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | |
获取状态字典
¤
返回对象的state_dict,可选择添加前缀。
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
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | |
获取参数
¤
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
113 114 115 116 117 118 119 120 121 122 123 124 125 | |
load_state_dict
¤
load_state_dict(
model,
state_dict: dict[str, Tensor],
strict=True,
verbose=True,
consume=False,
realize=True,
) -> None
将 state_dict 加载到模型中。
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
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 | |
tar_extract
¤
tar_extract(fn: Tensor | str | Path) -> dict[str, Tensor]
从tar存档中提取文件,并将它们作为名称(键)和张量(值)的字典返回。
tensors = nn.state.tar_extract(Tensor(pathlib.Path("archive.tar")))
Source code in tinygrad/nn/state.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
torch_load
¤
torch_load(fn: Tensor | str | Path) -> dict[str, Tensor]
加载一个torch .pth文件,返回state_dict。
state_dict = nn.state.torch_load("test.pth")
Source code in tinygrad/nn/state.py
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 259 260 261 262 263 264 265 266 267 | |
gguf加载
¤
加载一个.gguf文件,返回kv_data和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)
注意
提供的张量必须位于支持执行的设备上。
Source code in tinygrad/nn/state.py
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 328 329 330 331 332 333 334 335 336 337 | |