-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlayers.py
More file actions
40 lines (34 loc) · 1008 Bytes
/
layers.py
File metadata and controls
40 lines (34 loc) · 1008 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
class ReLU(nn.Module):
def forward(self, x: Tensor) -> Tensor:
gain = math.sqrt(2)
return gain * x.relu()
class Conv2d(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int,
padding: int,
) -> None:
super().__init__()
gain = 1 / math.sqrt(in_channels * kernel_size * kernel_size)
self.weight = nn.Parameter(
gain * torch.randn((out_channels, in_channels, kernel_size, kernel_size))
)
self.bias = nn.Parameter(torch.zeros((out_channels,)))
self.stride = stride
self.padding = padding
def forward(self, x: Tensor) -> Tensor:
return F.conv2d(
input=x,
weight=self.weight,
bias=self.bias,
stride=self.stride,
padding=self.padding,
)