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.
Files changed (74) hide show
  1. blocklearning/__init__.py +1 -0
  2. blocklearning/__main__.py +6 -0
  3. blocklearning/analysis.py +133 -0
  4. blocklearning/anomaly.py +148 -0
  5. blocklearning/blocks.py +601 -0
  6. blocklearning/cli.py +46 -0
  7. blocklearning/codegen.py +1012 -0
  8. blocklearning/core.py +861 -0
  9. blocklearning/data/bearing_uottawa.SOURCE.txt +6 -0
  10. blocklearning/data/bearing_uottawa.npz +0 -0
  11. blocklearning/data/concrete.SOURCE.txt +4 -0
  12. blocklearning/data/concrete.npz +0 -0
  13. blocklearning/data/digits32.SOURCE.txt +4 -0
  14. blocklearning/data/digits32.npz +0 -0
  15. blocklearning/data/ecg_mitdb.SOURCE.txt +6 -0
  16. blocklearning/data/ecg_mitdb.npz +0 -0
  17. blocklearning/data/hydraulic.SOURCE.txt +6 -0
  18. blocklearning/data/hydraulic.npz +0 -0
  19. blocklearning/data/pcb_det.SOURCE.txt +6 -0
  20. blocklearning/data/pcb_det.npz +0 -0
  21. blocklearning/data/pneumatic_seg.SOURCE.txt +8 -0
  22. blocklearning/data/pneumatic_seg.npz +0 -0
  23. blocklearning/data/pneumonia28.SOURCE.txt +13 -0
  24. blocklearning/data/pneumonia28.npz +0 -0
  25. blocklearning/data/steel_plates.SOURCE.txt +5 -0
  26. blocklearning/data/steel_plates.npz +0 -0
  27. blocklearning/data/steel_power.SOURCE.txt +3 -0
  28. blocklearning/data/steel_power.npz +0 -0
  29. blocklearning/data/steelblast.SOURCE.txt +4 -0
  30. blocklearning/data/steelblast.npz +0 -0
  31. blocklearning/data.py +1158 -0
  32. blocklearning/detect.py +222 -0
  33. blocklearning/forecast.py +204 -0
  34. blocklearning/graph.py +602 -0
  35. blocklearning/jobs.py +501 -0
  36. blocklearning/labeling.py +1294 -0
  37. blocklearning/labeling_sources.py +217 -0
  38. blocklearning/layers.py +615 -0
  39. blocklearning/losses.py +199 -0
  40. blocklearning/multi.py +175 -0
  41. blocklearning/nn_extra.py +643 -0
  42. blocklearning/predict.py +344 -0
  43. blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
  44. blocklearning/pretrained/mnv3s.SOURCE.txt +6 -0
  45. blocklearning/pretrained/mnv3s.bin +0 -0
  46. blocklearning/pretrained/mnv3s.json +1 -0
  47. blocklearning/pretrained.py +56 -0
  48. blocklearning/project.py +120 -0
  49. blocklearning/segment.py +173 -0
  50. blocklearning/server.py +116 -0
  51. blocklearning/static/app.js +1986 -0
  52. blocklearning/static/boot.js +51 -0
  53. blocklearning/static/demo.jpg +0 -0
  54. blocklearning/static/demo.webm +0 -0
  55. blocklearning/static/engine.js +1326 -0
  56. blocklearning/static/graph.js +1902 -0
  57. blocklearning/static/index.html +301 -0
  58. blocklearning/static/label.html +158 -0
  59. blocklearning/static/label.js +1040 -0
  60. blocklearning/static/labels.js +227 -0
  61. blocklearning/static/projects.js +516 -0
  62. blocklearning/static/store.js +259 -0
  63. blocklearning/static/style.css +844 -0
  64. blocklearning/static/train-worker.js +41 -0
  65. blocklearning/static/web.js +602 -0
  66. blocklearning/tasks.py +351 -0
  67. blocklearning/web.py +412 -0
  68. blocklearning/weblabel.py +316 -0
  69. blocklearning-0.1.0.dist-info/METADATA +66 -0
  70. blocklearning-0.1.0.dist-info/RECORD +74 -0
  71. blocklearning-0.1.0.dist-info/WHEEL +4 -0
  72. blocklearning-0.1.0.dist-info/entry_points.txt +2 -0
  73. blocklearning-0.1.0.dist-info/licenses/LICENSE +25 -0
  74. blocklearning-0.1.0.dist-info/licenses/src/blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
