19/31
Part 5 of 6 · A Linear layer, proved by gradcheckLearn
A Linear layer is MatMul plus a bias
The practice's last level puts a layer on top of your Function.
from torch import nn
class Linear(nn.Module):
def __init__(self, in_features: int, out_features: int) -> None:
super().__init__()
self.weight = nn.Parameter(torch.randn(in_features, out_features) / in_features ** 0.5)
self.bias = nn.Parameter(torch.zeros(out_features))
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""x: (..., in). Returns (..., out)."""
return MatMul.apply(x, self.weight) + self.bias
layer = Linear(3, 1)
print([(name, tuple(p.shape)) for name, p in layer.named_parameters()])
Linear(3, 1) stores a weight and a bias as nn.Parameter. What does named_parameters() list?
Pick one to see what it prints.
Pick an answer above to see the rest