Download src/model.py from shyo2/cnn0: direct link, hf CLI and curl.
- Browser
- Download file 1.93 kB
-
https://huggingface.co/shyo2/cnn0/resolve/main/src/model.py
- Command line
-
hf download hf://shyo2/cnn0/src/model.py
-
curl -L -o model.py https://huggingface.co/shyo2/cnn0/resolve/main/src/model.py
1.93 kB
| import torch | |
| import torch.nn as nn | |
| class PlainBlock(nn.Module): | |
| def __init__(self, channels, bn=True): | |
| super().__init__() | |
| self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=not bn) | |
| self.bn1 = nn.BatchNorm2d(channels) if bn else nn.Identity() | |
| self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=not bn) | |
| self.bn2 = nn.BatchNorm2d(channels) if bn else nn.Identity() | |
| def forward(self, x): | |
| out = torch.relu(self.bn1(self.conv1(x))) | |
| out = self.bn2(self.conv2(out)) | |
| return torch.relu(out) | |
| class ResBlock(nn.Module): | |
| def __init__(self, channels, bn=True): | |
| super().__init__() | |
| self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=not bn) | |
| self.bn1 = nn.BatchNorm2d(channels) if bn else nn.Identity() | |
| self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=not bn) | |
| self.bn2 = nn.BatchNorm2d(channels) if bn else nn.Identity() | |
| def forward(self, x): | |
| out = torch.relu(self.bn1(self.conv1(x))) | |
| out = self.bn2(self.conv2(out)) | |
| return torch.relu(out + x) | |
| class CNN(nn.Module): | |
| def __init__(self, depth, channels=64, num_classes=10, use_residual=False, bn=True): | |
| super().__init__() | |
| block = ResBlock if use_residual else PlainBlock | |
| self.stem = nn.Sequential( | |
| nn.Conv2d(1, channels, 3, stride=2, padding=1, bias=not bn), | |
| nn.BatchNorm2d(channels) if bn else nn.Identity(), | |
| nn.ReLU(inplace=True), | |
| ) | |
| self.blocks = nn.Sequential(*[block(channels, bn) for _ in range(depth)]) | |
| self.fc = nn.Linear(channels, num_classes) | |
| def forward(self, x): | |
| x = self.stem(x) | |
| x = self.blocks(x) | |
| x = torch.nn.functional.adaptive_avg_pool2d(x, 1).flatten(1) | |
| return self.fc(x) | |
| def count_params(model): | |
| return sum(p.numel() for p in model.parameters()) | |