blocklearning 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- blocklearning/__init__.py +1 -0
- blocklearning/__main__.py +6 -0
- blocklearning/analysis.py +133 -0
- blocklearning/anomaly.py +148 -0
- blocklearning/blocks.py +601 -0
- blocklearning/cli.py +46 -0
- blocklearning/codegen.py +1012 -0
- blocklearning/core.py +861 -0
- blocklearning/data/bearing_uottawa.SOURCE.txt +6 -0
- blocklearning/data/bearing_uottawa.npz +0 -0
- blocklearning/data/concrete.SOURCE.txt +4 -0
- blocklearning/data/concrete.npz +0 -0
- blocklearning/data/digits32.SOURCE.txt +4 -0
- blocklearning/data/digits32.npz +0 -0
- blocklearning/data/ecg_mitdb.SOURCE.txt +6 -0
- blocklearning/data/ecg_mitdb.npz +0 -0
- blocklearning/data/hydraulic.SOURCE.txt +6 -0
- blocklearning/data/hydraulic.npz +0 -0
- blocklearning/data/pcb_det.SOURCE.txt +6 -0
- blocklearning/data/pcb_det.npz +0 -0
- blocklearning/data/pneumatic_seg.SOURCE.txt +8 -0
- blocklearning/data/pneumatic_seg.npz +0 -0
- blocklearning/data/pneumonia28.SOURCE.txt +13 -0
- blocklearning/data/pneumonia28.npz +0 -0
- blocklearning/data/steel_plates.SOURCE.txt +5 -0
- blocklearning/data/steel_plates.npz +0 -0
- blocklearning/data/steel_power.SOURCE.txt +3 -0
- blocklearning/data/steel_power.npz +0 -0
- blocklearning/data/steelblast.SOURCE.txt +4 -0
- blocklearning/data/steelblast.npz +0 -0
- blocklearning/data.py +1158 -0
- blocklearning/detect.py +222 -0
- blocklearning/forecast.py +204 -0
- blocklearning/graph.py +602 -0
- blocklearning/jobs.py +501 -0
- blocklearning/labeling.py +1294 -0
- blocklearning/labeling_sources.py +217 -0
- blocklearning/layers.py +615 -0
- blocklearning/losses.py +199 -0
- blocklearning/multi.py +175 -0
- blocklearning/nn_extra.py +643 -0
- blocklearning/predict.py +344 -0
- blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
- blocklearning/pretrained/mnv3s.SOURCE.txt +6 -0
- blocklearning/pretrained/mnv3s.bin +0 -0
- blocklearning/pretrained/mnv3s.json +1 -0
- blocklearning/pretrained.py +56 -0
- blocklearning/project.py +120 -0
- blocklearning/segment.py +173 -0
- blocklearning/server.py +116 -0
- blocklearning/static/app.js +1986 -0
- blocklearning/static/boot.js +51 -0
- blocklearning/static/demo.jpg +0 -0
- blocklearning/static/demo.webm +0 -0
- blocklearning/static/engine.js +1326 -0
- blocklearning/static/graph.js +1902 -0
- blocklearning/static/index.html +301 -0
- blocklearning/static/label.html +158 -0
- blocklearning/static/label.js +1040 -0
- blocklearning/static/labels.js +227 -0
- blocklearning/static/projects.js +516 -0
- blocklearning/static/store.js +259 -0
- blocklearning/static/style.css +844 -0
- blocklearning/static/train-worker.js +41 -0
- blocklearning/static/web.js +602 -0
- blocklearning/tasks.py +351 -0
- blocklearning/web.py +412 -0
- blocklearning/weblabel.py +316 -0
- blocklearning-0.1.0.dist-info/METADATA +66 -0
- blocklearning-0.1.0.dist-info/RECORD +74 -0
- blocklearning-0.1.0.dist-info/WHEEL +4 -0
- blocklearning-0.1.0.dist-info/entry_points.txt +2 -0
- blocklearning-0.1.0.dist-info/licenses/LICENSE +25 -0
- blocklearning-0.1.0.dist-info/licenses/src/blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
"""추가 블록의 PyTorch 모듈. studio 모델(blocks.make_layer)이 쓰고, 코드 내보내기는 쓴 클래스의 소스를 그대로 붙여 넣는다
|
|
2
|
+
(그래서 클래스마다 혼자 읽혀야 함: math·torch·nn·F만 씀). 값의 모양은 채널이 먼저: (N, C, L) · (N, C, H, W).
|
|
3
|
+
웹 엔진(static/engine.js)이 같은 식을 TF.js로 옮겼다 (tests/test_engine.py가 값이 같은지 확인).
|
|
4
|
+
"""
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
import torch.nn.functional as F
|
|
9
|
+
from torch import nn
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GLU(nn.Module):
|
|
13
|
+
"""위치마다 채널을 2·units개로 바꿔 반은 값, 반은 문(gate): 값 × σ(문) (GLU) 또는 값 × SiLU(문) (SwiGLU)."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, c, units, gate="sigmoid"):
|
|
16
|
+
super().__init__()
|
|
17
|
+
self.proj, self.gate = nn.Linear(c, 2 * units), gate
|
|
18
|
+
|
|
19
|
+
def forward(self, x):
|
|
20
|
+
h = self.proj(x.movedim(1, -1))
|
|
21
|
+
a, b = h.chunk(2, dim=-1)
|
|
22
|
+
y = a * (torch.sigmoid(b) if self.gate == "sigmoid" else F.silu(b))
|
|
23
|
+
return y.movedim(-1, 1)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SeparableConv(nn.Module):
|
|
27
|
+
"""Depthwise(채널마다 따로 k칸) + Pointwise(1칸으로 채널 섞기): 같은 일을 훨씬 적은 가중치로 (MobileNet·Xception)."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, c, out, k, dims=1):
|
|
30
|
+
super().__init__()
|
|
31
|
+
conv = nn.Conv2d if dims == 2 else nn.Conv1d
|
|
32
|
+
self.depthwise = conv(c, c, k, padding=k // 2, groups=c)
|
|
33
|
+
self.pointwise = conv(c, out, 1)
|
|
34
|
+
|
|
35
|
+
def forward(self, x):
|
|
36
|
+
return self.pointwise(self.depthwise(x))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class GlobalMax(nn.Module):
|
|
40
|
+
"""채널마다 전체에서 가장 큰 값."""
|
|
41
|
+
|
|
42
|
+
def forward(self, x):
|
|
43
|
+
return x.flatten(2).amax(-1)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class FirstStep(nn.Module):
|
|
47
|
+
"""채널마다 첫 위치 값 (CLS token 자리)."""
|
|
48
|
+
|
|
49
|
+
def forward(self, x):
|
|
50
|
+
return x[:, :, 0]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class AttentionPool(nn.Module):
|
|
54
|
+
"""위치마다 점수를 매겨 softmax 가중치로 평균: 중요한 위치를 더 많이 반영."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, c):
|
|
57
|
+
super().__init__()
|
|
58
|
+
self.score = nn.Linear(c, 1)
|
|
59
|
+
|
|
60
|
+
def forward(self, x):
|
|
61
|
+
s = x.flatten(2)
|
|
62
|
+
a = torch.softmax(self.score(s.transpose(1, 2)).squeeze(-1), dim=-1)
|
|
63
|
+
return (s * a.unsqueeze(1)).sum(-1)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class PixelShuffle(nn.Module):
|
|
67
|
+
"""채널을 위치로 옮겨 2배로 키움: (C·2, L) → (C, 2L), (C·4, H, W) → (C, 2H, 2W)."""
|
|
68
|
+
|
|
69
|
+
def forward(self, x):
|
|
70
|
+
if x.dim() == 4:
|
|
71
|
+
return F.pixel_shuffle(x, 2)
|
|
72
|
+
n, c, length = x.shape
|
|
73
|
+
return x.reshape(n, c // 2, 2, length).permute(0, 1, 3, 2).reshape(n, c // 2, length * 2)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ECA(nn.Module):
|
|
77
|
+
"""Efficient Channel Attention: 채널 평균을 이웃 채널끼리 k칸 Conv1D → sigmoid → 채널마다 곱함 (SE의 가벼운 판)."""
|
|
78
|
+
|
|
79
|
+
def __init__(self, k=3):
|
|
80
|
+
super().__init__()
|
|
81
|
+
self.conv = nn.Conv1d(1, 1, k, padding=k // 2, bias=False)
|
|
82
|
+
|
|
83
|
+
def forward(self, x):
|
|
84
|
+
s = torch.sigmoid(self.conv(x.flatten(2).mean(-1).unsqueeze(1))).squeeze(1)
|
|
85
|
+
return x * s.reshape(*s.shape, *([1] * (x.dim() - 2)))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class SpatialAttention(nn.Module):
|
|
89
|
+
"""위치마다 채널 평균·최댓값 → k칸 Conv → sigmoid: '어디를 볼지' 지도를 곱함 (CBAM의 공간 부분)."""
|
|
90
|
+
|
|
91
|
+
def __init__(self, k=7, dims=2):
|
|
92
|
+
super().__init__()
|
|
93
|
+
self.conv = (nn.Conv2d if dims == 2 else nn.Conv1d)(2, 1, k, padding=k // 2)
|
|
94
|
+
|
|
95
|
+
def forward(self, x):
|
|
96
|
+
m = torch.cat([x.mean(1, keepdim=True), x.amax(1, keepdim=True)], dim=1)
|
|
97
|
+
return x * torch.sigmoid(self.conv(m))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class CBAM(nn.Module):
|
|
101
|
+
"""채널 주의(평균·최댓값 → 같은 MLP → 더해 sigmoid) 다음 공간 주의 (Convolutional Block Attention Module)."""
|
|
102
|
+
|
|
103
|
+
def __init__(self, c, ratio=4, k=7, dims=2):
|
|
104
|
+
super().__init__()
|
|
105
|
+
h = max(1, c // ratio)
|
|
106
|
+
self.fc1, self.fc2 = nn.Linear(c, h), nn.Linear(h, c)
|
|
107
|
+
self.conv = (nn.Conv2d if dims == 2 else nn.Conv1d)(2, 1, k, padding=k // 2)
|
|
108
|
+
|
|
109
|
+
def forward(self, x):
|
|
110
|
+
f = x.flatten(2)
|
|
111
|
+
mlp = lambda v: self.fc2(torch.relu(self.fc1(v)))
|
|
112
|
+
ca = torch.sigmoid(mlp(f.mean(-1)) + mlp(f.amax(-1)))
|
|
113
|
+
x = x * ca.reshape(*ca.shape, *([1] * (x.dim() - 2)))
|
|
114
|
+
m = torch.cat([x.mean(1, keepdim=True), x.amax(1, keepdim=True)], dim=1)
|
|
115
|
+
return x * torch.sigmoid(self.conv(m))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class MultiHeadAttention(nn.Module):
|
|
119
|
+
"""Self-attention: 위치마다 질문(Q)·열쇠(K)·값(V)을 만들고, 질문과 맞는 열쇠의 값을 softmax 가중치로 모음 (head마다 따로).
|
|
120
|
+
causal이면 앞 위치만 봄 (GPT식). rope면 Q·K를 위치만큼 돌려 순서를 앎 (RoPE). 그림은 칸들을 한 줄로 보고 돌려놓음."""
|
|
121
|
+
|
|
122
|
+
def __init__(self, c, heads=2, causal=False, rope=False):
|
|
123
|
+
super().__init__()
|
|
124
|
+
self.qkv, self.proj = nn.Linear(c, 3 * c), nn.Linear(c, c)
|
|
125
|
+
self.heads, self.causal, self.rope = heads, causal, rope
|
|
126
|
+
|
|
127
|
+
@staticmethod
|
|
128
|
+
def rotate(x):
|
|
129
|
+
"""RoPE: (N, heads, T, d)의 짝지은 채널 (2i, 2i+1)을 위치 × 10000^(-2i/d)만큼 돌림."""
|
|
130
|
+
T, d = x.shape[-2], x.shape[-1]
|
|
131
|
+
inv = 10000.0 ** (-torch.arange(0, d, 2, dtype=x.dtype, device=x.device) / d)
|
|
132
|
+
ang = torch.arange(T, dtype=x.dtype, device=x.device)[:, None] * inv[None]
|
|
133
|
+
cos, sin = torch.cos(ang), torch.sin(ang)
|
|
134
|
+
x1, x2 = x[..., 0::2], x[..., 1::2]
|
|
135
|
+
return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).flatten(-2)
|
|
136
|
+
|
|
137
|
+
def forward(self, x):
|
|
138
|
+
shape = x.shape
|
|
139
|
+
s = x.flatten(2).transpose(1, 2) # (N, T, C)
|
|
140
|
+
n, t, c = s.shape
|
|
141
|
+
q, k, v = (z.reshape(n, t, self.heads, c // self.heads).transpose(1, 2) for z in self.qkv(s).chunk(3, dim=-1))
|
|
142
|
+
if self.rope:
|
|
143
|
+
q, k = self.rotate(q), self.rotate(k)
|
|
144
|
+
att = q @ k.transpose(-1, -2) / math.sqrt(c // self.heads)
|
|
145
|
+
if self.causal:
|
|
146
|
+
att = att.masked_fill(torch.ones(t, t, dtype=torch.bool, device=x.device).triu(1), -1e9)
|
|
147
|
+
y = (torch.softmax(att, dim=-1) @ v).transpose(1, 2).reshape(n, t, c)
|
|
148
|
+
return self.proj(y).transpose(1, 2).reshape(shape)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class LinearAttention(nn.Module):
|
|
152
|
+
"""softmax 대신 φ(x) = ELU(x) + 1로 (Q·K)V를 Q·(KᵀV)로 바꿔 길이에 비례하는 계산 (Linear Transformer)."""
|
|
153
|
+
|
|
154
|
+
def __init__(self, c, heads=2):
|
|
155
|
+
super().__init__()
|
|
156
|
+
self.qkv, self.proj, self.heads = nn.Linear(c, 3 * c), nn.Linear(c, c), heads
|
|
157
|
+
|
|
158
|
+
def forward(self, x):
|
|
159
|
+
shape = x.shape
|
|
160
|
+
s = x.flatten(2).transpose(1, 2)
|
|
161
|
+
n, t, c = s.shape
|
|
162
|
+
q, k, v = (z.reshape(n, t, self.heads, c // self.heads).transpose(1, 2) for z in self.qkv(s).chunk(3, dim=-1))
|
|
163
|
+
q, k = F.elu(q) + 1, F.elu(k) + 1
|
|
164
|
+
kv = k.transpose(-1, -2) @ v # (N, heads, d, d)
|
|
165
|
+
z = 1.0 / (q @ k.sum(-2, keepdim=True).transpose(-1, -2) + 1e-6) # (N, heads, T, 1)
|
|
166
|
+
y = ((q @ kv) * z).transpose(1, 2).reshape(n, t, c)
|
|
167
|
+
return self.proj(y).transpose(1, 2).reshape(shape)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class NonLocal(nn.Module):
|
|
171
|
+
"""Non-local block: 모든 위치 쌍의 관계(θᵀφ, softmax)로 g를 모아 1×1로 되돌린 뒤 입력에 더함 (먼 칸끼리)."""
|
|
172
|
+
|
|
173
|
+
def __init__(self, c):
|
|
174
|
+
super().__init__()
|
|
175
|
+
h = max(1, c // 2)
|
|
176
|
+
self.theta, self.phi, self.g, self.out = nn.Linear(c, h), nn.Linear(c, h), nn.Linear(c, h), nn.Linear(h, c)
|
|
177
|
+
|
|
178
|
+
def forward(self, x):
|
|
179
|
+
s = x.flatten(2).transpose(1, 2)
|
|
180
|
+
att = torch.softmax(self.theta(s) @ self.phi(s).transpose(1, 2), dim=-1)
|
|
181
|
+
y = self.out(att @ self.g(s))
|
|
182
|
+
return x + y.transpose(1, 2).reshape(x.shape)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class CrossAttention(nn.Module):
|
|
186
|
+
"""첫 입력(질문)의 위치마다 둘째 입력(참고)의 어디를 볼지 정해 값을 모음. 출력 모양은 첫 입력과 같음."""
|
|
187
|
+
|
|
188
|
+
def __init__(self, c, c2, heads=2):
|
|
189
|
+
super().__init__()
|
|
190
|
+
self.q, self.kv, self.proj, self.heads = nn.Linear(c, c), nn.Linear(c2, 2 * c), nn.Linear(c, c), heads
|
|
191
|
+
|
|
192
|
+
def forward(self, x, ctx):
|
|
193
|
+
shape = x.shape
|
|
194
|
+
s, r = x.flatten(2).transpose(1, 2), ctx.flatten(2).transpose(1, 2)
|
|
195
|
+
n, t, c = s.shape
|
|
196
|
+
split = lambda z: z.reshape(n, z.shape[1], self.heads, c // self.heads).transpose(1, 2)
|
|
197
|
+
k, v = self.kv(r).chunk(2, dim=-1)
|
|
198
|
+
q, k, v = split(self.q(s)), split(k), split(v)
|
|
199
|
+
att = torch.softmax(q @ k.transpose(-1, -2) / math.sqrt(c // self.heads), dim=-1)
|
|
200
|
+
y = (att @ v).transpose(1, 2).reshape(n, t, c)
|
|
201
|
+
return self.proj(y).transpose(1, 2).reshape(shape)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class PositionalEncoding(nn.Module):
|
|
205
|
+
"""위치마다 정해진 값을 더해 순서를 알려 줌: sin·cos 표 (고정) 또는 배우는 값 (learned)."""
|
|
206
|
+
|
|
207
|
+
def __init__(self, c, n, learned=False):
|
|
208
|
+
super().__init__()
|
|
209
|
+
if learned:
|
|
210
|
+
self.pe = nn.Parameter(torch.randn(c, n) * 0.02)
|
|
211
|
+
else:
|
|
212
|
+
pe = torch.tensor([[(math.sin if ch % 2 == 0 else math.cos)(p / 10000 ** ((ch - ch % 2) / c)) for p in range(n)]
|
|
213
|
+
for ch in range(c)])
|
|
214
|
+
self.register_buffer("pe", pe, persistent=False)
|
|
215
|
+
|
|
216
|
+
def forward(self, x):
|
|
217
|
+
return x + self.pe.reshape(x.shape[1:])
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class PatchEmbedding(nn.Module):
|
|
221
|
+
"""그림을 patch×patch 조각으로 잘라 조각마다 dim개 값으로 → (dim, 조각 수) 줄 (ViT의 입구)."""
|
|
222
|
+
|
|
223
|
+
def __init__(self, c, dim, patch):
|
|
224
|
+
super().__init__()
|
|
225
|
+
self.proj = nn.Conv2d(c, dim, patch, stride=patch)
|
|
226
|
+
|
|
227
|
+
def forward(self, x):
|
|
228
|
+
return self.proj(x).flatten(2)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class ClsToken(nn.Module):
|
|
232
|
+
"""줄 맨 앞에 배우는 자리 하나(CLS)를 붙임. 어텐션을 지난 뒤 FirstTimestep으로 꺼내 전체 요약으로 씀."""
|
|
233
|
+
|
|
234
|
+
def __init__(self, c):
|
|
235
|
+
super().__init__()
|
|
236
|
+
self.cls = nn.Parameter(torch.randn(c) * 0.02)
|
|
237
|
+
|
|
238
|
+
def forward(self, x):
|
|
239
|
+
return torch.cat([self.cls.reshape(1, -1, 1).expand(x.shape[0], -1, -1), x], dim=2)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class LayerNorm(nn.Module):
|
|
243
|
+
"""위치마다 채널 값들을 평균 0·분산 1로 맞춘 뒤 채널마다 배우는 배율·이동 (Transformer의 정규화)."""
|
|
244
|
+
|
|
245
|
+
def __init__(self, c):
|
|
246
|
+
super().__init__()
|
|
247
|
+
self.weight, self.bias = nn.Parameter(torch.ones(c)), nn.Parameter(torch.zeros(c))
|
|
248
|
+
|
|
249
|
+
def forward(self, x):
|
|
250
|
+
y = F.layer_norm(x.movedim(1, -1), (x.shape[1],), self.weight, self.bias, 1e-5)
|
|
251
|
+
return y.movedim(-1, 1)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class RMSNorm(nn.Module):
|
|
255
|
+
"""위치마다 채널 값들의 제곱평균으로만 나눔 (평균은 빼지 않음, LayerNorm보다 가벼움 · 최신 LLM)."""
|
|
256
|
+
|
|
257
|
+
def __init__(self, c):
|
|
258
|
+
super().__init__()
|
|
259
|
+
self.weight = nn.Parameter(torch.ones(c))
|
|
260
|
+
|
|
261
|
+
def forward(self, x):
|
|
262
|
+
y = x * torch.rsqrt(x.pow(2).mean(1, keepdim=True) + 1e-5)
|
|
263
|
+
return y * self.weight.reshape(-1, *([1] * (x.dim() - 2)))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
class DropPath(nn.Module):
|
|
267
|
+
"""학습 때 샘플마다 rate 확률로 이 길 전체를 0으로 (남은 것은 1/(1−rate)배). Residual 안 마지막에 둠 (Stochastic Depth)."""
|
|
268
|
+
|
|
269
|
+
def __init__(self, rate=0.1):
|
|
270
|
+
super().__init__()
|
|
271
|
+
self.rate = rate
|
|
272
|
+
|
|
273
|
+
def forward(self, x):
|
|
274
|
+
if not self.training or self.rate == 0:
|
|
275
|
+
return x
|
|
276
|
+
keep = (torch.rand(x.shape[0], *([1] * (x.dim() - 1)), device=x.device) >= self.rate).to(x.dtype)
|
|
277
|
+
return x * keep / (1 - self.rate)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class GaussianNoise(nn.Module):
|
|
281
|
+
"""학습 때만 평균 0·표준편차 std 잡음을 더함."""
|
|
282
|
+
|
|
283
|
+
def __init__(self, std=0.1):
|
|
284
|
+
super().__init__()
|
|
285
|
+
self.std = std
|
|
286
|
+
|
|
287
|
+
def forward(self, x):
|
|
288
|
+
return x + torch.randn_like(x) * self.std if self.training else x
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class Split(nn.Module):
|
|
292
|
+
"""채널 일부만 꺼냄 (start부터 count개). 같은 값에서 둘 이상 꺼내면 채널 나누기."""
|
|
293
|
+
|
|
294
|
+
def __init__(self, start, count):
|
|
295
|
+
super().__init__()
|
|
296
|
+
self.start, self.count = start, count
|
|
297
|
+
|
|
298
|
+
def forward(self, x):
|
|
299
|
+
return x[:, self.start:self.start + self.count]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class Reshape(nn.Module):
|
|
303
|
+
"""값 전체를 (c, 나머지) 줄로 다시 묶음."""
|
|
304
|
+
|
|
305
|
+
def __init__(self, c):
|
|
306
|
+
super().__init__()
|
|
307
|
+
self.c = c
|
|
308
|
+
|
|
309
|
+
def forward(self, x):
|
|
310
|
+
return x.reshape(x.shape[0], self.c, -1)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class Transpose(nn.Module):
|
|
314
|
+
"""줄은 채널↔길이, 그림은 높이↔너비를 바꿈."""
|
|
315
|
+
|
|
316
|
+
def forward(self, x):
|
|
317
|
+
return x.transpose(1, 2) if x.dim() == 3 else x.transpose(2, 3)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class ToSequence(nn.Module):
|
|
321
|
+
"""그림 (C, H, W) → 칸들의 줄 (C, H·W)."""
|
|
322
|
+
|
|
323
|
+
def forward(self, x):
|
|
324
|
+
return x.flatten(2)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class Crop(nn.Module):
|
|
328
|
+
"""양쪽 가장자리를 a칸씩 잘라냄."""
|
|
329
|
+
|
|
330
|
+
def __init__(self, a):
|
|
331
|
+
super().__init__()
|
|
332
|
+
self.a = a
|
|
333
|
+
|
|
334
|
+
def forward(self, x):
|
|
335
|
+
a = self.a
|
|
336
|
+
return x[:, :, a:-a] if x.dim() == 3 else x[:, :, a:-a, a:-a]
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class Pad(nn.Module):
|
|
340
|
+
"""양쪽 가장자리에 0을 a칸씩 채움."""
|
|
341
|
+
|
|
342
|
+
def __init__(self, a):
|
|
343
|
+
super().__init__()
|
|
344
|
+
self.a = a
|
|
345
|
+
|
|
346
|
+
def forward(self, x):
|
|
347
|
+
return F.pad(x, (self.a, self.a) * (x.dim() - 2))
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
class Embedding(nn.Module):
|
|
351
|
+
"""값(정규화된 −3…3)을 bins개 구간 번호로 바꾸고, 번호마다 배우는 dim개 값으로 (Chronos식 시계열 토큰)."""
|
|
352
|
+
|
|
353
|
+
def __init__(self, bins, dim):
|
|
354
|
+
super().__init__()
|
|
355
|
+
self.bins = bins
|
|
356
|
+
self.weight = nn.Parameter(torch.randn(bins, dim))
|
|
357
|
+
|
|
358
|
+
def forward(self, x):
|
|
359
|
+
idx = torch.clamp(torch.floor((x[:, 0] + 3.0) / 6.0 * self.bins), 0, self.bins - 1).long()
|
|
360
|
+
return self.weight[idx].movedim(-1, 1)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
class Spectrogram(nn.Module):
|
|
364
|
+
"""신호 (1, L) → 시간·주파수 그림 (1, 주파수, 시간): Hann 창 n_fft칸을 hop칸씩 옮기며 FFT 크기²의 log(1+·).
|
|
365
|
+
mel이면 mel 필터로 주파수를 묶고, mfcc면 그 위에 DCT. 배우는 값 없음."""
|
|
366
|
+
|
|
367
|
+
def __init__(self, n_fft=32, hop=8, mode="log", n_mels=16, n_mfcc=13):
|
|
368
|
+
super().__init__()
|
|
369
|
+
self.hop, self.mode = hop, mode
|
|
370
|
+
nf = n_fft // 2 + 1
|
|
371
|
+
n = torch.arange(n_fft, dtype=torch.float64)
|
|
372
|
+
win = 0.5 - 0.5 * torch.cos(2 * math.pi * n / n_fft)
|
|
373
|
+
f = torch.arange(nf, dtype=torch.float64)[:, None]
|
|
374
|
+
self.register_buffer("cos_k", (win * torch.cos(2 * math.pi * f * n / n_fft)).float().unsqueeze(1), persistent=False)
|
|
375
|
+
self.register_buffer("sin_k", (win * torch.sin(2 * math.pi * f * n / n_fft)).float().unsqueeze(1), persistent=False)
|
|
376
|
+
sr = 16000.0
|
|
377
|
+
mel = lambda v: 2595.0 * math.log10(1.0 + v / 700.0)
|
|
378
|
+
hz = lambda m: 700.0 * (10 ** (m / 2595.0) - 1.0)
|
|
379
|
+
pts = [hz(mel(sr / 2) * i / (n_mels + 1)) for i in range(n_mels + 2)]
|
|
380
|
+
freqs = [sr / 2 * j / (nf - 1) for j in range(nf)]
|
|
381
|
+
fb = [[max(0.0, min((fr - pts[m]) / (pts[m + 1] - pts[m]) if pts[m + 1] > pts[m] else 0.0,
|
|
382
|
+
(pts[m + 2] - fr) / (pts[m + 2] - pts[m + 1]) if pts[m + 2] > pts[m + 1] else 0.0))
|
|
383
|
+
for fr in freqs] for m in range(n_mels)]
|
|
384
|
+
self.register_buffer("mel", torch.tensor(fb, dtype=torch.float32), persistent=False)
|
|
385
|
+
dct = [[math.sqrt((1.0 if k == 0 else 2.0) / n_mels) * math.cos(math.pi / n_mels * (m + 0.5) * k) for m in range(n_mels)]
|
|
386
|
+
for k in range(n_mfcc)]
|
|
387
|
+
self.register_buffer("dct", torch.tensor(dct, dtype=torch.float32), persistent=False)
|
|
388
|
+
|
|
389
|
+
def forward(self, x):
|
|
390
|
+
re, im = F.conv1d(x, self.cos_k, stride=self.hop), F.conv1d(x, self.sin_k, stride=self.hop)
|
|
391
|
+
p = re * re + im * im # (N, 주파수, 시간)
|
|
392
|
+
if self.mode == "log":
|
|
393
|
+
return torch.log1p(p).unsqueeze(1)
|
|
394
|
+
m = torch.log1p(torch.einsum("mf,nft->nmt", self.mel, p))
|
|
395
|
+
return (m if self.mode == "mel" else torch.einsum("km,nmt->nkt", self.dct, m)).unsqueeze(1)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
# ---------------------------------------------------------------- 증강 (학습 때만, 예측 때는 그대로 통과)
|
|
399
|
+
|
|
400
|
+
def _affine(x, theta):
|
|
401
|
+
"""그림 (N, C, H, W)에 샘플마다 2×3 변환 (출력 좌표 → 입력 좌표, −1…1)."""
|
|
402
|
+
grid = F.affine_grid(theta, list(x.shape), align_corners=False)
|
|
403
|
+
return F.grid_sample(x, grid, mode="bilinear", padding_mode="zeros", align_corners=False)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
class RandomFlip(nn.Module):
|
|
407
|
+
"""학습 때 반씩 뒤집음: 그림은 좌우(h)·상하(v)·둘 다(hv), 줄은 시간을 거꾸로."""
|
|
408
|
+
|
|
409
|
+
def __init__(self, dir="h"):
|
|
410
|
+
super().__init__()
|
|
411
|
+
self.dir = dir
|
|
412
|
+
|
|
413
|
+
def forward(self, x):
|
|
414
|
+
if not self.training:
|
|
415
|
+
return x
|
|
416
|
+
flip = lambda y, dim: torch.where((torch.rand(y.shape[0], *([1] * (y.dim() - 1)), device=y.device) < 0.5), y.flip(dim), y)
|
|
417
|
+
if x.dim() == 3:
|
|
418
|
+
return flip(x, 2)
|
|
419
|
+
if "h" in self.dir:
|
|
420
|
+
x = flip(x, 3)
|
|
421
|
+
if "v" in self.dir:
|
|
422
|
+
x = flip(x, 2)
|
|
423
|
+
return x
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
class RandomRotation(nn.Module):
|
|
427
|
+
"""학습 때 그림을 ±degrees도 안에서 무작위로 돌림."""
|
|
428
|
+
|
|
429
|
+
def __init__(self, degrees=15):
|
|
430
|
+
super().__init__()
|
|
431
|
+
self.degrees = degrees
|
|
432
|
+
|
|
433
|
+
def forward(self, x):
|
|
434
|
+
if not self.training:
|
|
435
|
+
return x
|
|
436
|
+
a = (torch.rand(x.shape[0], device=x.device) * 2 - 1) * math.radians(self.degrees)
|
|
437
|
+
c, s, z = torch.cos(a), torch.sin(a), torch.zeros_like(a)
|
|
438
|
+
return _affine(x, torch.stack([torch.stack([c, -s, z], -1), torch.stack([s, c, z], -1)], 1))
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
class RandomShift(nn.Module):
|
|
442
|
+
"""학습 때 크기의 ±frac 안에서 무작위로 옮김 (빈 곳은 0)."""
|
|
443
|
+
|
|
444
|
+
def __init__(self, frac=0.1):
|
|
445
|
+
super().__init__()
|
|
446
|
+
self.frac = frac
|
|
447
|
+
|
|
448
|
+
def forward(self, x):
|
|
449
|
+
if not self.training:
|
|
450
|
+
return x
|
|
451
|
+
n = x.shape[0]
|
|
452
|
+
if x.dim() == 3:
|
|
453
|
+
length = x.shape[2]
|
|
454
|
+
m = int(round(length * self.frac))
|
|
455
|
+
out = torch.zeros_like(x)
|
|
456
|
+
for i, d in enumerate(torch.randint(-m, m + 1, (n,)).tolist()):
|
|
457
|
+
if d >= 0:
|
|
458
|
+
out[i, :, d:] = x[i, :, :length - d]
|
|
459
|
+
else:
|
|
460
|
+
out[i, :, :d] = x[i, :, -d:]
|
|
461
|
+
return out
|
|
462
|
+
t = (torch.rand(n, 2, device=x.device) * 2 - 1) * self.frac * 2
|
|
463
|
+
one, z = torch.ones(n, device=x.device), torch.zeros(n, device=x.device)
|
|
464
|
+
return _affine(x, torch.stack([torch.stack([one, z, t[:, 0]], -1), torch.stack([z, one, t[:, 1]], -1)], 1))
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
class RandomZoom(nn.Module):
|
|
468
|
+
"""학습 때 그림을 1±frac배로 무작위 확대·축소."""
|
|
469
|
+
|
|
470
|
+
def __init__(self, frac=0.1):
|
|
471
|
+
super().__init__()
|
|
472
|
+
self.frac = frac
|
|
473
|
+
|
|
474
|
+
def forward(self, x):
|
|
475
|
+
if not self.training:
|
|
476
|
+
return x
|
|
477
|
+
n = x.shape[0]
|
|
478
|
+
s = 1 + (torch.rand(n, device=x.device) * 2 - 1) * self.frac
|
|
479
|
+
z = torch.zeros(n, device=x.device)
|
|
480
|
+
return _affine(x, torch.stack([torch.stack([1 / s, z, z], -1), torch.stack([z, 1 / s, z], -1)], 1))
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
class RandomScale(nn.Module):
|
|
484
|
+
"""학습 때 샘플마다 값 전체에 1±frac배를 곱함 (신호 세기 바꾸기)."""
|
|
485
|
+
|
|
486
|
+
def __init__(self, frac=0.2):
|
|
487
|
+
super().__init__()
|
|
488
|
+
self.frac = frac
|
|
489
|
+
|
|
490
|
+
def forward(self, x):
|
|
491
|
+
if not self.training:
|
|
492
|
+
return x
|
|
493
|
+
s = 1 + (torch.rand(x.shape[0], *([1] * (x.dim() - 1)), device=x.device) * 2 - 1) * self.frac
|
|
494
|
+
return x * s
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
class RandomStretch(nn.Module):
|
|
498
|
+
"""학습 때 신호를 시간 방향으로 1±frac배 늘이거나 줄인 뒤 가운데를 원래 길이로 (빈 곳은 0)."""
|
|
499
|
+
|
|
500
|
+
def __init__(self, frac=0.1):
|
|
501
|
+
super().__init__()
|
|
502
|
+
self.frac = frac
|
|
503
|
+
|
|
504
|
+
def forward(self, x):
|
|
505
|
+
if not self.training:
|
|
506
|
+
return x
|
|
507
|
+
n, c, length = x.shape
|
|
508
|
+
out = torch.zeros_like(x)
|
|
509
|
+
for i in range(n):
|
|
510
|
+
new = max(2, int(round(length * (1 + (float(torch.rand(1)) * 2 - 1) * self.frac))))
|
|
511
|
+
y = F.interpolate(x[i:i + 1], size=new, mode="linear", align_corners=False)[0]
|
|
512
|
+
if new >= length:
|
|
513
|
+
a = (new - length) // 2
|
|
514
|
+
out[i] = y[:, a:a + length]
|
|
515
|
+
else:
|
|
516
|
+
a = (length - new) // 2
|
|
517
|
+
out[i, :, a:a + new] = y
|
|
518
|
+
return out
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
class RNNBlock(nn.Module):
|
|
522
|
+
"""순환 층 (LSTM·GRU·SimpleRNN): (N, C, L)을 시점마다 C개 값으로 읽음. return_sequences면 (H, L) 줄을 그대로,
|
|
523
|
+
아니면 마지막 숨은 값 (양방향이면 앞→뒤의 끝과 뒤→앞의 끝을 이어 붙임)."""
|
|
524
|
+
|
|
525
|
+
def __init__(self, kind, c, hidden, layers=1, bidirectional=False, return_sequences=False):
|
|
526
|
+
super().__init__()
|
|
527
|
+
cls = {"lstm": nn.LSTM, "gru": nn.GRU, "simple_rnn": nn.RNN}[kind]
|
|
528
|
+
self.rnn = cls(c, hidden, layers, batch_first=True, bidirectional=bidirectional)
|
|
529
|
+
self.hidden, self.bi, self.seq = hidden, bidirectional, return_sequences
|
|
530
|
+
|
|
531
|
+
def forward(self, x):
|
|
532
|
+
out, _ = self.rnn(x.transpose(1, 2))
|
|
533
|
+
if self.seq:
|
|
534
|
+
return out.transpose(1, 2)
|
|
535
|
+
if self.bi:
|
|
536
|
+
return torch.cat([out[:, -1, :self.hidden], out[:, 0, self.hidden:]], dim=1)
|
|
537
|
+
return out[:, -1]
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
class CausalConv1d(nn.Conv1d):
|
|
541
|
+
"""앞(과거)만 보는 Conv1D: 왼쪽에만 dilation×(kernel−1)칸 0을 채움 (WaveNet·TCN)."""
|
|
542
|
+
|
|
543
|
+
def forward(self, x):
|
|
544
|
+
pad = self.dilation[0] * (self.kernel_size[0] - 1)
|
|
545
|
+
return F.conv1d(F.pad(x, (pad, 0)), self.weight, self.bias, self.stride, 0, self.dilation, self.groups)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
class MobileNetV3Small(nn.Module):
|
|
549
|
+
"""Google이 ImageNet으로 미리 학습한 MobileNetV3-Small 특징 추출기 (TF Hub mobilenet_v3_small_100_224/feature_vector,
|
|
550
|
+
Apache 2.0, BatchNorm은 합성곱에 접혀 있음). 학습하지 않음(고정).
|
|
551
|
+
그림 (N, 1 또는 3, H, W) → 그림마다 0~1로 → size×size (bilinear) → −1~1 → 특징 1024개.
|
|
552
|
+
out="map": 그림을 2배(2H×2W)로 넣어 앞 블록 8개까지 → 특징 지도 (48, H/8, W/8) (탐지: 원래 그림 8픽셀마다 한 칸).
|
|
553
|
+
train_last > 0: 끝 블록 train_last개(특징 1024개면 마지막 1×1 합성곱 둘도)를 함께 학습 (미세조정).
|
|
554
|
+
가장자리는 TensorFlow 'SAME'처럼 채움 (stride 2면 아래·오른쪽을 더).
|
|
555
|
+
CFG: (들어옴, kernel, 넓힘, 나감, SE 채널 (0이면 없음), HardSwish인지, stride)."""
|
|
556
|
+
|
|
557
|
+
CFG = ((16, 3, 16, 16, 8, 0, 2), (16, 3, 72, 24, 0, 0, 2), (24, 3, 88, 24, 0, 0, 1), (24, 5, 96, 40, 24, 1, 2),
|
|
558
|
+
(40, 5, 240, 40, 64, 1, 1), (40, 5, 240, 40, 64, 1, 1), (40, 5, 120, 48, 32, 1, 1), (48, 5, 144, 48, 40, 1, 1),
|
|
559
|
+
(48, 5, 288, 96, 72, 1, 2), (96, 5, 576, 96, 144, 1, 1), (96, 5, 576, 96, 144, 1, 1))
|
|
560
|
+
SE_SCALE = 0.16667 # 원래 모델의 hard sigmoid: relu6(x + 3) × 0.16667
|
|
561
|
+
|
|
562
|
+
def __init__(self, size=128, train_last=0, out="vector"):
|
|
563
|
+
super().__init__()
|
|
564
|
+
self.size, self.map = size, out == "map"
|
|
565
|
+
nb = 8 if self.map else len(self.CFG)
|
|
566
|
+
self.stem = nn.Conv2d(3, 16, 3, 2)
|
|
567
|
+
self.blocks = nn.ModuleList()
|
|
568
|
+
for i, k, e, o, q, hs, s in self.CFG[:nb]:
|
|
569
|
+
b = nn.Module()
|
|
570
|
+
if e != i:
|
|
571
|
+
b.expand = nn.Conv2d(i, e, 1)
|
|
572
|
+
b.dw = nn.Conv2d(e, e, k, s, groups=e)
|
|
573
|
+
if q:
|
|
574
|
+
b.se1, b.se2 = nn.Conv2d(e, q, 1), nn.Conv2d(q, e, 1)
|
|
575
|
+
b.project = nn.Conv2d(e, o, 1)
|
|
576
|
+
self.blocks.append(b)
|
|
577
|
+
if not self.map:
|
|
578
|
+
self.last = nn.Conv2d(96, 576, 1)
|
|
579
|
+
self.head = nn.Conv2d(576, 1024, 1)
|
|
580
|
+
self.requires_grad_(False)
|
|
581
|
+
if train_last: # 미세조정: 끝 블록 train_last개 (특징 1024개면 마지막 1×1 합성곱 둘도)
|
|
582
|
+
for m in list(self.blocks)[nb - train_last:] + ([] if self.map else [self.last, self.head]):
|
|
583
|
+
m.requires_grad_(True)
|
|
584
|
+
|
|
585
|
+
@staticmethod
|
|
586
|
+
def same(x, k, s):
|
|
587
|
+
"""TensorFlow 'SAME' 채움: 모자란 칸을 위·왼쪽에 반, 아래·오른쪽에 나머지."""
|
|
588
|
+
if k == 1:
|
|
589
|
+
return x
|
|
590
|
+
H, W = x.shape[2], x.shape[3]
|
|
591
|
+
ph, pw = max((-(-H // s) - 1) * s + k - H, 0), max((-(-W // s) - 1) * s + k - W, 0)
|
|
592
|
+
return F.pad(x, (pw // 2, pw - pw // 2, ph // 2, ph - ph // 2))
|
|
593
|
+
|
|
594
|
+
def prep(self, x):
|
|
595
|
+
n = x.shape[0]
|
|
596
|
+
flat = x.reshape(n, -1)
|
|
597
|
+
lo, hi = flat.min(1)[0].view(n, 1, 1, 1), flat.max(1)[0].view(n, 1, 1, 1)
|
|
598
|
+
x = (x - lo) / (hi - lo).clamp_min(1e-6)
|
|
599
|
+
if x.shape[1] == 1:
|
|
600
|
+
x = x.repeat(1, 3, 1, 1)
|
|
601
|
+
hw = (2 * x.shape[2], 2 * x.shape[3]) if self.map else (self.size, self.size)
|
|
602
|
+
if tuple(x.shape[2:]) != hw:
|
|
603
|
+
x = F.interpolate(x, size=hw, mode="bilinear", align_corners=False)
|
|
604
|
+
return x * 2 - 1
|
|
605
|
+
|
|
606
|
+
def features(self, x):
|
|
607
|
+
x = F.hardswish(self.stem(self.same(x, 3, 2)))
|
|
608
|
+
for (i, k, e, o, q, hs, s), b in zip(self.CFG, self.blocks):
|
|
609
|
+
act = F.hardswish if hs else F.relu
|
|
610
|
+
y = act(b.expand(x)) if e != i else x
|
|
611
|
+
y = act(b.dw(self.same(y, k, s)))
|
|
612
|
+
if q:
|
|
613
|
+
y = y * (F.relu6(b.se2(F.relu(b.se1(y.mean((2, 3), keepdim=True)))) + 3) * self.SE_SCALE)
|
|
614
|
+
y = b.project(y)
|
|
615
|
+
x = x + y if s == 1 and i == o else y
|
|
616
|
+
if self.map:
|
|
617
|
+
return x
|
|
618
|
+
x = F.hardswish(self.last(x)).mean((2, 3), keepdim=True)
|
|
619
|
+
return F.hardswish(self.head(x)).flatten(1)
|
|
620
|
+
|
|
621
|
+
def forward(self, x):
|
|
622
|
+
return self.features(self.prep(x))
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
class NormalDistance(nn.Module):
|
|
626
|
+
"""이상 탐지 출력 '정상과의 거리': 정상 샘플의 특징 분포(평균·주성분 k개)에서 떨어진 정도를 점수 하나로 냄
|
|
627
|
+
(Mahalanobis 거리를 주성분 k개로 줄인 것). 값은 학습 때 정상 샘플에서 한 번 계산해 넣음 (경사 학습 없음)."""
|
|
628
|
+
|
|
629
|
+
def __init__(self, c, k=128):
|
|
630
|
+
super().__init__()
|
|
631
|
+
self.register_buffer("mean", torch.zeros(c))
|
|
632
|
+
self.register_buffer("basis", torch.zeros(k, c))
|
|
633
|
+
self.register_buffer("inv_var", torch.zeros(k))
|
|
634
|
+
self.register_buffer("inv_rest", torch.zeros(1))
|
|
635
|
+
|
|
636
|
+
def forward(self, f):
|
|
637
|
+
d = f - self.mean
|
|
638
|
+
p = d @ self.basis.T
|
|
639
|
+
s = (p * p * self.inv_var).sum(1) + ((d * d).sum(1) - (p * p).sum(1)) * self.inv_rest
|
|
640
|
+
return (s / d.shape[1]).unsqueeze(1)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
RANDOM_MODULES = (DropPath, GaussianNoise, RandomFlip, RandomRotation, RandomShift, RandomZoom, RandomScale, RandomStretch)
|