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
blocklearning/layers.py
ADDED
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
"""추가 블록 정의 (torch 없이): 설정 규칙 · 모양 계산 · 가중치 목록 · PyTorch 모듈 이름과 인자.
|
|
2
|
+
|
|
3
|
+
blocks._Walker(모양 검사), codegen.param_specs(가중치 이름·모양, 웹 엔진이 씀), blocks.make_layer(PyTorch 모듈),
|
|
4
|
+
codegen(코드 내보내기)이 모두 여기서 읽는다. PyTorch 모듈 자체는 nn_extra.py (생성 코드에도 그 소스를 그대로 넣음).
|
|
5
|
+
|
|
6
|
+
모양 (배치 제외, 채널 먼저): 숫자 묶음 (n,) · 줄 (C, L) · 그림 (C, H, W).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
|
|
12
|
+
# ---------------------------------------------------------------- 종류
|
|
13
|
+
|
|
14
|
+
EXTRA_TYPES = (
|
|
15
|
+
# 완전연결
|
|
16
|
+
"glu",
|
|
17
|
+
# 합성곱
|
|
18
|
+
"dw_conv", "dw_conv2d", "sep_conv", "sep_conv2d",
|
|
19
|
+
# 줄이기·모으기
|
|
20
|
+
"max_pool", "max_pool2d", "global_max", "global_max2d", "adaptive_pool", "first_step", "attn_pool",
|
|
21
|
+
# 키우기
|
|
22
|
+
"upsample", "pixel_shuffle", "conv_t", "conv_t2d",
|
|
23
|
+
# 어텐션
|
|
24
|
+
"eca", "cbam", "spatial_attn", "mha", "linear_attn", "nonlocal", "cross_attn",
|
|
25
|
+
# Transformer 부품
|
|
26
|
+
"pos_enc", "patch_embed", "cls_token",
|
|
27
|
+
# 정규화
|
|
28
|
+
"layernorm", "rmsnorm", "groupnorm", "instancenorm",
|
|
29
|
+
# 활성화 (배우는 값이 있는 것)
|
|
30
|
+
"prelu",
|
|
31
|
+
# 과적합 막기
|
|
32
|
+
"spatial_dropout", "drop_path", "gaussian_noise",
|
|
33
|
+
# 나누기
|
|
34
|
+
"slice",
|
|
35
|
+
# 모양 바꾸기
|
|
36
|
+
"reshape", "permute", "to_seq", "crop", "pad",
|
|
37
|
+
# 입력 변환·증강
|
|
38
|
+
"embedding", "spectrogram", "rand_flip", "rand_rotate", "rand_shift", "rand_zoom", "rand_scale", "rand_stretch",
|
|
39
|
+
# 사전학습 (가중치 고정)
|
|
40
|
+
"mnv3s",
|
|
41
|
+
)
|
|
42
|
+
PRETRAINED_TYPES = ("mnv3s",) # 가중치를 pretrained/<종류>.bin에서 읽고 학습하지 않음
|
|
43
|
+
# Google MobileNetV3-Small 특징 추출기 (nn_extra.MobileNetV3Small.CFG와 같음): (들어옴, kernel, 넓힘, 나감, SE 채널, HardSwish인지, stride)
|
|
44
|
+
MNV3S_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),
|
|
45
|
+
(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),
|
|
46
|
+
(48, 5, 288, 96, 72, 1, 2), (96, 5, 576, 96, 144, 1, 1), (96, 5, 576, 96, 144, 1, 1))
|
|
47
|
+
MNV3S_OUT = 1024
|
|
48
|
+
MNV3S_MAP_BLOCKS, MNV3S_MAP_C = 8, 48 # 특징 지도: 앞 블록 8개까지 (그림을 2배로 넣어 원래 8픽셀마다 한 칸, 48채널)
|
|
49
|
+
DIST_K = 128 # 이상 탐지 출력 '정상과의 거리': 주성분 수 (특징이 적으면 그 수)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def dist_k(c: int) -> int:
|
|
53
|
+
return min(DIST_K, int(c))
|
|
54
|
+
NEW_MERGES = ("multiply", "average", "maximum") # 모양이 같은 값들을 원소마다 곱·평균·최댓값
|
|
55
|
+
TWO_INPUT = ("cross_attn",) # 입력이 정확히 둘 (질문, 참고)
|
|
56
|
+
RANDOM_TYPES = ("spatial_dropout", "drop_path", "gaussian_noise", "rand_flip", "rand_rotate", "rand_shift", "rand_zoom",
|
|
57
|
+
"rand_scale", "rand_stretch") # 학습 때만 무작위 (예측 때는 그대로 통과)
|
|
58
|
+
AUG_TYPES = ("rand_flip", "rand_rotate", "rand_shift", "rand_zoom", "rand_scale", "rand_stretch") # Input 바로 뒤(증강끼리)만
|
|
59
|
+
|
|
60
|
+
EXTRA_NAMES = {
|
|
61
|
+
"glu": "GLU", "dw_conv": "DepthwiseConv1D", "dw_conv2d": "DepthwiseConv2D", "sep_conv": "SeparableConv1D",
|
|
62
|
+
"sep_conv2d": "SeparableConv2D", "max_pool": "MaxPool1D", "max_pool2d": "MaxPool2D", "global_max": "GlobalMaxPool1D",
|
|
63
|
+
"global_max2d": "GlobalMaxPool2D", "adaptive_pool": "AdaptivePool", "first_step": "FirstTimestep",
|
|
64
|
+
"attn_pool": "AttentionPool", "upsample": "Upsample", "pixel_shuffle": "PixelShuffle", "conv_t": "ConvTranspose1D",
|
|
65
|
+
"conv_t2d": "ConvTranspose2D", "eca": "ECA", "cbam": "CBAM", "spatial_attn": "SpatialAttention",
|
|
66
|
+
"mha": "MultiHeadAttention", "linear_attn": "LinearAttention", "nonlocal": "NonLocal", "cross_attn": "CrossAttention",
|
|
67
|
+
"pos_enc": "PositionalEncoding", "patch_embed": "PatchEmbedding", "cls_token": "CLS token", "layernorm": "LayerNorm",
|
|
68
|
+
"rmsnorm": "RMSNorm", "groupnorm": "GroupNorm", "instancenorm": "InstanceNorm", "prelu": "PReLU",
|
|
69
|
+
"spatial_dropout": "SpatialDropout", "drop_path": "DropPath", "gaussian_noise": "GaussianNoise", "slice": "Split",
|
|
70
|
+
"reshape": "Reshape", "permute": "Transpose", "to_seq": "ToSequence", "crop": "Crop", "pad": "Pad",
|
|
71
|
+
"embedding": "Embedding", "spectrogram": "Spectrogram", "rand_flip": "RandomFlip", "rand_rotate": "RandomRotation",
|
|
72
|
+
"rand_shift": "RandomShift", "rand_zoom": "RandomZoom", "rand_scale": "RandomScale", "rand_stretch": "RandomStretch",
|
|
73
|
+
"multiply": "Multiply", "average": "Average", "maximum": "Maximum", "mnv3s": "MobileNetV3-Small (사전학습)",
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
# 정수 설정: (키, 최소, 최대, 기본값, 허용 값, 설명) — blocks.PARAMS와 같은 꼴
|
|
77
|
+
EXTRA_PARAMS = {
|
|
78
|
+
"glu": [("units", 1, 1024, None, None, "units는 1–1024")],
|
|
79
|
+
"dw_conv": [("kernel", 1, 31, 3, tuple(range(1, 32, 2)), "kernel size는 1–31의 홀수"),
|
|
80
|
+
("multiplier", 1, 8, 1, None, "multiplier는 1–8")],
|
|
81
|
+
"dw_conv2d": [("kernel", 1, 7, 3, (1, 3, 5, 7), "kernel size는 1·3·5·7"), ("multiplier", 1, 8, 1, None, "multiplier는 1–8")],
|
|
82
|
+
"sep_conv": [("channels", 1, 256, None, None, "filters는 1–256"), ("kernel", 1, 31, 3, tuple(range(1, 32, 2)), "kernel size는 1–31의 홀수")],
|
|
83
|
+
"sep_conv2d": [("channels", 1, 256, None, None, "filters는 1–256"), ("kernel", 1, 7, 3, (1, 3, 5, 7), "kernel size는 1·3·5·7")],
|
|
84
|
+
"max_pool": [("size", 2, 4, 2, (2, 4), "pool size는 2 또는 4")],
|
|
85
|
+
"max_pool2d": [("size", 2, 2, 2, (2,), "pool size는 2")],
|
|
86
|
+
"adaptive_pool": [("size", 1, 64, 4, None, "출력 크기는 1–64")],
|
|
87
|
+
"upsample": [("scale", 2, 2, 2, (2,), "배율은 2")],
|
|
88
|
+
"pixel_shuffle": [("scale", 2, 2, 2, (2,), "배율은 2")],
|
|
89
|
+
"conv_t": [("channels", 1, 256, None, None, "filters는 1–256"), ("kernel", 1, 5, 2, (1, 2, 3, 4, 5), "kernel size는 1–5"),
|
|
90
|
+
("stride", 1, 2, 2, (1, 2), "stride는 1 또는 2")],
|
|
91
|
+
"conv_t2d": [("channels", 1, 256, None, None, "filters는 1–256"), ("kernel", 1, 5, 2, (1, 2, 3, 4, 5), "kernel size는 1–5"),
|
|
92
|
+
("stride", 1, 2, 2, (1, 2), "stride는 1 또는 2")],
|
|
93
|
+
"eca": [("kernel", 3, 7, 3, (3, 5, 7), "kernel size는 3·5·7")],
|
|
94
|
+
"cbam": [("ratio", 1, 64, 4, None, "ratio는 1–64"), ("kernel", 3, 7, 7, (3, 5, 7), "kernel size는 3·5·7")],
|
|
95
|
+
"spatial_attn": [("kernel", 3, 7, 7, (3, 5, 7), "kernel size는 3·5·7")],
|
|
96
|
+
"mha": [("heads", 1, 8, 2, (1, 2, 4, 8), "heads는 1·2·4·8")],
|
|
97
|
+
"linear_attn": [("heads", 1, 8, 2, (1, 2, 4, 8), "heads는 1·2·4·8")],
|
|
98
|
+
"cross_attn": [("heads", 1, 8, 2, (1, 2, 4, 8), "heads는 1·2·4·8")],
|
|
99
|
+
"patch_embed": [("patch", 2, 8, 4, (2, 4, 8), "조각 크기는 2·4·8"), ("dim", 1, 256, 32, None, "dim은 1–256")],
|
|
100
|
+
"groupnorm": [("groups", 1, 32, 4, (1, 2, 4, 8, 16, 32), "groups는 1·2·4·8·16·32")],
|
|
101
|
+
"slice": [("start", 0, 1024, 0, None, "시작 채널은 0 이상"), ("count", 1, 1024, None, None, "채널 수는 1 이상")],
|
|
102
|
+
"reshape": [("channels", 1, 65536, None, None, "채널 수는 1 이상")],
|
|
103
|
+
"crop": [("amount", 1, 64, 1, None, "자르는 칸은 1–64")],
|
|
104
|
+
"pad": [("amount", 1, 64, 1, None, "채우는 칸은 1–64")],
|
|
105
|
+
"rand_rotate": [("degrees", 1, 180, 15, None, "각도는 1–180")],
|
|
106
|
+
"embedding": [("bins", 2, 256, 32, (8, 16, 32, 64, 128, 256), "구간 수는 8·16·32·64·128·256"),
|
|
107
|
+
("dim", 1, 256, 16, None, "dim은 1–256")],
|
|
108
|
+
"spectrogram": [("n_fft", 8, 256, 32, (8, 16, 32, 64, 128, 256), "창 길이(n_fft)는 8·16·32·64·128·256"),
|
|
109
|
+
("hop", 1, 128, 8, (1, 2, 4, 8, 16, 32, 64, 128), "hop은 1·2·4·…·128"),
|
|
110
|
+
("n_mels", 4, 64, 16, (8, 16, 32, 64), "mel 칸 수는 8·16·32·64"),
|
|
111
|
+
("n_mfcc", 4, 40, 13, (8, 13, 20, 40), "MFCC 개수는 8·13·20·40")],
|
|
112
|
+
"mnv3s": [("size", 64, 224, 128, (64, 96, 128, 160, 224), "크기는 64·96·128·160·224"),
|
|
113
|
+
("train_last", 0, 3, 0, (0, 1, 2, 3), "학습할 끝 블록 수는 0–3 (0이면 모두 고정)")],
|
|
114
|
+
}
|
|
115
|
+
# 실수 설정: (키, 최소(포함), 최대(미포함), 기본값, 설명)
|
|
116
|
+
FLOAT_PARAMS = {
|
|
117
|
+
"spatial_dropout": [("rate", 0.0, 1.0, 0.1, "rate는 0 이상 1 미만")],
|
|
118
|
+
"drop_path": [("rate", 0.0, 1.0, 0.1, "rate는 0 이상 1 미만")],
|
|
119
|
+
"gaussian_noise": [("std", 0.0, 5.0, 0.1, "std는 0 이상 5 미만")],
|
|
120
|
+
"rand_shift": [("frac", 0.0, 0.5, 0.1, "비율은 0 이상 0.5 미만")],
|
|
121
|
+
"rand_zoom": [("frac", 0.0, 0.5, 0.1, "비율은 0 이상 0.5 미만")],
|
|
122
|
+
"rand_scale": [("frac", 0.0, 0.9, 0.2, "비율은 0 이상 0.9 미만")],
|
|
123
|
+
"rand_stretch": [("frac", 0.0, 0.5, 0.1, "비율은 0 이상 0.5 미만")],
|
|
124
|
+
}
|
|
125
|
+
# 글자·참거짓 설정: 키 → (허용 값, 기본값, 설명)
|
|
126
|
+
STR_PARAMS = {
|
|
127
|
+
"glu": {"gate": (("sigmoid", "silu"), "sigmoid", "gate는 sigmoid(GLU) 또는 silu(SwiGLU)")},
|
|
128
|
+
"adaptive_pool": {"mode": (("avg", "max"), "avg", "mode는 avg 또는 max")},
|
|
129
|
+
"upsample": {"mode": (("nearest", "linear"), "nearest", "mode는 nearest 또는 linear")},
|
|
130
|
+
"mha": {"causal": ((False, True), False, "causal은 참·거짓"), "pos": (("none", "rope"), "none", "pos는 none 또는 rope")},
|
|
131
|
+
"pos_enc": {"mode": (("sin", "learned"), "sin", "mode는 sin 또는 learned")},
|
|
132
|
+
"rand_flip": {"dir": (("h", "v", "hv"), "h", "방향은 h·v·hv")},
|
|
133
|
+
"mnv3s": {"out": (("vector", "map"), "vector", "출력은 vector(특징 1024개) 또는 map(특징 지도)")},
|
|
134
|
+
"spectrogram": {"mode": (("log", "mel", "mfcc"), "log", "mode는 log·mel·mfcc")},
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
TRANSPOSE_SPECS = {"conv_t": 1, "conv_t2d": 2}
|
|
138
|
+
# ConvTranspose (stride 2): kernel → (padding, output_padding) — 출력이 정확히 2배가 되게
|
|
139
|
+
T_PAD = {1: (0, 1), 2: (0, 0), 3: (1, 1), 4: (1, 0), 5: (2, 1)}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def name_of(t: str) -> str:
|
|
143
|
+
return EXTRA_NAMES.get(t, t)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def values_ok(w, b: dict, path) -> bool:
|
|
147
|
+
"""정수 밖의 설정(실수·글자·참거짓) 검사. 정수는 blocks.PARAMS(EXTRA_PARAMS가 합쳐짐)가 함."""
|
|
148
|
+
ok = True
|
|
149
|
+
t = b["type"]
|
|
150
|
+
for key, lo, hi, default, desc in FLOAT_PARAMS.get(t, []):
|
|
151
|
+
v = b.get(key, default)
|
|
152
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or not lo <= v < hi:
|
|
153
|
+
w.issue(path, f"{name_of(t)}: {key} 값 {v!r}이(가) 맞지 않음", desc)
|
|
154
|
+
ok = False
|
|
155
|
+
for key, (choices, default, desc) in STR_PARAMS.get(t, {}).items():
|
|
156
|
+
v = b.get(key, default)
|
|
157
|
+
if v not in choices or (isinstance(v, bool) != isinstance(default, bool)):
|
|
158
|
+
w.issue(path, f"{name_of(t)}: {key} 값 {v!r}이(가) 맞지 않음", desc)
|
|
159
|
+
ok = False
|
|
160
|
+
return ok
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def opt(b: dict, key: str):
|
|
164
|
+
"""설정 값 (없으면 기본값)."""
|
|
165
|
+
t = b["type"]
|
|
166
|
+
for k, lo, hi, d, ch, desc in EXTRA_PARAMS.get(t, []):
|
|
167
|
+
if k == key:
|
|
168
|
+
return b.get(key, d)
|
|
169
|
+
for k, lo, hi, d, desc in FLOAT_PARAMS.get(t, []):
|
|
170
|
+
if k == key:
|
|
171
|
+
return b.get(key, d)
|
|
172
|
+
if key in STR_PARAMS.get(t, {}):
|
|
173
|
+
return b.get(key, STR_PARAMS[t][key][1])
|
|
174
|
+
return b.get(key)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _prod(s) -> int:
|
|
178
|
+
n = 1
|
|
179
|
+
for v in s:
|
|
180
|
+
n *= v
|
|
181
|
+
return n
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ---------------------------------------------------------------- 모양
|
|
185
|
+
|
|
186
|
+
SEQ_HINT = "이미지는 ToSequence·PatchEmbedding 뒤에, 숫자 묶음(Dense·GlobalPool 뒤)에는 쓸 수 없음"
|
|
187
|
+
IMG_HINT = "이미지(채널, 높이, 너비)에만. 시계열은 Spectrogram 뒤에는 됨"
|
|
188
|
+
SPATIAL_HINT = "시간 축이나 (높이, 너비)가 있는 값에만. GlobalPool·Flatten·Dense 앞으로 옮기세요"
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _need(w, t, shape, ranks, path) -> bool:
|
|
192
|
+
want = {2: "(채널, 길이)", 3: "(채널, 높이, 너비)", 1: "숫자 묶음"}
|
|
193
|
+
if len(shape) in ranks:
|
|
194
|
+
return True
|
|
195
|
+
hint = SEQ_HINT if ranks == (2,) else IMG_HINT if ranks == (3,) else SPATIAL_HINT
|
|
196
|
+
w.issue(path, f"{name_of(t)}은(는) {' 또는 '.join(want[r] for r in ranks)} 모양에만 쓸 수 있음 (지금 {tuple(shape)})", hint)
|
|
197
|
+
return False
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _spatial(shape):
|
|
201
|
+
return _prod(shape[1:])
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def shape(w, b: dict, shape_in, path, ctx):
|
|
205
|
+
"""추가 블록 하나의 출력 모양 (문제가 있으면 w.issue 후 None). w: blocks._Walker."""
|
|
206
|
+
t = b["type"]
|
|
207
|
+
s = tuple(shape_in)
|
|
208
|
+
C = s[0]
|
|
209
|
+
rank = len(s)
|
|
210
|
+
o = lambda k: opt(b, k)
|
|
211
|
+
if t in ("layernorm", "rmsnorm", "prelu", "drop_path", "gaussian_noise", "rand_scale"):
|
|
212
|
+
return s
|
|
213
|
+
if t == "glu":
|
|
214
|
+
return (o("units"),) + s[1:]
|
|
215
|
+
if t == "slice":
|
|
216
|
+
if o("start") + o("count") > C:
|
|
217
|
+
w.issue(path, f"Split: 채널 {o('start')}부터 {o('count')}개는 들어온 채널 {C}개를 넘음", f"시작 + 개수를 {C} 이하로")
|
|
218
|
+
return None
|
|
219
|
+
return (o("count"),) + s[1:]
|
|
220
|
+
if t == "reshape":
|
|
221
|
+
n = _prod(s)
|
|
222
|
+
if n % o("channels"):
|
|
223
|
+
w.issue(path, f"Reshape: 값 {n}개를 채널 {o('channels')}개로 나눌 수 없음", f"{n}의 약수로 정하세요")
|
|
224
|
+
return None
|
|
225
|
+
return (o("channels"), n // o("channels"))
|
|
226
|
+
if t in ("rand_flip", "rand_shift"):
|
|
227
|
+
return s if _need(w, t, s, (2, 3), path) else None
|
|
228
|
+
if t in ("rand_rotate", "rand_zoom"):
|
|
229
|
+
return s if _need(w, t, s, (3,), path) else None
|
|
230
|
+
if t == "rand_stretch":
|
|
231
|
+
return s if _need(w, t, s, (2,), path) else None
|
|
232
|
+
if t == "embedding":
|
|
233
|
+
if not _need(w, t, s, (2, 3), path):
|
|
234
|
+
return None
|
|
235
|
+
if C != 1:
|
|
236
|
+
w.issue(path, f"Embedding은 채널이 1개인 값에만 (지금 {C}개)", "Input 바로 뒤에 두세요")
|
|
237
|
+
return None
|
|
238
|
+
return (o("dim"),) + s[1:]
|
|
239
|
+
if t == "mnv3s":
|
|
240
|
+
if not _need(w, t, s, (3,), path):
|
|
241
|
+
return None
|
|
242
|
+
if C not in (1, 3):
|
|
243
|
+
w.issue(path, f"MobileNetV3-Small은 흑백(채널 1)이나 컬러(채널 3) 그림에만 (지금 채널 {C}개)", "Input 바로 뒤에 두세요")
|
|
244
|
+
return None
|
|
245
|
+
if o("out") == "map": # 그림을 2배로 넣고 stride 2를 네 번 (TensorFlow 'SAME'처럼 올림)
|
|
246
|
+
h, w = s[1], s[2]
|
|
247
|
+
for _ in range(3):
|
|
248
|
+
h, w = -(-h // 2), -(-w // 2)
|
|
249
|
+
return (MNV3S_MAP_C, h, w)
|
|
250
|
+
return (MNV3S_OUT,)
|
|
251
|
+
if t == "spectrogram":
|
|
252
|
+
if not _need(w, t, s, (2,), path):
|
|
253
|
+
return None
|
|
254
|
+
if C != 1:
|
|
255
|
+
w.issue(path, f"Spectrogram은 채널이 1개인 신호에만 (지금 {C}개)", "Input 바로 뒤에 두세요")
|
|
256
|
+
return None
|
|
257
|
+
n_fft, hop = o("n_fft"), o("hop")
|
|
258
|
+
if s[1] < n_fft:
|
|
259
|
+
w.issue(path, f"Spectrogram: 길이 {s[1]}이(가) 창 길이 {n_fft}보다 짧음", "n_fft를 줄이세요")
|
|
260
|
+
return None
|
|
261
|
+
T = 1 + (s[1] - n_fft) // hop
|
|
262
|
+
F = n_fft // 2 + 1 if o("mode") == "log" else o("n_mels") if o("mode") == "mel" else o("n_mfcc")
|
|
263
|
+
if o("mode") == "mfcc" and o("n_mfcc") > o("n_mels"):
|
|
264
|
+
w.issue(path, "Spectrogram: MFCC 개수는 mel 칸 수 이하", "n_mfcc를 줄이거나 n_mels를 늘리세요")
|
|
265
|
+
return None
|
|
266
|
+
return w.grid(1, F, T, path)
|
|
267
|
+
# ---- 아래는 (채널, 길이) 또는 (채널, 높이, 너비)
|
|
268
|
+
if t in ("dw_conv", "sep_conv", "max_pool", "global_max", "first_step", "conv_t", "cls_token"):
|
|
269
|
+
if not _need(w, t, s, (2,), path):
|
|
270
|
+
return None
|
|
271
|
+
elif t in ("dw_conv2d", "sep_conv2d", "max_pool2d", "global_max2d", "conv_t2d", "patch_embed", "to_seq"):
|
|
272
|
+
if not _need(w, t, s, (3,), path):
|
|
273
|
+
return None
|
|
274
|
+
elif not _need(w, t, s, (2, 3), path):
|
|
275
|
+
return None
|
|
276
|
+
sp = s[1:]
|
|
277
|
+
if t == "dw_conv":
|
|
278
|
+
return (C * o("multiplier"), s[1])
|
|
279
|
+
if t == "dw_conv2d":
|
|
280
|
+
return (C * o("multiplier"),) + sp
|
|
281
|
+
if t == "sep_conv":
|
|
282
|
+
return (o("channels"), s[1])
|
|
283
|
+
if t == "sep_conv2d":
|
|
284
|
+
return (o("channels"),) + sp
|
|
285
|
+
if t == "max_pool":
|
|
286
|
+
return w.seq(C, s[1] // o("size"), path)
|
|
287
|
+
if t == "max_pool2d":
|
|
288
|
+
return w.grid(C, s[1] // 2, s[2] // 2, path)
|
|
289
|
+
if t in ("global_max", "global_max2d", "first_step", "attn_pool"):
|
|
290
|
+
return (C,)
|
|
291
|
+
if t == "adaptive_pool":
|
|
292
|
+
return (C,) + (o("size"),) * (rank - 1)
|
|
293
|
+
if t == "upsample":
|
|
294
|
+
return (C,) + tuple(v * 2 for v in sp)
|
|
295
|
+
if t == "pixel_shuffle":
|
|
296
|
+
r = 2 ** (rank - 1)
|
|
297
|
+
if C % r:
|
|
298
|
+
w.issue(path, f"PixelShuffle: 채널 {C}개가 {r}로 나누어떨어지지 않음", f"앞 층의 채널을 {r}의 배수로")
|
|
299
|
+
return None
|
|
300
|
+
return (C // r,) + tuple(v * 2 for v in sp)
|
|
301
|
+
if t in ("conv_t", "conv_t2d"):
|
|
302
|
+
k, st = o("kernel"), o("stride")
|
|
303
|
+
if st == 1 and k % 2 == 0:
|
|
304
|
+
w.issue(path, f"{name_of(t)}: stride 1이면 kernel은 홀수", "kernel을 1·3·5로 하거나 stride 2로")
|
|
305
|
+
return None
|
|
306
|
+
return (o("channels"),) + tuple(v * st for v in sp)
|
|
307
|
+
if t == "eca":
|
|
308
|
+
return s
|
|
309
|
+
if t in ("cbam", "spatial_attn"):
|
|
310
|
+
if t == "cbam" and C // o("ratio") < 1:
|
|
311
|
+
w.issue(path, f"CBAM: 채널 {C}개를 ratio {o('ratio')}로 나누면 0", "ratio를 채널 수보다 작게")
|
|
312
|
+
return None
|
|
313
|
+
return s
|
|
314
|
+
if t in ("mha", "linear_attn"):
|
|
315
|
+
h = o("heads")
|
|
316
|
+
if C % h:
|
|
317
|
+
w.issue(path, f"{name_of(t)}: 채널 {C}개를 heads {h}로 나눌 수 없음", "heads를 채널 수의 약수로")
|
|
318
|
+
return None
|
|
319
|
+
if t == "mha" and o("pos") == "rope" and (C // h) % 2:
|
|
320
|
+
w.issue(path, f"MultiHeadAttention: RoPE는 head마다 채널이 짝수여야 함 (지금 {C // h})", "채널이나 heads를 바꾸세요")
|
|
321
|
+
return None
|
|
322
|
+
if _spatial(s) > 4096:
|
|
323
|
+
w.issue(path, f"{name_of(t)}: 위치 {_spatial(s):,}개는 너무 많음 (4,096개까지)", "Pool·PatchEmbedding으로 줄인 뒤에 쓰세요")
|
|
324
|
+
return None
|
|
325
|
+
return s
|
|
326
|
+
if t == "nonlocal":
|
|
327
|
+
if _spatial(s) > 4096:
|
|
328
|
+
w.issue(path, f"NonLocal: 위치 {_spatial(s):,}개는 너무 많음 (4,096개까지)", "Pool로 줄인 뒤에 쓰세요")
|
|
329
|
+
return None
|
|
330
|
+
return s
|
|
331
|
+
if t == "pos_enc":
|
|
332
|
+
return s
|
|
333
|
+
if t == "patch_embed":
|
|
334
|
+
p = o("patch")
|
|
335
|
+
if s[1] < p or s[2] < p:
|
|
336
|
+
w.issue(path, f"PatchEmbedding: 그림 {s[1]}×{s[2]}이(가) 조각 {p}보다 작음", "조각 크기를 줄이세요")
|
|
337
|
+
return None
|
|
338
|
+
return (o("dim"), (s[1] // p) * (s[2] // p))
|
|
339
|
+
if t == "cls_token":
|
|
340
|
+
return (C, s[1] + 1)
|
|
341
|
+
if t == "groupnorm":
|
|
342
|
+
if C % o("groups"):
|
|
343
|
+
w.issue(path, f"GroupNorm: 채널 {C}개를 groups {o('groups')}로 나눌 수 없음", "groups를 채널 수의 약수로")
|
|
344
|
+
return None
|
|
345
|
+
return s
|
|
346
|
+
if t in ("instancenorm", "spatial_dropout"):
|
|
347
|
+
return s
|
|
348
|
+
if t == "permute":
|
|
349
|
+
return (s[1], s[0]) if rank == 2 else (C, s[2], s[1])
|
|
350
|
+
if t == "to_seq":
|
|
351
|
+
return (C, s[1] * s[2])
|
|
352
|
+
if t in ("crop", "pad"):
|
|
353
|
+
a = o("amount") * (-2 if t == "crop" else 2)
|
|
354
|
+
if any(v + a < 1 for v in sp):
|
|
355
|
+
w.issue(path, f"Crop: 크기 {sp}에서 양쪽 {o('amount')}칸씩 자르면 남는 것이 없음", "amount를 줄이세요")
|
|
356
|
+
return None
|
|
357
|
+
return (C,) + tuple(v + a for v in sp)
|
|
358
|
+
return s
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def two_shape(issue, b: dict, q, ctx):
|
|
362
|
+
"""입력이 둘인 블록 (CrossAttention): 질문 q, 참고 ctx의 모양 → 출력 모양 또는 None (issue(message, hint) 후)."""
|
|
363
|
+
if len(q) not in (2, 3) or len(ctx) not in (2, 3):
|
|
364
|
+
issue("CrossAttention: 두 입력 모두 (채널, 길이)나 (채널, 높이, 너비)여야 함", SPATIAL_HINT)
|
|
365
|
+
return None
|
|
366
|
+
h = opt(b, "heads")
|
|
367
|
+
if q[0] % h:
|
|
368
|
+
issue(f"CrossAttention: 첫 입력(질문)의 채널 {q[0]}개를 heads {h}로 나눌 수 없음", "heads를 채널 수의 약수로")
|
|
369
|
+
return None
|
|
370
|
+
return tuple(q)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
# ---------------------------------------------------------------- 가중치 (PyTorch state_dict 이름·모양 + 처음 값)
|
|
374
|
+
# 처음 값: uniform(기본: ±1/√fan_in, PyTorch Linear·Conv와 같음) · ones · zeros · normal1 · normal02 · const0.25
|
|
375
|
+
|
|
376
|
+
def params(t: str, b: dict, ins, out, k: str, ins2=None) -> list:
|
|
377
|
+
o = lambda key: opt(b, key)
|
|
378
|
+
W = lambda name, *shape: (f"{k}.{name}", list(shape), "weight", "uniform")
|
|
379
|
+
C = ins[0]
|
|
380
|
+
rank = len(ins)
|
|
381
|
+
if t == "glu":
|
|
382
|
+
return [W("proj.weight", 2 * o("units"), C), W("proj.bias", 2 * o("units"))]
|
|
383
|
+
if t in ("dw_conv", "dw_conv2d"):
|
|
384
|
+
kk = (o("kernel"),) * (2 if t == "dw_conv2d" else 1)
|
|
385
|
+
return [W("weight", C * o("multiplier"), 1, *kk), W("bias", C * o("multiplier"))]
|
|
386
|
+
if t in ("sep_conv", "sep_conv2d"):
|
|
387
|
+
two = t == "sep_conv2d"
|
|
388
|
+
kk, one = (o("kernel"),) * (2 if two else 1), (1,) * (2 if two else 1)
|
|
389
|
+
return [W("depthwise.weight", C, 1, *kk), W("depthwise.bias", C),
|
|
390
|
+
W("pointwise.weight", o("channels"), C, *one), W("pointwise.bias", o("channels"))]
|
|
391
|
+
if t in ("conv_t", "conv_t2d"):
|
|
392
|
+
kk = (o("kernel"),) * (2 if t == "conv_t2d" else 1)
|
|
393
|
+
return [W("weight", C, o("channels"), *kk), W("bias", o("channels"))]
|
|
394
|
+
if t == "attn_pool":
|
|
395
|
+
return [W("score.weight", 1, C), W("score.bias", 1)]
|
|
396
|
+
if t == "eca":
|
|
397
|
+
return [W("conv.weight", 1, 1, o("kernel"))]
|
|
398
|
+
if t == "cbam":
|
|
399
|
+
h = max(1, C // o("ratio"))
|
|
400
|
+
kk = (o("kernel"),) * (rank - 1)
|
|
401
|
+
return [W("fc1.weight", h, C), W("fc1.bias", h), W("fc2.weight", C, h), W("fc2.bias", C),
|
|
402
|
+
W("conv.weight", 1, 2, *kk), W("conv.bias", 1)]
|
|
403
|
+
if t == "spatial_attn":
|
|
404
|
+
kk = (o("kernel"),) * (rank - 1)
|
|
405
|
+
return [W("conv.weight", 1, 2, *kk), W("conv.bias", 1)]
|
|
406
|
+
if t in ("mha", "linear_attn"):
|
|
407
|
+
return [W("qkv.weight", 3 * C, C), W("qkv.bias", 3 * C), W("proj.weight", C, C), W("proj.bias", C)]
|
|
408
|
+
if t == "nonlocal":
|
|
409
|
+
h = max(1, C // 2)
|
|
410
|
+
return [W("theta.weight", h, C), W("theta.bias", h), W("phi.weight", h, C), W("phi.bias", h),
|
|
411
|
+
W("g.weight", h, C), W("g.bias", h), W("out.weight", C, h), W("out.bias", C)]
|
|
412
|
+
if t == "cross_attn":
|
|
413
|
+
C2 = ins2[0]
|
|
414
|
+
return [W("q.weight", C, C), W("q.bias", C), W("kv.weight", 2 * C, C2), W("kv.bias", 2 * C),
|
|
415
|
+
W("proj.weight", C, C), W("proj.bias", C)]
|
|
416
|
+
if t == "pos_enc":
|
|
417
|
+
return [(f"{k}.pe", [C, _prod(ins[1:])], "weight", "normal02")] if o("mode") == "learned" else []
|
|
418
|
+
if t == "patch_embed":
|
|
419
|
+
p = o("patch")
|
|
420
|
+
return [W("proj.weight", o("dim"), C, p, p), W("proj.bias", o("dim"))]
|
|
421
|
+
if t == "cls_token":
|
|
422
|
+
return [(f"{k}.cls", [C], "weight", "normal02")]
|
|
423
|
+
if t in ("layernorm", "groupnorm", "instancenorm"):
|
|
424
|
+
return [(f"{k}.weight", [C], "weight", "ones"), (f"{k}.bias", [C], "weight", "zeros")]
|
|
425
|
+
if t == "rmsnorm":
|
|
426
|
+
return [(f"{k}.weight", [C], "weight", "ones")]
|
|
427
|
+
if t == "prelu":
|
|
428
|
+
return [(f"{k}.weight", [1], "weight", "const0.25")]
|
|
429
|
+
if t == "embedding":
|
|
430
|
+
return [(f"{k}.weight", [o("bins"), o("dim")], "weight", "normal1")]
|
|
431
|
+
if t == "mnv3s":
|
|
432
|
+
return mnv3s_params(k, o("train_last"), o("out"))
|
|
433
|
+
return []
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def mnv3s_params(k: str, train_last: int = 0, out_kind: str = "vector") -> list:
|
|
437
|
+
"""MobileNetV3-Small 가중치 (처음 값은 사전학습 파일). 종류 frozen = 학습하지 않음.
|
|
438
|
+
train_last > 0 (미세조정): 끝 블록 train_last개(특징 1024개면 마지막 1×1 합성곱 둘도)는 weight (함께 학습).
|
|
439
|
+
out_kind "map" (특징 지도): 앞 블록 8개까지만."""
|
|
440
|
+
nb = MNV3S_MAP_BLOCKS if out_kind == "map" else len(MNV3S_CFG)
|
|
441
|
+
tune = nb - train_last if train_last else nb + 1
|
|
442
|
+
out = []
|
|
443
|
+
for j, (i, kk, e, o, q, hs, s) in enumerate(MNV3S_CFG[:nb]):
|
|
444
|
+
kind = "weight" if j >= tune else "frozen"
|
|
445
|
+
Fz = lambda name, *shape: (f"{k}.{name}", list(shape), kind, "pretrained")
|
|
446
|
+
p = f"blocks.{j}."
|
|
447
|
+
if e != i:
|
|
448
|
+
out += [Fz(p + "expand.weight", e, i, 1, 1), Fz(p + "expand.bias", e)]
|
|
449
|
+
out += [Fz(p + "dw.weight", e, 1, kk, kk), Fz(p + "dw.bias", e)]
|
|
450
|
+
if q:
|
|
451
|
+
out += [Fz(p + "se1.weight", q, e, 1, 1), Fz(p + "se1.bias", q), Fz(p + "se2.weight", e, q, 1, 1), Fz(p + "se2.bias", e)]
|
|
452
|
+
out += [Fz(p + "project.weight", o, e, 1, 1), Fz(p + "project.bias", o)]
|
|
453
|
+
kind = "weight" if train_last else "frozen"
|
|
454
|
+
Fz = lambda name, *shape: (f"{k}.{name}", list(shape), kind, "pretrained")
|
|
455
|
+
stem = [(f"{k}.stem.weight", [16, 3, 3, 3], "frozen", "pretrained"), (f"{k}.stem.bias", [16], "frozen", "pretrained")]
|
|
456
|
+
if out_kind == "map":
|
|
457
|
+
return stem + out
|
|
458
|
+
return stem + out + [Fz("last.weight", 576, 96, 1, 1), Fz("last.bias", 576),
|
|
459
|
+
Fz("head.weight", MNV3S_OUT, 576, 1, 1), Fz("head.bias", MNV3S_OUT)]
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
# ---------------------------------------------------------------- PyTorch 모듈: (이름, 인자) — "nn.X"는 torch 내장, 나머지는 nn_extra
|
|
463
|
+
|
|
464
|
+
def torch_args(t: str, b: dict, ins, ins2=None):
|
|
465
|
+
o = lambda key: opt(b, key)
|
|
466
|
+
C, rank = ins[0], len(ins)
|
|
467
|
+
if t == "glu":
|
|
468
|
+
return "GLU", {"c": C, "units": o("units"), "gate": o("gate")}
|
|
469
|
+
if t == "dw_conv":
|
|
470
|
+
return "nn.Conv1d", {"_": [C, C * o("multiplier"), o("kernel")], "padding": o("kernel") // 2, "groups": C}
|
|
471
|
+
if t == "dw_conv2d":
|
|
472
|
+
return "nn.Conv2d", {"_": [C, C * o("multiplier"), o("kernel")], "padding": o("kernel") // 2, "groups": C}
|
|
473
|
+
if t in ("sep_conv", "sep_conv2d"):
|
|
474
|
+
return "SeparableConv", {"c": C, "out": o("channels"), "k": o("kernel"), "dims": 2 if t == "sep_conv2d" else 1}
|
|
475
|
+
if t == "max_pool":
|
|
476
|
+
return "nn.MaxPool1d", {"_": [o("size")]}
|
|
477
|
+
if t == "max_pool2d":
|
|
478
|
+
return "nn.MaxPool2d", {"_": [2]}
|
|
479
|
+
if t in ("global_max", "global_max2d"):
|
|
480
|
+
return "GlobalMax", {}
|
|
481
|
+
if t == "adaptive_pool":
|
|
482
|
+
cls = {("avg", 2): "AdaptiveAvgPool1d", ("avg", 3): "AdaptiveAvgPool2d",
|
|
483
|
+
("max", 2): "AdaptiveMaxPool1d", ("max", 3): "AdaptiveMaxPool2d"}[(o("mode"), rank)]
|
|
484
|
+
return "nn." + cls, {"_": [o("size")]}
|
|
485
|
+
if t == "first_step":
|
|
486
|
+
return "FirstStep", {}
|
|
487
|
+
if t == "attn_pool":
|
|
488
|
+
return "AttentionPool", {"c": C}
|
|
489
|
+
if t == "upsample":
|
|
490
|
+
mode = "nearest" if o("mode") == "nearest" else ("linear" if rank == 2 else "bilinear")
|
|
491
|
+
kw = {"scale_factor": 2, "mode": mode}
|
|
492
|
+
if mode != "nearest":
|
|
493
|
+
kw["align_corners"] = False
|
|
494
|
+
return "nn.Upsample", kw
|
|
495
|
+
if t == "pixel_shuffle":
|
|
496
|
+
return "PixelShuffle", {}
|
|
497
|
+
if t in ("conv_t", "conv_t2d"):
|
|
498
|
+
k, st = o("kernel"), o("stride")
|
|
499
|
+
p, op = T_PAD[k] if st == 2 else ((k - 1) // 2, 0)
|
|
500
|
+
cls = "nn.ConvTranspose1d" if t == "conv_t" else "nn.ConvTranspose2d"
|
|
501
|
+
kw = {"_": [C, o("channels"), k], "stride": st, "padding": p}
|
|
502
|
+
if op:
|
|
503
|
+
kw["output_padding"] = op
|
|
504
|
+
return cls, kw
|
|
505
|
+
if t == "eca":
|
|
506
|
+
return "ECA", {"k": o("kernel")}
|
|
507
|
+
if t == "cbam":
|
|
508
|
+
return "CBAM", {"c": C, "ratio": o("ratio"), "k": o("kernel"), "dims": rank - 1}
|
|
509
|
+
if t == "spatial_attn":
|
|
510
|
+
return "SpatialAttention", {"k": o("kernel"), "dims": rank - 1}
|
|
511
|
+
if t == "mha":
|
|
512
|
+
return "MultiHeadAttention", {"c": C, "heads": o("heads"), "causal": bool(o("causal")), "rope": o("pos") == "rope"}
|
|
513
|
+
if t == "linear_attn":
|
|
514
|
+
return "LinearAttention", {"c": C, "heads": o("heads")}
|
|
515
|
+
if t == "nonlocal":
|
|
516
|
+
return "NonLocal", {"c": C}
|
|
517
|
+
if t == "cross_attn":
|
|
518
|
+
return "CrossAttention", {"c": C, "c2": ins2[0], "heads": o("heads")}
|
|
519
|
+
if t == "pos_enc":
|
|
520
|
+
return "PositionalEncoding", {"c": C, "n": _prod(ins[1:]), "learned": o("mode") == "learned"}
|
|
521
|
+
if t == "patch_embed":
|
|
522
|
+
return "PatchEmbedding", {"c": C, "dim": o("dim"), "patch": o("patch")}
|
|
523
|
+
if t == "cls_token":
|
|
524
|
+
return "ClsToken", {"c": C}
|
|
525
|
+
if t == "layernorm":
|
|
526
|
+
return "LayerNorm", {"c": C}
|
|
527
|
+
if t == "rmsnorm":
|
|
528
|
+
return "RMSNorm", {"c": C}
|
|
529
|
+
if t == "groupnorm":
|
|
530
|
+
return "nn.GroupNorm", {"_": [o("groups"), C]}
|
|
531
|
+
if t == "instancenorm":
|
|
532
|
+
return "nn.GroupNorm", {"_": [C, C]}
|
|
533
|
+
if t == "prelu":
|
|
534
|
+
return "nn.PReLU", {}
|
|
535
|
+
if t == "spatial_dropout":
|
|
536
|
+
return ("nn.Dropout1d" if rank == 2 else "nn.Dropout2d"), {"_": [float(o("rate"))]}
|
|
537
|
+
if t == "drop_path":
|
|
538
|
+
return "DropPath", {"rate": float(o("rate"))}
|
|
539
|
+
if t == "gaussian_noise":
|
|
540
|
+
return "GaussianNoise", {"std": float(o("std"))}
|
|
541
|
+
if t == "slice":
|
|
542
|
+
return "Split", {"start": o("start"), "count": o("count")}
|
|
543
|
+
if t == "reshape":
|
|
544
|
+
return "Reshape", {"c": o("channels")}
|
|
545
|
+
if t == "permute":
|
|
546
|
+
return "Transpose", {}
|
|
547
|
+
if t == "to_seq":
|
|
548
|
+
return "ToSequence", {}
|
|
549
|
+
if t == "crop":
|
|
550
|
+
return "Crop", {"a": o("amount")}
|
|
551
|
+
if t == "pad":
|
|
552
|
+
return "Pad", {"a": o("amount")}
|
|
553
|
+
if t == "embedding":
|
|
554
|
+
return "Embedding", {"bins": o("bins"), "dim": o("dim")}
|
|
555
|
+
if t == "spectrogram":
|
|
556
|
+
return "Spectrogram", {"n_fft": o("n_fft"), "hop": o("hop"), "mode": o("mode"), "n_mels": o("n_mels"), "n_mfcc": o("n_mfcc")}
|
|
557
|
+
if t == "rand_flip":
|
|
558
|
+
return "RandomFlip", {"dir": o("dir")}
|
|
559
|
+
if t == "rand_rotate":
|
|
560
|
+
return "RandomRotation", {"degrees": o("degrees")}
|
|
561
|
+
if t == "rand_shift":
|
|
562
|
+
return "RandomShift", {"frac": float(o("frac"))}
|
|
563
|
+
if t == "rand_zoom":
|
|
564
|
+
return "RandomZoom", {"frac": float(o("frac"))}
|
|
565
|
+
if t == "rand_scale":
|
|
566
|
+
return "RandomScale", {"frac": float(o("frac"))}
|
|
567
|
+
if t == "rand_stretch":
|
|
568
|
+
return "RandomStretch", {"frac": float(o("frac"))}
|
|
569
|
+
if t == "mnv3s":
|
|
570
|
+
return "MobileNetV3Small", dict({"size": o("size")}, **({"train_last": o("train_last")} if o("train_last") else {}),
|
|
571
|
+
**({"out": "map"} if o("out") == "map" else {}))
|
|
572
|
+
raise ValueError(f"알 수 없는 층 {t}")
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def args_text(kw: dict) -> str:
|
|
576
|
+
"""인자 dict → 코드 글자 ("_"는 자리 인자)."""
|
|
577
|
+
pos = [repr(v) for v in kw.get("_", [])]
|
|
578
|
+
named = [f"{k}={v!r}" for k, v in kw.items() if k != "_"]
|
|
579
|
+
return ", ".join(pos + named)
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
# ---------------------------------------------------------------- 고정 표 (Spectrogram·위치): 웹 엔진(engine.js)도 같은 식
|
|
583
|
+
|
|
584
|
+
SR = 16000 # mel 눈금에 쓰는 가정 표본 주파수 (신호의 실제 주파수와는 상관없이 낮은 칸을 촘촘히)
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def mel_matrix(n_fft: int, n_mels: int) -> list:
|
|
588
|
+
"""(n_mels, n_fft//2+1) 삼각 mel 필터 (HTK 식)."""
|
|
589
|
+
F = n_fft // 2 + 1
|
|
590
|
+
mel = lambda f: 2595.0 * math.log10(1.0 + f / 700.0)
|
|
591
|
+
hz = lambda m: 700.0 * (10 ** (m / 2595.0) - 1.0)
|
|
592
|
+
top = mel(SR / 2)
|
|
593
|
+
pts = [hz(top * i / (n_mels + 1)) for i in range(n_mels + 2)]
|
|
594
|
+
freqs = [SR / 2 * j / (F - 1) for j in range(F)]
|
|
595
|
+
out = []
|
|
596
|
+
for m in range(n_mels):
|
|
597
|
+
lo, c, hi = pts[m], pts[m + 1], pts[m + 2]
|
|
598
|
+
row = []
|
|
599
|
+
for f in freqs:
|
|
600
|
+
up = (f - lo) / (c - lo) if c > lo else 0.0
|
|
601
|
+
down = (hi - f) / (hi - c) if hi > c else 0.0
|
|
602
|
+
row.append(max(0.0, min(up, down)))
|
|
603
|
+
out.append(row)
|
|
604
|
+
return out
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def dct_matrix(n_mfcc: int, n_mels: int) -> list:
|
|
608
|
+
"""(n_mfcc, n_mels) DCT-II (정규 직교)."""
|
|
609
|
+
return [[math.sqrt((1.0 if k == 0 else 2.0) / n_mels) * math.cos(math.pi / n_mels * (m + 0.5) * k)
|
|
610
|
+
for m in range(n_mels)] for k in range(n_mfcc)]
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def sin_table(c: int, n: int) -> list:
|
|
614
|
+
"""(c, n) 위치 표: 채널 2i는 sin, 2i+1은 cos, 파장은 10000^(2i/c)."""
|
|
615
|
+
return [[(math.sin if ch % 2 == 0 else math.cos)(p / 10000 ** ((ch - ch % 2) / c)) for p in range(n)] for ch in range(c)]
|