Create model.py
Browse files
model.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import json
|
| 4 |
+
from safetensors.torch import load_file
|
| 5 |
+
|
| 6 |
+
class ConvBlock(nn.Module):
|
| 7 |
+
def __init__(self, in_c, out_c):
|
| 8 |
+
super().__init__()
|
| 9 |
+
self.conv = nn.Sequential(
|
| 10 |
+
nn.Conv2d(in_c, out_c, 3, padding=1),
|
| 11 |
+
nn.BatchNorm2d(out_c),
|
| 12 |
+
nn.ReLU(),
|
| 13 |
+
nn.Conv2d(out_c, out_c, 3, padding=1),
|
| 14 |
+
nn.BatchNorm2d(out_c),
|
| 15 |
+
nn.ReLU()
|
| 16 |
+
)
|
| 17 |
+
def forward(self, x): return self.conv(x)
|
| 18 |
+
|
| 19 |
+
class AlphaUNet(nn.Module):
|
| 20 |
+
def __init__(self):
|
| 21 |
+
super().__init__()
|
| 22 |
+
# Encoder
|
| 23 |
+
self.enc1 = ConvBlock(3, 32)
|
| 24 |
+
self.pool = nn.MaxPool2d(2)
|
| 25 |
+
self.enc2 = ConvBlock(32, 64)
|
| 26 |
+
self.enc3 = ConvBlock(64, 128)
|
| 27 |
+
|
| 28 |
+
# Decoder
|
| 29 |
+
self.up2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
|
| 30 |
+
self.dec2 = ConvBlock(128 + 64, 64)
|
| 31 |
+
self.up1 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
|
| 32 |
+
self.dec1 = ConvBlock(64 + 32, 32)
|
| 33 |
+
|
| 34 |
+
self.final = nn.Conv2d(32, 1, 1)
|
| 35 |
+
self.sigmoid = nn.Sigmoid()
|
| 36 |
+
|
| 37 |
+
def forward(self, x):
|
| 38 |
+
e1 = self.enc1(x)
|
| 39 |
+
e2 = self.enc2(self.pool(e1))
|
| 40 |
+
e3 = self.enc3(self.pool(e2))
|
| 41 |
+
|
| 42 |
+
d2 = self.up2(e3)
|
| 43 |
+
d2 = torch.cat([d2, e2], dim=1)
|
| 44 |
+
d2 = self.dec2(d2)
|
| 45 |
+
|
| 46 |
+
d1 = self.up1(d2)
|
| 47 |
+
d1 = torch.cat([d1, e1], dim=1)
|
| 48 |
+
d1 = self.dec1(d1)
|
| 49 |
+
|
| 50 |
+
return self.sigmoid(self.final(d1))
|
| 51 |
+
|
| 52 |
+
# Метод для удобной загрузки
|
| 53 |
+
@classmethod
|
| 54 |
+
def from_pretrained(cls, path="."):
|
| 55 |
+
model = cls()
|
| 56 |
+
# Грузим Safetensors
|
| 57 |
+
try:
|
| 58 |
+
state_dict = load_file(f"{path}/model.safetensors")
|
| 59 |
+
model.load_state_dict(state_dict)
|
| 60 |
+
print(">>> AlphaDepth loaded from .safetensors")
|
| 61 |
+
except FileNotFoundError:
|
| 62 |
+
print("Error: model.safetensors not found.")
|
| 63 |
+
return model
|