@@ -0,0 +1,1012 @@
1
+ """그래프 → 파이썬 코드 (PyTorch · TensorFlow Keras).
2
+
3
+ 화면에서 이은 모델을 사람이 읽고 고칠 수 있는 코드로 바꾼다. 층 하나가 코드 한 줄(변수 하나)이 되고, 줄마다 화면 이름과 출력 모양을 주석으로 단다.
4
+ Repeat 묶음은 반복마다 펼친다 (이름: <층>_r<반복 번호>, 예: conv_r0 · conv_r1).
5
+
6
+ - PyTorch: studio 모델과 계산이 같다. torch_state_dict()로 studio에서 학습한 가중치를 생성 코드의 이름으로 바꿔 그대로 불러올 수 있다.
7
+ - Keras: 같은 구조 (채널이 마지막인 모양). 가중치는 옮기지 않으므로 TF에서 새로 학습한다.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import keyword
12
+ from dataclasses import dataclass, field
13
+ from typing import Optional
14
+
15
+ from blocklearning import layers as X
16
+ from blocklearning.blocks import RNN_TYPES
17
+ from blocklearning.graph import BODY_IN, INPUT, _Checker, _config, _key, channels_of
18
+
19
+ FRAMEWORKS = ("pytorch", "tensorflow")
20
+ RESERVED = {"x", "self", "torch", "nn", "F", "tf", "keras", "layers", "model", "np", "h", "s"}
21
+
22
+
23
+ @dataclass
24
+ class Step:
25
+ """펼친 층 하나: 코드 이름, 종류, 설정, 입력 이름들, 들어오는/나가는 모양(배치 제외, 채널 먼저), studio 가중치 키 앞부분."""
26
+ name: str
27
+ type: str
28
+ cfg: dict
29
+ inputs: list
30
+ in_shape: tuple
31
+ out_shape: tuple
32
+ key: str # 예: "mods.m_b0" · "mods.m_R.1.m_c"
33
+ node: str = "" # 그래프의 노드 id (Repeat 안이면 안쪽 id)
34
+ in_shapes: list = field(default_factory=list) # 입력마다 모양 (입력이 둘인 층)
35
+
36
+
37
+ @dataclass
38
+ class Plan:
39
+ steps: list = field(default_factory=list)
40
+ kind: str = "cnn" # cnn | rnn | image
41
+ in_shape: tuple = ()
42
+ out: str = ""
43
+ n_out: int = 1
44
+ aliases: dict = field(default_factory=dict) # Repeat 노드 id → 마지막 반복의 출구 이름
45
+
46
+
47
+ def _ident(nid: str, used: set) -> str:
48
+ n = nid if nid.isidentifier() and not keyword.iskeyword(nid) and nid not in RESERVED else "n_" + nid
49
+ base, k = n, 2
50
+ while n in used:
51
+ n, k = f"{base}_{k}", k + 1
52
+ used.add(n)
53
+ return n
54
+
55
+
56
+ # 생성 코드의 변수 이름: 층 종류 + 번호 (conv1, relu1, pool1 …). 가중치 이름(key)과는 따로라 바꿔도 저장한 프로젝트와 상관없음
57
+ PREFIX = {"conv": "conv", "conv2d": "conv", "pool": "pool", "pool2d": "pool", "global_avg": "gap", "global_avg2d": "gap",
58
+ "last_step": "last", "bn": "bn", "dropout": "drop", "flatten": "flat", "dense": "fc", "lstm": "lstm", "gru": "gru",
59
+ "simple_rnn": "rnn", "se": "se", "add": "add", "concat": "cat",
60
+ "glu": "glu", "dw_conv": "dwconv", "dw_conv2d": "dwconv", "sep_conv": "sepconv", "sep_conv2d": "sepconv",
61
+ "max_pool": "maxpool", "max_pool2d": "maxpool", "global_max": "gmp", "global_max2d": "gmp", "adaptive_pool": "apool",
62
+ "first_step": "first", "attn_pool": "attnpool", "upsample": "up", "pixel_shuffle": "shuffle", "conv_t": "convt",
63
+ "conv_t2d": "convt", "eca": "eca", "cbam": "cbam", "spatial_attn": "spattn", "mha": "attn", "linear_attn": "linattn",
64
+ "nonlocal": "nonlocal", "cross_attn": "xattn", "pos_enc": "pos", "patch_embed": "patch", "cls_token": "cls",
65
+ "layernorm": "ln", "rmsnorm": "rms", "groupnorm": "gn", "instancenorm": "inorm", "prelu": "prelu",
66
+ "spatial_dropout": "sdrop", "drop_path": "droppath", "gaussian_noise": "noise", "slice": "split",
67
+ "reshape": "reshape", "permute": "transpose", "to_seq": "seq", "crop": "crop", "pad": "pad", "embedding": "emb",
68
+ "spectrogram": "spec", "rand_flip": "flip", "rand_rotate": "rotate", "rand_shift": "shift", "rand_zoom": "zoom",
69
+ "rand_scale": "scale", "rand_stretch": "stretch", "multiply": "mul", "average": "avg", "maximum": "max",
70
+ "mnv3s": "mnv3"}
71
+
72
+
73
+ def _pretty(t: str, cfg: dict, counts: dict) -> str:
74
+ if t == "output":
75
+ return "out"
76
+ p = cfg.get("kind", "act") if t == "act" else PREFIX.get(t, t)
77
+ counts[p] = counts.get(p, 0) + 1
78
+ return f"{p}{counts[p]}"
79
+
80
+
81
+ def make_plan(graph: dict, length: int, n_out: int, image: tuple = None) -> Plan:
82
+ """그래프 → 펼친 층 목록. 검사를 통과하지 못하면 ValueError(첫 문제)."""
83
+ from blocklearning.graph import check_graph
84
+ checked = check_graph(graph, length, n_out, image=image, rules=False)
85
+ if not checked.ok:
86
+ raise ValueError(checked.issues[0].message)
87
+ c = _Checker(length, n_out, image)
88
+ sc = c.scope(c.form(graph), INPUT)
89
+ start = (1,) + tuple(image) if image else (channels_of(length), int(length))
90
+ plan = Plan(kind=checked.kind, in_shape=start, n_out=n_out)
91
+ used: set = set()
92
+ counts: dict = {}
93
+
94
+ def walk(scope, in_shape, in_name: str, suffix: str, key_prefix: str) -> str:
95
+ c.shape_pass(scope, in_shape)
96
+ shapes = {scope.entry: tuple(in_shape)}
97
+ names = {scope.entry: in_name}
98
+ for k in scope.order:
99
+ n = scope.nodes[k]
100
+ t, ins = n["type"], list(n.get("inputs") or [])
101
+ if t == "repeat":
102
+ cur, s = names[ins[0]], shapes[ins[0]]
103
+ body = scope.bodies[k]
104
+ for i in range(n["times"]):
105
+ cur = walk(body, s, cur, f"{suffix}_r{i}", f"{key_prefix}{_key(k)}.{i}.")
106
+ s = tuple(c.shapes[body.exit])
107
+ names[k], shapes[k] = cur, s
108
+ plan.aliases[k] = cur
109
+ continue
110
+ nm = _ident(_pretty(t, n, counts), used)
111
+ out = tuple(c.shapes[k])
112
+ cfg = _config(n)
113
+ if t == "output" and getattr(n_out, "grid", None): # 탐지 출력: 격자 칸마다 1×1 필터
114
+ cfg = dict(cfg, head="grid", per_cell=n_out.per_cell, grid=n_out.grid)
115
+ if t == "output" and getattr(n_out, "seg", False): # 구간 분할 출력: 시점마다 1×1 필터
116
+ cfg = dict(cfg, head="seq", n_cls=n_out.n_cls)
117
+ plan.steps.append(Step(nm, t, cfg, [names[x] for x in ins], shapes[ins[0]], out, key_prefix + _key(k), k,
118
+ [tuple(shapes[x]) for x in ins]))
119
+ names[k], shapes[k] = nm, out
120
+ return names[scope.exit]
121
+
122
+ plan.out = walk(sc, start, "x", "", "mods.")
123
+ return plan
124
+
125
+
126
+ # ---------------------------------------------------------------- 공통 글자
127
+
128
+ ACT_LABEL = {"selu": "SELU", "relu6": "ReLU6", "hardswish": "HardSwish", "hardsigmoid": "HardSigmoid", "softmax": "Softmax",
129
+ "relu": "ReLU", "leaky_relu": "LeakyReLU", "gelu": "GELU", "silu": "SiLU", "elu": "ELU", "mish": "Mish",
130
+ "softplus": "Softplus", "sigmoid": "Sigmoid", "tanh": "Tanh"}
131
+
132
+
133
+ def _label(s: Step) -> str:
134
+ b, t = s.cfg, s.type
135
+ if t in ("conv", "conv2d"):
136
+ extra = "".join(f" · {k} {b[k]}" for k in ("stride", "dilation", "groups") if b.get(k, 1) != 1)
137
+ return f"{'Conv1D' if t == 'conv' else 'Conv2D'} {b['channels']} filters · k={b['kernel']}{extra}" + \
138
+ (" · valid" if b.get("padding") == "valid" else "")
139
+ return {"pool": f"AvgPool1D {b.get('size')}", "pool2d": "AvgPool2D 2", "global_avg": "GlobalAvgPool1D",
140
+ "global_avg2d": "GlobalAvgPool2D", "last_step": "LastTimestep", "bn": "BatchNorm",
141
+ "act": ACT_LABEL.get(b.get("kind"), "Activation"), "dropout": f"Dropout {b.get('rate', 0.5)}",
142
+ "flatten": "Flatten", "dense": f"Dense {b.get('units')}", "output": "Output",
143
+ "lstm": f"LSTM {b.get('hidden')}", "gru": f"GRU {b.get('hidden')}", "simple_rnn": f"SimpleRNN {b.get('hidden')}",
144
+ "se": f"SE block (ratio {b.get('ratio', 4)})", "add": "Add", "concat": "Concat"}.get(t, X.name_of(t))
145
+
146
+
147
+ def _shape_text(shape: tuple) -> str:
148
+ return "(" + ", ".join(str(v) for v in shape) + ")"
149
+
150
+
151
+ def _prod(shape) -> int:
152
+ n = 1
153
+ for v in shape:
154
+ n *= v
155
+ return n
156
+
157
+
158
+ def _io_doc(plan: Plan, data_info: Optional[dict], channels_last: bool) -> list:
159
+ """파일 머리 설명: 입력·출력 모양과 데이터 준비."""
160
+ L = plan.in_shape
161
+ if plan.kind == "image":
162
+ shape = f"(샘플 수, {L[1]}, {L[2]}, 1)" if channels_last else f"(샘플 수, 1, {L[1]}, {L[2]})"
163
+ what = "흑백 그림 (높이 × 너비)"
164
+ elif plan.kind == "rnn":
165
+ shape, what = f"(샘플 수, {L[1]}, {L[0]})", ("시점마다 값 하나" if L[0] == 1 else f"시점마다 채널 {L[0]}개의 값") + " (순환 층은 시점이 먼저)"
166
+ elif L[0] > 1:
167
+ shape = f"(샘플 수, {L[1]}, {L[0]})" if channels_last else f"(샘플 수, {L[0]}, {L[1]})"
168
+ what = f"채널 {L[0]}개의 시계열 (채널마다 길이 {L[1]})"
169
+ else:
170
+ shape = f"(샘플 수, {L[1]}, 1)" if channels_last else f"(샘플 수, 1, {L[1]})"
171
+ what = "값 한 줄 (시계열이면 시점, 표면 특징)"
172
+ lines = [f"입력: {shape} — {what}"]
173
+ info = data_info or {}
174
+ head = next((s.cfg for s in plan.steps if s.type == "output" and s.cfg.get("head") == "grid"), None)
175
+ if head:
176
+ G, A = head["grid"], head["per_cell"]
177
+ lines.append(f"출력: (샘플 수, {plan.n_out}) = 칸마다 값 {A}개 × 격자 {G}×{G}칸을 펼친 것 (값 순서가 먼저, PyTorch 모양 (값, 세로, 가로)). "
178
+ f"칸마다: 사물 있음 · 칸 안 가운데 x·y · 너비·높이의 제곱근 · 클래스 점수 {A - 5}개"
179
+ + (f" ({', '.join(map(str, info.get('classes') or []))})" if info.get("classes") else ""))
180
+ lines.append("정답: 그림마다 같은 모양의 목표값 (BlockLearning의 blocklearning.detect.encode). 찾은 상자는 아래 decode()로.")
181
+ return lines
182
+ seq = next((s.cfg for s in plan.steps if s.type == "output" and s.cfg.get("head") == "seq"), None)
183
+ if seq:
184
+ K = seq["n_cls"]
185
+ lines.append(f"출력: (샘플 수, {plan.n_out}) = 시점마다 상태 점수 {K}개 × 길이 {plan.n_out // K}를 펼친 것 (상태가 먼저, 모양 (상태, 시점))"
186
+ + (f". 상태: {', '.join(map(str, info.get('classes') or []))}" if info.get("classes") else ""))
187
+ lines.append("정답: 창마다 시점마다 상태 번호 (샘플 수, 길이). 예측 = 시점마다 점수가 가장 큰 상태.")
188
+ return lines
189
+ if info.get("task") == "classification" and info.get("classes"):
190
+ lines.append(f"출력: (샘플 수, {plan.n_out}) 클래스 점수 — 가장 큰 칸이 예측. 순서: {', '.join(map(str, info['classes']))}")
191
+ elif info.get("task") == "regression":
192
+ lines.append("출력: (샘플 수, 1) 예측값")
193
+ elif info.get("task") == "forecast":
194
+ lines.append(f"출력: (샘플 수, {plan.n_out}) 다음 {plan.n_out}개 값 (원래 단위). 입력 = 바로 앞의 값들 (신호 전체의 평균·표준편차로 정규화)")
195
+ if info.get("calendar"):
196
+ lines.append("입력 채널: 값, " + ", ".join(info["calendar"]) + " — 그 시점의 하루 중 시각 a = 2π·(초/86400)의 sin·cos, "
197
+ "요일 b = 2π·((월요일 0 … 일요일 6) + 초/86400)/7의 sin·cos (정규화하지 않음)")
198
+ elif info.get("task") == "multi" and info.get("heads"):
199
+ lines.append(f"출력: (샘플 수, {plan.n_out}) 정답마다의 머리를 이어 붙인 것 — " + "; ".join(
200
+ f"{h['name']} [{h['start']}:{h['start'] + h['size']}] " +
201
+ (f"클래스 점수 ({', '.join(map(str, h['classes']))})" if h["kind"] == "class" else "값 (원래 단위)") for h in info["heads"]))
202
+ elif info.get("task") == "anomaly":
203
+ lines.append(f"출력: (샘플 수, {plan.n_out}) 되살린 입력 (정규화한 값). 이상 점수 = (입력 − 출력)²의 평균, 클수록 이상. "
204
+ "정상만으로 학습하세요")
205
+ else:
206
+ lines.append(f"출력: (샘플 수, {plan.n_out})")
207
+ lines.append("데이터 준비: BlockLearning처럼 학습 데이터의 열마다 평균·표준편차로 정규화한 뒤 위 모양으로 바꿔 넣으세요.")
208
+ return lines
209
+
210
+
211
+ # ---------------------------------------------------------------- PyTorch
212
+
213
+ _TORCH_ACT = {"relu": "torch.relu({})", "leaky_relu": "F.leaky_relu({})", "gelu": "F.gelu({})", "silu": "F.silu({})",
214
+ "elu": "F.elu({})", "mish": "F.mish({})", "softplus": "F.softplus({})", "sigmoid": "torch.sigmoid({})",
215
+ "tanh": "torch.tanh({})", "selu": "F.selu({})", "relu6": "F.relu6({})", "hardswish": "F.hardswish({})",
216
+ "hardsigmoid": "F.hardsigmoid({})", "softmax": "torch.softmax({}, dim=1)"}
217
+
218
+ _TORCH_SE = '''
219
+
220
+ class SE(nn.Module):
221
+ """Squeeze-and-Excitation: 채널마다 평균 → Linear → activation → Linear → sigmoid → 채널마다 곱함."""
222
+
223
+ def __init__(self, channels, ratio, act):
224
+ super().__init__()
225
+ hidden = max(1, channels // ratio)
226
+ self.fc1, self.act, self.fc2 = nn.Linear(channels, hidden), act, nn.Linear(hidden, channels)
227
+
228
+ def forward(self, x):
229
+ s = torch.sigmoid(self.fc2(self.act(self.fc1(x.flatten(2).mean(-1)))))
230
+ return x * s.reshape(*s.shape, *([1] * (x.dim() - 2)))
231
+ '''
232
+
233
+ _TORCH_ACT_MODULE = {"relu": "nn.ReLU()", "leaky_relu": "nn.LeakyReLU()", "gelu": "nn.GELU()", "silu": "nn.SiLU()",
234
+ "elu": "nn.ELU()", "mish": "nn.Mish()", "softplus": "nn.Softplus()", "sigmoid": "nn.Sigmoid()",
235
+ "tanh": "nn.Tanh()"}
236
+
237
+
238
+ def _torch_layer(s: Step, n_out: int):
239
+ """(모듈 만드는 식 또는 None, forward 식, studio 키 → 코드 키 짝 [(studio 앞부분, 코드 앞부분)])."""
240
+ b, t, a = s.cfg, s.type, s.inputs[0] if s.inputs else ""
241
+ me = f"self.{s.name}"
242
+ if t == "conv" and b.get("padding") == "causal":
243
+ opts = "".join(f", {n}={v}" for n, v, dflt in (("stride", b.get("stride", 1), 1), ("dilation", b.get("dilation", 1), 1),
244
+ ("groups", b.get("groups", 1), 1)) if v != dflt)
245
+ return f"CausalConv1d({s.in_shape[0]}, {b['channels']}, {b['kernel']}{opts})", f"{me}({a})", [(s.key, s.name)]
246
+ if t == "conv":
247
+ k, d = b["kernel"], b.get("dilation", 1)
248
+ pad = 0 if b.get("padding", "same") == "valid" else d * (k - 1) // 2
249
+ opts = "".join(f", {n}={v}" for n, v, dflt in (("stride", b.get("stride", 1), 1), ("padding", pad, 0),
250
+ ("dilation", d, 1), ("groups", b.get("groups", 1), 1)) if v != dflt)
251
+ return f"nn.Conv1d({s.in_shape[0]}, {b['channels']}, {k}{opts})", f"{me}({a})", [(s.key, s.name)]
252
+ if t == "conv2d":
253
+ k, d = b["kernel"], b.get("dilation", 1)
254
+ pad = 0 if b.get("padding", "same") == "valid" else d * (k - 1) // 2
255
+ opts = "".join(f", {n}={v}" for n, v, dflt in (("stride", b.get("stride", 1), 1), ("padding", pad, 0), ("dilation", d, 1),
256
+ ("groups", b.get("groups", 1), 1)) if v != dflt)
257
+ return f"nn.Conv2d({s.in_shape[0]}, {b['channels']}, {k}{opts})", f"{me}({a})", [(s.key, s.name)]
258
+ if t == "pool":
259
+ return None, f"F.avg_pool1d({a}, {b['size']})", []
260
+ if t == "pool2d":
261
+ return None, f"F.avg_pool2d({a}, 2)", []
262
+ if t == "global_avg":
263
+ return None, f"{a}.mean(-1)", []
264
+ if t == "global_avg2d":
265
+ return None, f"{a}.mean(dim=(-1, -2))", []
266
+ if t == "last_step":
267
+ return None, f"{a}[:, :, -1]", []
268
+ if t == "bn":
269
+ cls = "nn.BatchNorm2d" if len(s.in_shape) == 3 else "nn.BatchNorm1d"
270
+ return f"{cls}({s.in_shape[0]})", f"{me}({a})", [(s.key, s.name)]
271
+ if t == "act":
272
+ return None, _TORCH_ACT[b["kind"]].format(a), []
273
+ if t == "dropout":
274
+ return f"nn.Dropout({float(b.get('rate', 0.5))})", f"{me}({a})", []
275
+ if t == "flatten":
276
+ return None, f"torch.flatten({a}, 1)", []
277
+ if t == "output" and b.get("head") == "grid":
278
+ return f"nn.Conv2d({s.in_shape[0]}, {b['per_cell']}, 1)", f"torch.flatten({me}({a}), 1)", [(s.key + ".0", s.name)]
279
+ if t == "output" and b.get("head") == "seq":
280
+ return f"nn.Conv1d({s.in_shape[0]}, {b['n_cls']}, 1)", f"torch.flatten({me}({a}), 1)", [(s.key + ".0", s.name)]
281
+ if t == "output" and b.get("head") == "distance":
282
+ C = _prod(s.in_shape)
283
+ return f"NormalDistance({C}, {X.dist_k(C)})", f"{me}({a})", [(s.key, s.name)]
284
+ if t in ("dense", "output"):
285
+ units = n_out if t == "output" else b["units"]
286
+ flat = len(s.in_shape) >= 2
287
+ src = f"torch.flatten({a}, 1)" if flat else a
288
+ return f"nn.Linear({_prod(s.in_shape)}, {units})", f"{me}({src})", [(s.key + (".1" if flat else ""), s.name)]
289
+ if t in RNN_TYPES:
290
+ opts = "".join(f", {n}={v}" for n, v, dflt in (("layers", b.get("layers", 1), 1), ("bidirectional", bool(b.get("bidirectional")), False),
291
+ ("return_sequences", bool(b.get("return_sequences")), False)) if v != dflt)
292
+ return f'RNNBlock("{t}", {s.in_shape[0]}, {b["hidden"]}{opts})', f"{me}({a})", [(s.key, s.name)]
293
+ if t in X.EXTRA_TYPES:
294
+ name, kw = X.torch_args(t, b, s.in_shape, s.in_shapes[1] if len(s.in_shapes) > 1 else None)
295
+ expr = f"{me}({a}, {s.inputs[1]})" if t in X.TWO_INPUT else f"{me}({a})"
296
+ return f"{name}({X.args_text(kw)})", expr, [(s.key, s.name)]
297
+ if t == "multiply":
298
+ return None, " * ".join(s.inputs), []
299
+ if t == "average":
300
+ return None, f"({' + '.join(s.inputs)}) / {len(s.inputs)}", []
301
+ if t == "maximum":
302
+ return None, f"torch.stack([{', '.join(s.inputs)}]).amax(0)", []
303
+ if t == "se":
304
+ act = _TORCH_ACT_MODULE[b.get("act", "relu")]
305
+ return f"SE({s.in_shape[0]}, {b.get('ratio', 4)}, {act})", f"{me}({a})", [(s.key, s.name)]
306
+ if t == "add":
307
+ return None, " + ".join(s.inputs), []
308
+ if t == "concat":
309
+ return None, f"torch.cat([{', '.join(s.inputs)}], dim=1)", []
310
+ raise ValueError(f"코드로 바꿀 수 없는 층: {t}")
311
+
312
+
313
+ def _extra_classes(plan: Plan) -> list:
314
+ """생성 코드에 넣을 nn_extra 클래스 이름 (쓴 순서)."""
315
+ out = []
316
+ for s in plan.steps:
317
+ if s.type in RNN_TYPES:
318
+ name = "RNNBlock"
319
+ elif s.type == "conv" and s.cfg.get("padding") == "causal":
320
+ name = "CausalConv1d"
321
+ elif s.type in X.EXTRA_TYPES:
322
+ name = X.torch_args(s.type, s.cfg, s.in_shape, s.in_shapes[1] if len(s.in_shapes) > 1 else None)[0]
323
+ elif s.type == "output" and s.cfg.get("head") == "distance":
324
+ name = "NormalDistance"
325
+ else:
326
+ continue
327
+ if not name.startswith("nn.") and name not in out:
328
+ out.append(name)
329
+ if any(n in out for n in ("RandomRotation", "RandomShift", "RandomZoom")):
330
+ out.insert(0, "_affine")
331
+ return out
332
+
333
+
334
+ def _class_sources(names: list) -> list:
335
+ """nn_extra.py에서 그 클래스·함수의 소스 (torch 없이 글자로 읽음: 웹(Pyodide)에서도 됨)."""
336
+ import ast
337
+ from pathlib import Path
338
+ text = (Path(__file__).resolve().parent / "nn_extra.py").read_text(encoding="utf-8")
339
+ tree = ast.parse(text)
340
+ found = {n.name: ast.get_source_segment(text, n) for n in tree.body if isinstance(n, (ast.ClassDef, ast.FunctionDef))}
341
+ return [found[n] for n in names]
342
+
343
+
344
+ def _key_map(plan: Plan) -> list:
345
+ out = []
346
+ for s in plan.steps:
347
+ out += _torch_layer(s, plan.n_out)[2]
348
+ return out
349
+
350
+
351
+ def to_pytorch(graph: dict, length: int, n_out: int, image: tuple = None, data_info: Optional[dict] = None,
352
+ train: Optional[dict] = None, weights_file: Optional[str] = None) -> str:
353
+ """PyTorch 코드 (모델 클래스 StudioModel + 학습 함수 + 실행 예). weights_file: 함께 저장한 가중치 파일 이름."""
354
+ plan = make_plan(graph, length, n_out, image)
355
+ task = (data_info or {}).get("task", "classification")
356
+ tr = dict({"epochs": 30, "lr": 1e-3, "batch_size": 32}, **(train or {}))
357
+ init, fwd = [], []
358
+ for s in plan.steps:
359
+ make, expr, _ = _torch_layer(s, plan.n_out)
360
+ if make:
361
+ init.append(f" self.{s.name} = {make}")
362
+ fwd.append((f" {s.name} = {expr}", f"# {_label(s)} → {_shape_text(s.out_shape)}"))
363
+ width = min(80, max(len(a) for a, _ in fwd) + 2)
364
+ fwd_lines = [a.ljust(width) + c for a, c in fwd]
365
+ doc = _io_doc(plan, data_info, channels_last=False)
366
+ ex_shape = ", ".join(["4"] + [str(v) for v in plan.in_shape]) if plan.kind != "rnn" else f"4, {plan.in_shape[1]}, 1"
367
+ if weights_file:
368
+ doc[-1] = "데이터 준비: 아래 predict()에 학습 CSV와 같은 열 순서의 원래 값(정답 열 빼고)을 넣으면 BlockLearning과 같은 정규화를 해 줍니다."
369
+ doc.append(f"학습한 가중치·정규화 값: {weights_file} (BlockLearning에서 학습한 값, load_trained()가 불러옴)")
370
+ lines = ['"""BlockLearning에서 만든 모델 (PyTorch).', ""] + doc + ['"""'] + (["import numpy as np"] if weights_file else []) + [
371
+ "import torch", "import torch.nn.functional as F", "from torch import nn"]
372
+ if any(s.type == "se" for s in plan.steps):
373
+ lines += _TORCH_SE.rstrip("\n").split("\n")
374
+ used = _extra_classes(plan)
375
+ if used:
376
+ lines.insert(lines.index("import torch"), "import math")
377
+ for src in _class_sources(used):
378
+ lines += ["", ""] + src.split("\n")
379
+ lines += ["", "", "class StudioModel(nn.Module):", " def __init__(self):", " super().__init__()"]
380
+ lines += init or [" pass"]
381
+ first = [" x = x.transpose(1, 2) # 순환 모델: (샘플 수, 길이, 1) → 층들이 쓰는 (샘플 수, 1, 길이)"] if plan.kind == "rnn" else []
382
+ act_nodes = sorted({t["node"] for t in (tr.get("loss") or []) if t["term"] == "act_l1"})
383
+ names = dict({s.node: s.name for s in plan.steps}, **plan.aliases)
384
+ keep = [f" self.acts = {{{', '.join(f'{k!r}: {names[k]}' for k in act_nodes if k in names)}}} # 손실 '블록 출력 L1'이 씀"] if act_nodes else []
385
+ lines += ["", " def forward(self, x):"] + first + fwd_lines + keep + [f" return {plan.out}", "", ""]
386
+ head = next((s.cfg for s in plan.steps if s.type == "output" and s.cfg.get("head") == "grid"), None)
387
+ if head:
388
+ return "\n".join(lines + _torch_det(head, tr, weights_file, plan))
389
+ seq = next((s.cfg for s in plan.steps if s.type == "output" and s.cfg.get("head") == "seq"), None)
390
+ custom = tr.get("loss") # 조립한 손실 (BlockLearning ④ 학습 → 더 보기)
391
+ if custom:
392
+ lines += _torch_loss_code(custom, task, plan.n_out if task == "classification" else (seq or {}).get("n_cls", 0),
393
+ tr.get("class_weights"), (data_info or {}).get("heads"))
394
+ if seq: # 구간 분할: 시점마다 교차 엔트로피
395
+ loss, ytype = f"lambda out, t: F.cross_entropy(out.reshape(len(t), {seq['n_cls']}, -1), t)", "torch.long"
396
+ elif task in ("regression", "forecast", "anomaly", "multi"): # 이상 탐지는 y = X (입력을 되살림)
397
+ loss, ytype = "nn.MSELoss()", "torch.float32"
398
+ else:
399
+ loss, ytype = "nn.CrossEntropyLoss()", "torch.long"
400
+ lines += [
401
+ f"def train(model, X, y, epochs={tr['epochs']}, lr={tr['lr']}, batch_size={tr['batch_size']}):",
402
+ f' """X: 위 입력 모양의 배열, y: {_y_doc(task)}. Adam으로 학습."""',
403
+ " X = torch.as_tensor(X, dtype=torch.float32)",
404
+ f" y = torch.as_tensor(y, dtype={ytype})" + (".reshape(len(X), -1)" if task in ("regression", "forecast", "anomaly", "multi") else ""),
405
+ f" opt, loss_fn = torch.optim.Adam(model.parameters(), lr=lr), {'lambda out, t: studio_loss(out, t, model)' if custom else loss}",
406
+ " for epoch in range(epochs):",
407
+ " model.train()",
408
+ " for idx in torch.randperm(len(X)).split(batch_size):",
409
+ " opt.zero_grad()",
410
+ " loss = loss_fn(model(X[idx]), y[idx])",
411
+ " loss.backward()",
412
+ " opt.step()",
413
+ f" print(f\"epoch {{epoch + 1}}: loss {{loss.item():.4f}}\")",
414
+ " return model.eval()",
415
+ "", "",
416
+ ]
417
+ if weights_file:
418
+ if plan.kind == "image":
419
+ shape, n_feat = f"-1, 1, {plan.in_shape[1]}, {plan.in_shape[2]}", plan.in_shape[1] * plan.in_shape[2]
420
+ elif plan.kind == "rnn":
421
+ shape, n_feat = f"-1, {plan.in_shape[1]}, 1", plan.in_shape[1]
422
+ else:
423
+ shape, n_feat = f"-1, 1, {plan.in_shape[1]}", plan.in_shape[1]
424
+ answer = ("out[:, 0].tolist() # 예측값 (원래 단위)" if task == "regression"
425
+ else "out.tolist() # 다음 값들 (원래 단위)" if task == "forecast"
426
+ else "((out - x.reshape(len(x), -1)) ** 2).mean(1).tolist() # 이상 점수 (클수록 이상)" if task == "anomaly"
427
+ else f'[[str(info["classes"][k]) for k in row] for row in out.reshape(len(x), {seq["n_cls"]}, -1).argmax(1).tolist()] # 시점마다 상태' if seq
428
+ else ('[{h["name"]: (h["classes"][int(r[h["start"]:h["start"] + h["size"]].argmax())] if h["kind"] == "class" '
429
+ 'else float(r[h["start"]])) for h in HEADS} for r in out.numpy()] # 정답마다') if task == "multi"
430
+ else '[str(info["classes"][i]) for i in out.argmax(1)] # 클래스 이름')
431
+ lines += [
432
+ f'def load_trained(path="{weights_file}"):',
433
+ ' """BlockLearning에서 학습한 모델과 정규화 값을 불러옴 → (model, info)."""',
434
+ " z = np.load(path)",
435
+ " model = StudioModel()",
436
+ ' model.load_state_dict({k: torch.from_numpy(z[k]) for k in z.files if not k.startswith("_")})',
437
+ ' info = {k[1:]: z[k] for k in z.files if k.startswith("_")} # mean, std, classes',
438
+ " return model.eval(), info",
439
+ "", "",
440
+ "def predict(model, info, rows):",
441
+ f' """원래 값 행들 (샘플 수, {n_feat}: 학습 CSV와 같은 열 순서, 정답 열 빼고) → 예측. BlockLearning과 같은 정규화."""',
442
+ ' x = (np.asarray(rows, dtype=np.float32) - info["mean"]) / info["std"]',
443
+ f" x = torch.as_tensor(x.reshape({shape}), dtype=torch.float32)",
444
+ " with torch.no_grad():",
445
+ " out = model(x)",
446
+ f" return {answer}",
447
+ "", "",
448
+ 'if __name__ == "__main__":',
449
+ " model, info = load_trained()",
450
+ f" rows = np.zeros((2, {n_feat}), dtype=np.float32) # ← 여기에 내 데이터 (원래 값, 한 행 = 샘플 하나)",
451
+ " print(predict(model, info, rows))",
452
+ "",
453
+ ]
454
+ return "\n".join(lines)
455
+ lines += ['if __name__ == "__main__":', " model = StudioModel().eval()",
456
+ f" x = torch.randn({ex_shape})", " with torch.no_grad():",
457
+ f" print(model(x).shape) # torch.Size([4, {plan.n_out}])", ""]
458
+ return "\n".join(lines)
459
+
460
+
461
+ def _y_doc(task: str) -> str:
462
+ return {"regression": "정답 값", "forecast": "다음 값들 (샘플, 예측 길이)", "anomaly": "X를 펼친 것 (샘플, 값 수) — 정상만 넣으세요",
463
+ "multi": "정답 표 (샘플, 정답 수): 분류 정답은 클래스 번호, 값 정답은 숫자",
464
+ "segmentation": "시점마다 상태 번호 (샘플, 길이)"}.get(task, "정답 클래스 번호")
465
+
466
+
467
+ def _heads_code(heads: list) -> list:
468
+ """정답 여러 개: 출력 한 줄에서 정답마다의 칸 (start·size)."""
469
+ rows = [f" {{'name': {h['name']!r}, 'kind': {h['kind']!r}, 'classes': {h['classes']!r}, 'start': {h['start']}, 'size': {h['size']}}},"
470
+ for h in heads]
471
+ return ["HEADS = [ # 정답마다 출력 칸: 분류는 클래스 점수 size개, 값은 1개"] + rows + ["]", ""]
472
+
473
+
474
+ def _torch_loss_code(spec: list, task: str, K: int, cw, heads: Optional[list] = None) -> list:
475
+ """조립한 손실 → studio_loss(out, y, model) 코드 (losses.build와 같은 식). heads: 정답 여러 개의 머리."""
476
+ from blocklearning import losses
477
+ seg = task == "segmentation"
478
+ col = {h["name"]: (j, h) for j, h in enumerate(heads or [])}
479
+ out = _heads_code(heads) if heads else []
480
+ if isinstance(cw, dict) and cw:
481
+ out += ["CLASS_WEIGHTS = { # 정답마다 드문 클래스를 무겁게"] + [
482
+ f" {k!r}: torch.tensor({[round(float(v), 6) for v in w]})," for k, w in cw.items()] + ["}", ""]
483
+ elif cw:
484
+ out += [f"CLASS_WEIGHTS = torch.tensor({[round(float(v), 6) for v in cw]}) # 드문 클래스를 무겁게", ""]
485
+ out += [
486
+ "def studio_loss(out, y, model):",
487
+ f' """손실 = {" + ".join(losses.label(t) for t in spec)} (BlockLearning에서 조립한 것)."""',
488
+ " total = 0"]
489
+ for t in spec:
490
+ n, w = t["term"], t["w"]
491
+ O, Y, KK, CW = "out", "y", K, "CLASS_WEIGHTS"
492
+ if t.get("head") is not None and n not in ("l2", "l1"):
493
+ j, h = col[t["head"]]
494
+ s, e = h["start"], h["start"] + h["size"]
495
+ if h["kind"] == "class":
496
+ out.append(f" o, yh = out[:, {s}:{e}], y[:, {j}].long() # 정답 '{h['name']}'")
497
+ KK = h["size"]
498
+ else:
499
+ out.append(f" o, yh = out[:, {s}], y[:, {j}] # 정답 '{h['name']}'")
500
+ O, Y, CW = "o", "yh", f"CLASS_WEIGHTS[{h['name']!r}]"
501
+ if n in ("ce", "focal"):
502
+ out.append(f" logp = F.log_softmax({O}.reshape(len({Y}), {KK}, -1), 1).transpose(1, 2).reshape(-1, {KK}); yt = {Y}.reshape(-1)"
503
+ if seg else f" logp, yt = F.log_softmax({O}, 1), {Y}")
504
+ if n == "ce":
505
+ sm = t.get("smooth", 0.0)
506
+ out += [f" q = F.one_hot(yt, {KK}).float() * {1 - sm} + {sm / KK}", " per = -(q * logp).sum(1)"]
507
+ else:
508
+ out += [" lp = logp.gather(1, yt[:, None])[:, 0]", f" per = -((1 - lp.exp()).clamp_min(0) ** {t['gamma']}) * lp"]
509
+ if t.get("balance") and cw:
510
+ out += [f" cw = {CW}.to(out.device)[yt]", " v = (per * cw).sum() / cw.sum().clamp_min(1e-12)"]
511
+ else:
512
+ out.append(" v = per.mean()")
513
+ elif n == "dice":
514
+ out += [f" p = F.softmax({O}.reshape(len({Y}), {KK}, -1), 1)", f" oh = F.one_hot({Y}, {KK}).permute(0, 2, 1).float()",
515
+ " v = (1 - (2 * (p * oh).sum((0, 2)) + 1) / (p.sum((0, 2)) + oh.sum((0, 2)) + 1)).mean()"]
516
+ elif n == "mse":
517
+ out.append(f" v = (({O} - {Y}) ** 2).mean()")
518
+ elif n == "mae":
519
+ out.append(f" v = ({O} - {Y}).abs().mean()")
520
+ elif n == "huber":
521
+ d = t["delta"]
522
+ out += [f" e = ({O} - {Y}).abs()", f" v = torch.where(e < {d}, 0.5 * e * e, {d} * (e - {0.5 * d})).mean()"]
523
+ elif n == "act_l1":
524
+ out.append(f" v = model.acts[{t['node']!r}].abs().mean()")
525
+ elif n in ("l2", "l1"):
526
+ f = "(p * p).sum()" if n == "l2" else "p.abs().sum()"
527
+ out.append(f" v = sum({f} for p in model.parameters() if p.requires_grad)")
528
+ else:
529
+ continue
530
+ out.append(f" total = total + {w} * v # {losses.label(t)}")
531
+ return out + [" return total", "", ""]
532
+
533
+
534
+ def _torch_det(head: dict, tr: dict, weights_file: Optional[str], plan: Plan) -> list:
535
+ """탐지: 손실(YOLO 첫 버전식, BlockLearning과 같음)·상자 풀기·학습·예측 코드."""
536
+ from blocklearning import detect
537
+ G, A = head["grid"], head["per_cell"]
538
+ H, W = plan.in_shape[1], plan.in_shape[2]
539
+ out = [
540
+ f"GRID, PER_CELL = {G}, {A} # 격자 {G}×{G}, 칸마다 값 {A}개",
541
+ "", "",
542
+ "def det_loss(out, target):",
543
+ ' """있음(BCE, 없는 칸은 무게 %s) + 사물 칸의 위치·크기 제곱 오차 × %s + 클래스 교차 엔트로피, 그림 수로 나눔."""'
544
+ % (detect.LAMBDA_NOOBJ, detect.LAMBDA_COORD),
545
+ " N = out.shape[0]",
546
+ " o, t = out.reshape(N, PER_CELL, GRID, GRID), target.reshape(N, PER_CELL, GRID, GRID)",
547
+ " pos = t[:, 0]",
548
+ " bce = F.binary_cross_entropy_with_logits(o[:, 0], pos, reduction=\"none\")",
549
+ f" loss = (bce * (pos + {detect.LAMBDA_NOOBJ} * (1 - pos))).sum()",
550
+ f" loss = loss + {detect.LAMBDA_COORD} * (((torch.sigmoid(o[:, 1:5]) - t[:, 1:5]) ** 2).sum(1) * pos).sum()",
551
+ " if PER_CELL > 6:",
552
+ " loss = loss + (-(t[:, 5:] * F.log_softmax(o[:, 5:], 1)).sum(1) * pos).sum()",
553
+ " return loss / N",
554
+ "", "",
555
+ f"def decode(out_row, score_min={detect.SHOW_SCORE}, nms_iou={detect.NMS_IOU}):",
556
+ ' """출력 한 줄 → 찾은 상자 [(클래스 번호, 점수, x, y, w, h)] (0–1 비율, 왼쪽 위 기준). 점수 = 있음 × 클래스 확률."""',
557
+ " o = torch.as_tensor(out_row, dtype=torch.float32).reshape(PER_CELL, GRID, GRID)",
558
+ " obj = torch.sigmoid(o[0])",
559
+ " prob = torch.softmax(o[5:], 0) if PER_CELL > 6 else torch.ones(1, GRID, GRID)",
560
+ " p, k = prob.max(0)",
561
+ " score = obj * p",
562
+ " cand = []",
563
+ " for gy, gx in (score >= score_min).nonzero().tolist():",
564
+ " cx, cy = (gx + torch.sigmoid(o[1, gy, gx]).item()) / GRID, (gy + torch.sigmoid(o[2, gy, gx]).item()) / GRID",
565
+ " w, h = torch.sigmoid(o[3, gy, gx]).item() ** 2, torch.sigmoid(o[4, gy, gx]).item() ** 2",
566
+ " x0, y0, x1, y1 = max(0.0, cx - w / 2), max(0.0, cy - h / 2), min(1.0, cx + w / 2), min(1.0, cy + h / 2)",
567
+ " cand.append((int(k[gy, gx]), float(score[gy, gx]), x0, y0, x1 - x0, y1 - y0))",
568
+ " keep = []",
569
+ " for c in sorted(cand, key=lambda b: -b[1]): # 같은 클래스끼리 많이 겹치면 점수 높은 것만",
570
+ " if all(c[0] != q[0] or _iou(c[2:], q[2:]) <= nms_iou for q in keep):",
571
+ " keep.append(c)",
572
+ " return keep",
573
+ "", "",
574
+ "def _iou(a, b):",
575
+ " x0, y0, x1, y1 = max(a[0], b[0]), max(a[1], b[1]), min(a[0] + a[2], b[0] + b[2]), min(a[1] + a[3], b[1] + b[3])",
576
+ " inter = max(0.0, x1 - x0) * max(0.0, y1 - y0)",
577
+ " union = a[2] * a[3] + b[2] * b[3] - inter",
578
+ " return inter / union if union > 0 else 0.0",
579
+ "", "",
580
+ f"def train(model, X, Y, epochs={tr['epochs']}, lr={tr['lr']}, batch_size={tr['batch_size']}):",
581
+ ' """X: 위 입력 모양의 그림, Y: 그림마다 목표값 (샘플 수, %d). Adam으로 학습."""' % (G * G * A),
582
+ " X, Y = torch.as_tensor(X, dtype=torch.float32), torch.as_tensor(Y, dtype=torch.float32)",
583
+ " opt = torch.optim.Adam(model.parameters(), lr=lr)",
584
+ " for epoch in range(epochs):",
585
+ " model.train()",
586
+ " for idx in torch.randperm(len(X)).split(batch_size):",
587
+ " opt.zero_grad()",
588
+ " loss = det_loss(model(X[idx]), Y[idx])",
589
+ " loss.backward()",
590
+ " opt.step()",
591
+ ' print(f"epoch {epoch + 1}: loss {loss.item():.4f}")',
592
+ " return model.eval()",
593
+ "", "",
594
+ ]
595
+ if weights_file:
596
+ out += [
597
+ f'def load_trained(path="{weights_file}"):',
598
+ ' """BlockLearning에서 학습한 모델과 정규화 값을 불러옴 → (model, info)."""',
599
+ " z = np.load(path)",
600
+ " model = StudioModel()",
601
+ ' model.load_state_dict({k: torch.from_numpy(z[k]) for k in z.files if not k.startswith("_")})',
602
+ ' info = {k[1:]: z[k] for k in z.files if k.startswith("_")} # mean, std, classes',
603
+ " return model.eval(), info",
604
+ "", "",
605
+ "def predict(model, info, images):",
606
+ f' """흑백 그림들 (샘플 수, {H}, {W}) 픽셀 0–1 → 그림마다 찾은 상자 [(클래스 이름, 점수, x, y, w, h)]."""',
607
+ ' x = (np.asarray(images, dtype=np.float32).reshape(len(images), -1) - info["mean"]) / info["std"]',
608
+ f" x = torch.as_tensor(x.reshape(-1, 1, {H}, {W}), dtype=torch.float32)",
609
+ " with torch.no_grad():",
610
+ " out = model(x)",
611
+ ' return [[(str(info["classes"][b[0]]),) + b[1:] for b in decode(row)] for row in out]',
612
+ "", "",
613
+ 'if __name__ == "__main__":',
614
+ " model, info = load_trained()",
615
+ f" images = np.zeros((2, {H}, {W}), dtype=np.float32) # ← 여기에 내 그림 (흑백 {H}×{W}, 0–1)",
616
+ " print(predict(model, info, images))",
617
+ "",
618
+ ]
619
+ return out
620
+ return out + ['if __name__ == "__main__":', " model = StudioModel().eval()",
621
+ f" x = torch.randn(4, 1, {H}, {W})", " with torch.no_grad():",
622
+ " print([len(decode(row)) for row in model(x)]) # 그림마다 찾은 상자 수 (학습 전이라 무작위)", ""]
623
+
624
+
625
+ def code_state(state: dict, graph: dict, length: int, n_out: int, image: tuple = None) -> dict:
626
+ """studio 가중치(GraphNet state_dict 이름: mods.m_<id>...) → 생성한 PyTorch 코드(StudioModel)의 이름. 값은 그대로."""
627
+ plan = make_plan(graph, length, n_out, image)
628
+ pairs = sorted(_key_map(plan), key=lambda p: -len(p[0]))
629
+ out = {}
630
+ for k, v in state.items():
631
+ for src, dst in pairs:
632
+ if k.startswith(src + "."):
633
+ out[dst + k[len(src):]] = v
634
+ break
635
+ else:
636
+ raise KeyError(f"가중치 {k}를 코드 이름으로 옮길 수 없음")
637
+ return out
638
+
639
+
640
+ def torch_state_dict(net, graph: dict, length: int, n_out: int, image: tuple = None) -> dict:
641
+ """studio 모델(GraphNet)의 가중치 → 생성한 PyTorch 코드(StudioModel)의 이름으로."""
642
+ return {k: v.detach().clone() for k, v in code_state(net.state_dict(), graph, length, n_out, image).items()}
643
+
644
+
645
+ def save_npz(state: dict, file, data=None) -> None:
646
+ """가중치 dict(이름 → 배열·텐서) → .npz (numpy만 있으면 읽음, torch 형식에 기대지 않음).
647
+ data(Dataset)를 주면 정규화 값(_mean·_std)과 클래스 이름(_classes)도 함께 — 생성 코드의 predict가 씀."""
648
+ import numpy as np
649
+ arrays = {k: (v.detach().cpu().numpy() if hasattr(v, "detach") else np.asarray(v)) for k, v in state.items()}
650
+ if data is not None:
651
+ arrays["_mean"] = np.asarray(data.mean, dtype=np.float32)
652
+ arrays["_std"] = np.asarray(data.std, dtype=np.float32)
653
+ if data.task in ("classification", "detection"):
654
+ arrays["_classes"] = np.asarray([str(c) for c in data.classes])
655
+ np.savez(file, **arrays)
656
+
657
+
658
+ def param_specs(step: Step) -> list:
659
+ """층 하나의 가중치 [(studio 이름, 모양, 종류)]. 종류: weight(학습) · buffer(BatchNorm 통계) · count · frozen(사전학습, 고정).
660
+ 이름·모양은 PyTorch(GraphNet)와 같다 — 웹 엔진(TF.js)이 이대로 만들어 PyTorch로 그대로 내보낸다."""
661
+ b, t, k, ins = step.cfg, step.type, step.key, step.in_shape
662
+ w = lambda name, *shape: (f"{k}.{name}", list(shape), "weight")
663
+ if t == "conv":
664
+ return [w("weight", b["channels"], ins[0] // b.get("groups", 1), b["kernel"]), w("bias", b["channels"])]
665
+ if t == "conv2d":
666
+ return [w("weight", b["channels"], ins[0] // b.get("groups", 1), b["kernel"], b["kernel"]), w("bias", b["channels"])]
667
+ if t == "bn":
668
+ C = ins[0]
669
+ return [w("weight", C), w("bias", C), (f"{k}.running_mean", [C], "buffer"), (f"{k}.running_var", [C], "buffer"),
670
+ (f"{k}.num_batches_tracked", [], "count")]
671
+ if t == "output" and b.get("head") == "grid":
672
+ return [(f"{k}.0.weight", [b["per_cell"], ins[0], 1, 1], "weight"), (f"{k}.0.bias", [b["per_cell"]], "weight")]
673
+ if t == "output" and b.get("head") == "seq":
674
+ return [(f"{k}.0.weight", [b["n_cls"], ins[0], 1], "weight"), (f"{k}.0.bias", [b["n_cls"]], "weight")]
675
+ if t == "output" and b.get("head") == "distance": # 정상과의 거리: 정상 샘플에서 계산해 넣는 값
676
+ C = _prod(ins)
677
+ K = X.dist_k(C)
678
+ return [(f"{k}.mean", [C], "buffer"), (f"{k}.basis", [K, C], "buffer"), (f"{k}.inv_var", [K], "buffer"),
679
+ (f"{k}.inv_rest", [1], "buffer")]
680
+ if t in ("dense", "output"):
681
+ units = step.out_shape[0]
682
+ kk = k + (".1" if len(ins) >= 2 else "")
683
+ return [(f"{kk}.weight", [units, _prod(ins)], "weight"), (f"{kk}.bias", [units], "weight")]
684
+ if t in RNN_TYPES:
685
+ G, H = {"lstm": 4, "gru": 3, "simple_rnn": 1}[t], b["hidden"]
686
+ out = []
687
+ dirs = ("", "_reverse") if b.get("bidirectional") else ("",)
688
+ for layer in range(b.get("layers", 1)):
689
+ inp = ins[0] if layer == 0 else H * len(dirs)
690
+ for sfx in dirs:
691
+ out += [(f"{k}.rnn.weight_ih_l{layer}{sfx}", [G * H, inp], "weight"), (f"{k}.rnn.weight_hh_l{layer}{sfx}", [G * H, H], "weight"),
692
+ (f"{k}.rnn.bias_ih_l{layer}{sfx}", [G * H], "weight"), (f"{k}.rnn.bias_hh_l{layer}{sfx}", [G * H], "weight")]
693
+ return out
694
+ if t in X.EXTRA_TYPES:
695
+ return X.params(t, b, ins, step.out_shape, k, step.in_shapes[1] if len(step.in_shapes) > 1 else None)
696
+ if t == "se":
697
+ C = ins[0]
698
+ h = max(1, C // b.get("ratio", 4))
699
+ return [w("fc1.weight", h, C), w("fc1.bias", h), w("fc2.weight", C, h), w("fc2.bias", C)]
700
+ return []
701
+
702
+
703
+ def plan_dict(graph: dict, length: int, n_out: int, image: tuple = None) -> dict:
704
+ """웹 엔진용 계획 (JSON): 층 순서·설정·모양·가중치 이름과 모양, 학습 파라미터 수."""
705
+ plan = make_plan(graph, length, n_out, image)
706
+ steps = [{"name": s.name, "type": s.type, "cfg": s.cfg, "inputs": s.inputs, "in_shape": list(s.in_shape),
707
+ "in_shapes": [list(x) for x in s.in_shapes], "out_shape": list(s.out_shape), "node": s.node, "key": s.key,
708
+ "params": [list(p) for p in param_specs(s)]} for s in plan.steps]
709
+ n_params = sum(_prod(p[1]) for st in steps for p in st["params"] if p[2] == "weight")
710
+ n_frozen = sum(_prod(p[1]) for st in steps for p in st["params"] if p[2] == "frozen")
711
+ return {"kind": plan.kind, "in_shape": list(plan.in_shape), "n_out": plan.n_out, "out": plan.out, "steps": steps,
712
+ "aliases": plan.aliases, "params": n_params, "frozen": n_frozen}
713
+
714
+
715
+ # ---------------------------------------------------------------- TensorFlow Keras
716
+
717
+ _KERAS_ACT = {"selu": 'layers.Activation("selu"', "relu6": "layers.ReLU(6.0", "softmax": "layers.Softmax(axis=-1",
718
+ "hardswish": "layers.Lambda(lambda t: t * tf.nn.relu6(t + 3.0) / 6.0",
719
+ "hardsigmoid": "layers.Lambda(lambda t: tf.nn.relu6(t + 3.0) / 6.0",
720
+ "relu": 'layers.Activation("relu"', "gelu": 'layers.Activation(gelu', "silu": 'layers.Activation("swish"',
721
+ "elu": 'layers.Activation("elu"', "softplus": 'layers.Activation("softplus"',
722
+ "sigmoid": 'layers.Activation("sigmoid"', "tanh": 'layers.Activation("tanh"',
723
+ "mish": 'layers.Activation(mish', "leaky_relu": "layers.LeakyReLU(0.01"}
724
+
725
+
726
+ def _keras_shape(shape: tuple) -> tuple:
727
+ """studio 모양(채널 먼저) → Keras 모양(채널 마지막)."""
728
+ return tuple(shape[1:]) + (shape[0],) if len(shape) >= 2 else tuple(shape)
729
+
730
+
731
+ def _keras_lines(s: Step, n_out: int) -> list:
732
+ b, t, n = s.cfg, s.type, s.name
733
+ a = s.inputs[0] if s.inputs else ""
734
+ nm = f'name="{n}"'
735
+ if t in ("conv", "conv2d"):
736
+ cls = "Conv1D" if t == "conv" else "Conv2D"
737
+ stride, dil = b.get("stride", 1), b.get("dilation", 1)
738
+ both = stride != 1 and dil != 1 # Keras는 strides와 dilation_rate를 함께 못 받음 → stride 1로 계산 뒤 건너뛰어 뽑음
739
+ opts = "".join(f", {k}={v}" for k, v, dflt in (("strides", 1 if both else stride, 1), ("dilation_rate", dil, 1),
740
+ ("groups", b.get("groups", 1), 1)) if v != dflt)
741
+ pad = "valid" if b.get("padding", "same") == "valid" else "same"
742
+ if b.get("padding") == "causal":
743
+ pad = "causal"
744
+ if both:
745
+ return [f'{n}_full = layers.{cls}({b["channels"]}, {b["kernel"]}, padding="{pad}"{opts}, name="{n}_full")({a})',
746
+ f"{n} = layers.Lambda(lambda t: t[:, ::{stride}, :], {nm})({n}_full)"]
747
+ return [f'{n} = layers.{cls}({b["channels"]}, {b["kernel"]}, padding="{pad}"{opts}, {nm})({a})']
748
+ if t == "pool":
749
+ return [f"{n} = layers.AveragePooling1D({b['size']}, {nm})({a})"]
750
+ if t == "pool2d":
751
+ return [f"{n} = layers.AveragePooling2D(2, {nm})({a})"]
752
+ if t == "global_avg":
753
+ return [f"{n} = layers.GlobalAveragePooling1D({nm})({a})"]
754
+ if t == "global_avg2d":
755
+ return [f"{n} = layers.GlobalAveragePooling2D({nm})({a})"]
756
+ if t == "last_step":
757
+ return [f"{n} = layers.Lambda(lambda t: t[:, -1, :], {nm})({a})"]
758
+ if t == "bn":
759
+ return [f"{n} = layers.BatchNormalization(momentum=0.9, epsilon=1e-5, {nm})({a})"]
760
+ if t == "act":
761
+ return [f"{n} = {_KERAS_ACT[b['kind']]}, {nm})({a})"]
762
+ if t == "dropout":
763
+ return [f"{n} = layers.Dropout({float(b.get('rate', 0.5))}, {nm})({a})"]
764
+ if t == "flatten":
765
+ return [f"{n} = layers.Flatten({nm})({a})"]
766
+ if t == "output" and b.get("head") == "seq": # 시점마다 1×1 필터, 상태를 앞으로 옮겨 펼침 (PyTorch와 같은 순서)
767
+ return [f'{n}_steps = layers.Conv1D({b["n_cls"]}, 1, name="{n}_steps")({a})',
768
+ f'{n}_first = layers.Permute((2, 1), name="{n}_first")({n}_steps)',
769
+ f"{n} = layers.Flatten({nm})({n}_first)"]
770
+ if t == "output" and b.get("head") == "grid": # 칸마다 1×1 필터, 채널을 앞으로 옮겨 펼침 (PyTorch와 같은 순서)
771
+ return [f'{n}_cells = layers.Conv2D({b["per_cell"]}, 1, name="{n}_cells")({a})',
772
+ f'{n}_first = layers.Permute((3, 1, 2), name="{n}_first")({n}_cells)',
773
+ f"{n} = layers.Flatten({nm})({n}_first)"]
774
+ if t in ("dense", "output"):
775
+ units = n_out if t == "output" else b["units"]
776
+ out = []
777
+ if len(s.in_shape) >= 2:
778
+ out.append(f'{n}_flat = layers.Flatten(name="{n}_flat")({a})')
779
+ a = f"{n}_flat"
780
+ return out + [f"{n} = layers.Dense({units}, {nm})({a})"]
781
+ if t in RNN_TYPES:
782
+ cls = {"lstm": "LSTM", "gru": "GRU", "simple_rnn": "SimpleRNN"}[t]
783
+ k = b.get("layers", 1)
784
+ out, cur = [], a
785
+ for i in range(k):
786
+ last = i == k - 1
787
+ var = n if last else f"{n}_l{i}"
788
+ seq = "" if last and not b.get("return_sequences") else ", return_sequences=True"
789
+ layer = f'layers.{cls}({b["hidden"]}{seq})'
790
+ if b.get("bidirectional"):
791
+ out.append(f'{var} = layers.Bidirectional({layer}, name="{var}")({cur})')
792
+ else:
793
+ out.append(f'{var} = layers.{cls}({b["hidden"]}{seq}, name="{var}")({cur})')
794
+ cur = var
795
+ return out
796
+ if t in X.EXTRA_TYPES or t in X.NEW_MERGES:
797
+ return _keras_extra(s)
798
+ if t == "se":
799
+ C, h = s.in_shape[0], max(1, s.in_shape[0] // b.get("ratio", 4))
800
+ act = b.get("act", "relu")
801
+ act_kw = {"relu": '"relu"', "sigmoid": '"sigmoid"', "tanh": '"tanh"'}.get(act, '"relu"')
802
+ two = len(s.in_shape) == 3
803
+ return [f'{n}_s = layers.GlobalAveragePooling{"2" if two else "1"}D(name="{n}_squeeze")({a})',
804
+ f'{n}_s = layers.Dense({h}, activation={act_kw}, name="{n}_fc1")({n}_s)',
805
+ f'{n}_s = layers.Dense({C}, activation="sigmoid", name="{n}_fc2")({n}_s)',
806
+ f'{n} = layers.Multiply({nm})([{a}, layers.Reshape(({"1, 1" if two else "1"}, {C}), name="{n}_reshape")({n}_s)])']
807
+ if t == "add":
808
+ return [f"{n} = layers.Add({nm})([{', '.join(s.inputs)}])"]
809
+ if t == "concat":
810
+ return [f"{n} = layers.Concatenate(axis=-1, {nm})([{', '.join(s.inputs)}])"]
811
+ raise ValueError(f"코드로 바꿀 수 없는 층: {t}")
812
+
813
+
814
+ KERAS_UNSUPPORTED = ("mnv3s", "adaptive_pool", "attn_pool", "rmsnorm", "eca", "cbam", "spatial_attn", "linear_attn", "nonlocal",
815
+ "cross_attn", "pos_enc", "cls_token", "embedding", "spectrogram", "rand_scale", "rand_stretch", "drop_path")
816
+
817
+
818
+ def keras_unsupported(graph: dict, length: int, n_out: int, image: tuple = None) -> list:
819
+ """Keras 코드로 바꿀 수 없는 블록 이름들 (PyTorch 코드는 모두 됨)."""
820
+ plan = make_plan(graph, length, n_out, image)
821
+ bad = []
822
+ for s in plan.steps:
823
+ rank = len(s.in_shape)
824
+ if s.type in KERAS_UNSUPPORTED or (s.type == "mha" and s.cfg.get("pos") == "rope") \
825
+ or (s.type == "output" and s.cfg.get("head") == "distance") \
826
+ or (s.type == "upsample" and rank == 2 and s.cfg.get("mode") == "linear") \
827
+ or (s.type in ("pixel_shuffle", "rand_flip", "rand_shift") and rank == 2):
828
+ bad.append("출력 '정상과의 거리'" if s.type == "output" else X.name_of(s.type))
829
+ return sorted(set(bad))
830
+
831
+
832
+ def _keras_extra(s: Step) -> list:
833
+ """추가 블록 → Keras 줄 (채널이 마지막: 줄 (N, L, C), 그림 (N, H, W, C))."""
834
+ b, t, n = s.cfg, s.type, s.name
835
+ a = s.inputs[0] if s.inputs else ""
836
+ nm = f'name="{n}"'
837
+ o = lambda k: X.opt(b, k)
838
+ rank = len(s.in_shape)
839
+ d = "2D" if rank == 3 else "1D"
840
+ C = s.in_shape[0]
841
+ if t in ("multiply", "average", "maximum"):
842
+ return [f"{n} = layers.{t.capitalize()}({nm})([{', '.join(s.inputs)}])"]
843
+ if t == "glu":
844
+ g = "tf.sigmoid" if o("gate") == "sigmoid" else "tf.nn.silu"
845
+ return [f'{n}_h = layers.Dense({2 * o("units")}, name="{n}_proj")({a})',
846
+ f"{n} = layers.Lambda(lambda t: t[..., :{o('units')}] * {g}(t[..., {o('units')}:]), {nm})({n}_h)"]
847
+ if t in ("dw_conv", "dw_conv2d"):
848
+ return [f'{n} = layers.DepthwiseConv{"2D" if t == "dw_conv2d" else "1D"}({o("kernel")}, depth_multiplier={o("multiplier")}, padding="same", {nm})({a})']
849
+ if t in ("sep_conv", "sep_conv2d"):
850
+ return [f'{n} = layers.SeparableConv{"2D" if t == "sep_conv2d" else "1D"}({o("channels")}, {o("kernel")}, padding="same", {nm})({a})']
851
+ if t in ("max_pool", "max_pool2d"):
852
+ return [f"{n} = layers.MaxPooling{d}({o('size')}, {nm})({a})"]
853
+ if t in ("global_max", "global_max2d"):
854
+ return [f"{n} = layers.GlobalMaxPooling{d}({nm})({a})"]
855
+ if t == "first_step":
856
+ return [f"{n} = layers.Lambda(lambda t: t[:, 0, :], {nm})({a})"]
857
+ if t == "upsample":
858
+ if rank == 3:
859
+ mode = "bilinear" if o("mode") == "linear" else "nearest"
860
+ return [f'{n} = layers.UpSampling2D(2, interpolation="{mode}", {nm})({a})']
861
+ return [f"{n} = layers.UpSampling1D(2, {nm})({a})"]
862
+ if t == "pixel_shuffle":
863
+ return [f"{n} = layers.Lambda(lambda t: tf.nn.depth_to_space(t, 2), {nm})({a})"]
864
+ if t in ("conv_t", "conv_t2d"):
865
+ return [f'{n} = layers.Conv{d}Transpose({o("channels")}, {o("kernel")}, strides={o("stride")}, padding="same", {nm})({a})']
866
+ if t == "mha":
867
+ h = o("heads")
868
+ causal = ", use_causal_mask=True" if o("causal") else ""
869
+ if rank == 3:
870
+ H, W = s.in_shape[1], s.in_shape[2]
871
+ return [f'{n}_s = layers.Reshape(({H * W}, {C}), name="{n}_seq")({a})',
872
+ f'{n}_s = layers.MultiHeadAttention({h}, {C // h}, name="{n}_mha")({n}_s, {n}_s{causal})',
873
+ f"{n} = layers.Reshape(({H}, {W}, {C}), {nm})({n}_s)"]
874
+ return [f"{n} = layers.MultiHeadAttention({h}, {C // h}, {nm})({a}, {a}{causal})"]
875
+ if t == "patch_embed":
876
+ p = o("patch")
877
+ return [f'{n}_c = layers.Conv2D({o("dim")}, {p}, strides={p}, name="{n}_proj")({a})',
878
+ f"{n} = layers.Reshape((-1, {o('dim')}), {nm})({n}_c)"]
879
+ if t == "layernorm":
880
+ return [f"{n} = layers.LayerNormalization(axis=-1, epsilon=1e-5, {nm})({a})"]
881
+ if t == "groupnorm":
882
+ return [f"{n} = layers.GroupNormalization({o('groups')}, axis=-1, epsilon=1e-5, {nm})({a})"]
883
+ if t == "instancenorm":
884
+ return [f"{n} = layers.GroupNormalization({C}, axis=-1, epsilon=1e-5, {nm})({a})"]
885
+ if t == "prelu":
886
+ axes = list(range(1, rank + 1))
887
+ return [f"{n} = layers.PReLU(shared_axes={axes}, {nm})({a})"]
888
+ if t == "spatial_dropout":
889
+ return [f"{n} = layers.SpatialDropout{d}({float(o('rate'))}, {nm})({a})"]
890
+ if t == "gaussian_noise":
891
+ return [f"{n} = layers.GaussianNoise({float(o('std'))}, {nm})({a})"]
892
+ if t == "slice":
893
+ return [f"{n} = layers.Lambda(lambda t: t[..., {o('start')}:{o('start') + o('count')}], {nm})({a})"]
894
+ if t == "reshape":
895
+ c = o("channels")
896
+ first = "(0, 2, 1)" if rank == 2 else "(0, 3, 1, 2)" if rank == 3 else None
897
+ pre = f"tf.transpose(t, {first})" if first else "t"
898
+ return [f"{n} = layers.Lambda(lambda t: tf.transpose(tf.reshape({pre}, (-1, {c}, {s.out_shape[1]})), (0, 2, 1)), {nm})({a})"]
899
+ if t == "permute":
900
+ return [f"{n} = layers.Permute({'(2, 1)' if rank == 2 else '(2, 1, 3)'}, {nm})({a})"]
901
+ if t == "to_seq":
902
+ return [f"{n} = layers.Reshape(({s.in_shape[1] * s.in_shape[2]}, {C}), {nm})({a})"]
903
+ if t == "crop":
904
+ return [f"{n} = layers.Cropping{d}({o('amount')}, {nm})({a})"]
905
+ if t == "pad":
906
+ return [f"{n} = layers.ZeroPadding{d}({o('amount')}, {nm})({a})"]
907
+ if t == "rand_flip":
908
+ mode = {"h": "horizontal", "v": "vertical", "hv": "horizontal_and_vertical"}[o("dir")]
909
+ return [f'{n} = layers.RandomFlip("{mode}", {nm})({a})']
910
+ if t == "rand_rotate":
911
+ return [f"{n} = layers.RandomRotation({o('degrees') / 360:.6g}, fill_mode='constant', {nm})({a})"]
912
+ if t == "rand_zoom":
913
+ return [f"{n} = layers.RandomZoom({float(o('frac'))}, fill_mode='constant', {nm})({a})"]
914
+ if t == "rand_shift":
915
+ return [f"{n} = layers.RandomTranslation({float(o('frac'))}, {float(o('frac'))}, fill_mode='constant', {nm})({a})"]
916
+ raise ValueError(f"TensorFlow 코드로 바꿀 수 없는 블록: {X.name_of(t)} (PyTorch 코드를 쓰세요)")
917
+
918
+
919
+ def to_keras(graph: dict, length: int, n_out: int, image: tuple = None, data_info: Optional[dict] = None,
920
+ train: Optional[dict] = None) -> str:
921
+ """TensorFlow Keras 코드 (build_model 함수형 API + 학습 함수 + 실행 예). 채널이 마지막인 모양."""
922
+ plan = make_plan(graph, length, n_out, image)
923
+ bad = keras_unsupported(graph, length, n_out, image)
924
+ if bad:
925
+ raise ValueError(f"TensorFlow 코드로 바꿀 수 없는 블록: {', '.join(bad)} — PyTorch 코드로 내보내세요 (모든 블록이 됨)")
926
+ task = (data_info or {}).get("task", "classification")
927
+ tr = dict({"epochs": 30, "lr": 1e-3, "batch_size": 32}, **(train or {}))
928
+ if plan.kind == "rnn":
929
+ in_shape = (plan.in_shape[1], 1)
930
+ else:
931
+ in_shape = _keras_shape(plan.in_shape)
932
+ body = []
933
+ for s in plan.steps:
934
+ ls = _keras_lines(s, plan.n_out)
935
+ comment = f"# {_label(s)} → {_shape_text(_keras_shape(s.out_shape))}"
936
+ body += [f" {l}" for l in ls[:-1]] + [(f" {ls[-1]}", comment)]
937
+ width = min(84, max(len(x[0]) for x in body if isinstance(x, tuple)) + 2)
938
+ body = [x[0].ljust(width) + x[1] if isinstance(x, tuple) else x for x in body]
939
+ kinds = {s.cfg.get("kind") for s in plan.steps if s.type == "act"}
940
+ helpers = []
941
+ if "gelu" in kinds:
942
+ helpers += ["", "", "def gelu(t):", ' """GELU (PyTorch와 같은 정확한 식)."""', " return keras.activations.gelu(t, approximate=False)"]
943
+ if "mish" in kinds:
944
+ helpers += ["", "", "def mish(t):", " return t * tf.math.tanh(tf.math.softplus(t))"]
945
+ doc = _io_doc(plan, data_info, channels_last=True)
946
+ doc.append("가중치: BlockLearning에서 학습한 값은 들어 있지 않음 (TensorFlow에서 아래 train으로 새로 학습)")
947
+ head = next((s.cfg for s in plan.steps if s.type == "output" and s.cfg.get("head") == "grid"), None)
948
+ if head:
949
+ from blocklearning import detect
950
+ G, A = head["grid"], head["per_cell"]
951
+ helpers += ["", "", f"GRID, PER_CELL = {G}, {A}", "", "",
952
+ "def det_loss(target, out):",
953
+ ' """BlockLearning과 같은 탐지 손실 (YOLO 첫 버전식). 출력·목표값은 (값, 세로, 가로) 순서로 펼친 것."""',
954
+ " o, t = tf.reshape(out, (-1, PER_CELL, GRID, GRID)), tf.reshape(target, (-1, PER_CELL, GRID, GRID))",
955
+ " pos = t[:, 0]",
956
+ " bce = tf.nn.sigmoid_cross_entropy_with_logits(labels=pos, logits=o[:, 0])",
957
+ f" loss = tf.reduce_sum(bce * (pos + {detect.LAMBDA_NOOBJ} * (1 - pos)))",
958
+ f" loss += {detect.LAMBDA_COORD} * tf.reduce_sum(tf.reduce_sum((tf.sigmoid(o[:, 1:5]) - t[:, 1:5]) ** 2, 1) * pos)",
959
+ " if PER_CELL > 6:",
960
+ " loss += tf.reduce_sum(-tf.reduce_sum(t[:, 5:] * tf.nn.log_softmax(o[:, 5:], axis=1), 1) * pos)",
961
+ " return loss / tf.cast(tf.shape(out)[0], tf.float32)"]
962
+ loss, metric = "det_loss", "[]"
963
+ elif task == "multi" and (data_info or {}).get("heads"):
964
+ helpers += [""] + _heads_code(data_info["heads"]) + [
965
+ "def multi_loss(target, out):",
966
+ ' """정답마다: 분류는 교차 엔트로피, 값은 MSE (BlockLearning의 기본), 모두 더함."""',
967
+ " total = 0.0",
968
+ " for j, h in enumerate(HEADS):",
969
+ ' o = out[:, h["start"]:h["start"] + h["size"]]',
970
+ ' if h["kind"] == "class":',
971
+ " total += tf.reduce_mean(keras.losses.sparse_categorical_crossentropy(tf.cast(target[:, j], tf.int32), o, from_logits=True))",
972
+ " else:",
973
+ " total += tf.reduce_mean((o[:, 0] - target[:, j]) ** 2)",
974
+ " return total"]
975
+ loss, metric = "multi_loss", "[]"
976
+ elif task in ("regression", "forecast", "anomaly"):
977
+ loss, metric = '"mse"', '["mae"]'
978
+ elif any(s.type == "output" and s.cfg.get("head") == "seq" for s in plan.steps): # 구간 분할: 시점마다 교차 엔트로피
979
+ K = next(s.cfg for s in plan.steps if s.type == "output" and s.cfg.get("head") == "seq")["n_cls"]
980
+ helpers += ["", "", f"N_STATES = {K}", "", "",
981
+ "def seg_loss(target, out):",
982
+ ' """시점마다 교차 엔트로피 (BlockLearning과 같음). out: (상태 수 × 길이)를 상태가 먼저 펼친 것, target: (샘플, 길이) 상태 번호."""',
983
+ " o = tf.transpose(tf.reshape(out, (-1, N_STATES, tf.shape(target)[1])), (0, 2, 1))",
984
+ " return tf.reduce_mean(keras.losses.sparse_categorical_crossentropy(tf.cast(target, tf.int32), o, from_logits=True))"]
985
+ loss, metric = "seg_loss", "[]"
986
+ else:
987
+ loss, metric = "keras.losses.SparseCategoricalCrossentropy(from_logits=True)", '["accuracy"]'
988
+ lines = ['"""BlockLearning에서 만든 모델 (TensorFlow Keras).', ""] + doc + ['"""', "import tensorflow as tf",
989
+ "from tensorflow import keras",
990
+ "from tensorflow.keras import layers"]
991
+ lines += helpers
992
+ lines += ["", "", "def build_model():", f" x = keras.Input(shape={_shape_text(in_shape) if len(in_shape) > 1 else f'({in_shape[0]},)'})"]
993
+ lines += body
994
+ lines += [f' return keras.Model(x, {plan.out}, name="studio_model")', "", "",
995
+ f"def train(model, X, y, epochs={tr['epochs']}, lr={tr['lr']}, batch_size={tr['batch_size']}):",
996
+ f' """X: 위 입력 모양의 배열, y: {_y_doc(task)}. Adam으로 학습."""',
997
+ f" model.compile(optimizer=keras.optimizers.Adam(lr), loss={loss}, metrics={metric})",
998
+ " model.fit(X, y, epochs=epochs, batch_size=batch_size)",
999
+ " return model", "", "",
1000
+ 'if __name__ == "__main__":',
1001
+ " model = build_model()",
1002
+ " model.summary()", ""]
1003
+ return "\n".join(lines)
1004
+
1005
+
1006
+ def generate(framework: str, graph: dict, length: int, n_out: int, image: tuple = None, data_info: Optional[dict] = None,
1007
+ train: Optional[dict] = None, weights_file: Optional[str] = None) -> str:
1008
+ if framework == "pytorch":
1009
+ return to_pytorch(graph, length, n_out, image, data_info, train, weights_file)
1010
+ if framework == "tensorflow":
1011
+ return to_keras(graph, length, n_out, image, data_info, train)
1012
+ raise ValueError(f"framework는 {' 또는 '.join(FRAMEWORKS)}: {framework!r}")