keypadml 0.3.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 (57) hide show
  1. keypadml/__init__.py +20 -0
  2. keypadml/_runtime/desktop/kp/desktop/DesktopRun$1.class +0 -0
  3. keypadml/_runtime/desktop/kp/desktop/DesktopRun.class +0 -0
  4. keypadml/_runtime/desktop/kp/desktop/PhotoRun$1.class +0 -0
  5. keypadml/_runtime/desktop/kp/desktop/PhotoRun.class +0 -0
  6. keypadml/_runtime/icon.png +0 -0
  7. keypadml/_runtime/phone/kp/Bench$Listener.class +0 -0
  8. keypadml/_runtime/phone/kp/Bench.class +0 -0
  9. keypadml/_runtime/phone/kp/BenchMIDlet$1.class +0 -0
  10. keypadml/_runtime/phone/kp/BenchMIDlet$2.class +0 -0
  11. keypadml/_runtime/phone/kp/BenchMIDlet$3.class +0 -0
  12. keypadml/_runtime/phone/kp/BenchMIDlet.class +0 -0
  13. keypadml/_runtime/phone/kp/Camera.class +0 -0
  14. keypadml/_runtime/phone/kp/Card$1.class +0 -0
  15. keypadml/_runtime/phone/kp/Card.class +0 -0
  16. keypadml/_runtime/phone/kp/Inputs.class +0 -0
  17. keypadml/_runtime/phone/kp/Jpeg$Huffman.class +0 -0
  18. keypadml/_runtime/phone/kp/Jpeg.class +0 -0
  19. keypadml/_runtime/phone/kp/MathX.class +0 -0
  20. keypadml/_runtime/phone/kp/Net.class +0 -0
  21. keypadml/_runtime/phone/kp/Ops.class +0 -0
  22. keypadml/_runtime/phone/kp/Parts.class +0 -0
  23. keypadml/_runtime/phone/kp/Photo$Rows.class +0 -0
  24. keypadml/_runtime/phone/kp/Photo.class +0 -0
  25. keypadml/_runtime/phone/kp/ResultsCanvas.class +0 -0
  26. keypadml/_runtime/phone/kp/Saver.class +0 -0
  27. keypadml/_runtime/phone/kp/TryIt$1.class +0 -0
  28. keypadml/_runtime/phone/kp/TryIt$2.class +0 -0
  29. keypadml/_runtime/phone/kp/TryIt$3.class +0 -0
  30. keypadml/_runtime/phone/kp/TryIt$4.class +0 -0
  31. keypadml/_runtime/phone/kp/TryIt$5.class +0 -0
  32. keypadml/_runtime/phone/kp/TryIt$6.class +0 -0
  33. keypadml/_runtime/phone/kp/TryIt$7.class +0 -0
  34. keypadml/_runtime/phone/kp/TryIt$8.class +0 -0
  35. keypadml/_runtime/phone/kp/TryIt$Files.class +0 -0
  36. keypadml/_runtime/phone/kp/TryIt$Job.class +0 -0
  37. keypadml/_runtime/phone/kp/TryIt$Snapper.class +0 -0
  38. keypadml/_runtime/phone/kp/TryIt.class +0 -0
  39. keypadml/_tools.py +88 -0
  40. keypadml/_version.py +1 -0
  41. keypadml/cli.py +69 -0
  42. keypadml/convert.py +576 -0
  43. keypadml/export.py +311 -0
  44. keypadml/graph.py +211 -0
  45. keypadml/jarfile.py +68 -0
  46. keypadml/photo.py +80 -0
  47. keypadml/py.typed +0 -0
  48. keypadml/reference.py +109 -0
  49. keypadml/report.py +433 -0
  50. keypadml/runner.py +111 -0
  51. keypadml/serialize.py +228 -0
  52. keypadml-0.3.0.dist-info/METADATA +155 -0
  53. keypadml-0.3.0.dist-info/RECORD +57 -0
  54. keypadml-0.3.0.dist-info/WHEEL +5 -0
  55. keypadml-0.3.0.dist-info/entry_points.txt +2 -0
  56. keypadml-0.3.0.dist-info/licenses/LICENSE +202 -0
  57. keypadml-0.3.0.dist-info/top_level.txt +1 -0
keypadml/convert.py ADDED
@@ -0,0 +1,576 @@
1
+ """PyTorch model -> keypadml Graph, using torch.fx symbolic tracing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import operator
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.fx as fx
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from torch.fx.passes.shape_prop import ShapeProp
13
+
14
+ from .graph import (
15
+ ACT_CLAMP, ACT_ELU, ACT_GELU, ACT_GELU_TANH, ACT_HARDSIGMOID, ACT_HARDSWISH, ACT_LEAKY,
16
+ ACT_RELU, ACT_SIGMOID, ACT_SILU, ACT_TANH, Graph, Op,
17
+ )
18
+
19
+
20
+ class UnsupportedModelError(Exception):
21
+ """The model uses something keypadml cannot run on a phone. The message lists every problem."""
22
+
23
+
24
+ BIG = 3.0e38 # stands in for "no bound" in clamp
25
+
26
+
27
+ def _torch_fns(*names):
28
+ """torch functions that exist in this PyTorch version (some were added in 2.x)."""
29
+ return tuple(getattr(torch, n) for n in names if hasattr(torch, n))
30
+
31
+
32
+ _MAXPOOL = (F.max_pool2d,) + _torch_fns("max_pool2d")
33
+ _AVGPOOL = (F.avg_pool2d,) + _torch_fns("avg_pool2d")
34
+ _CAT = _torch_fns("cat", "concat", "concatenate")
35
+
36
+
37
+ def _f32(t) -> np.ndarray:
38
+ return t.detach().cpu().to(torch.float32).numpy().copy()
39
+
40
+
41
+ def _pair(v):
42
+ if isinstance(v, (tuple, list)):
43
+ return (int(v[0]), int(v[1])) if len(v) == 2 else (int(v[0]), int(v[0]))
44
+ return (int(v), int(v))
45
+
46
+
47
+ # ---------------------------------------------------------------- activations
48
+
49
+ def _activation(kind, target, args, kwargs, module=None):
50
+ """(act_code, a, b) if this node is an activation, else None."""
51
+ m = module
52
+ if m is not None:
53
+ if isinstance(m, nn.ReLU):
54
+ return (ACT_RELU, 0.0, 0.0)
55
+ if isinstance(m, nn.ReLU6):
56
+ return (ACT_CLAMP, 0.0, 6.0)
57
+ if isinstance(m, nn.Hardtanh):
58
+ return (ACT_CLAMP, float(m.min_val), float(m.max_val))
59
+ if isinstance(m, nn.LeakyReLU):
60
+ return (ACT_LEAKY, float(m.negative_slope), 0.0)
61
+ if isinstance(m, nn.Sigmoid):
62
+ return (ACT_SIGMOID, 0.0, 0.0)
63
+ if isinstance(m, nn.Tanh):
64
+ return (ACT_TANH, 0.0, 0.0)
65
+ if isinstance(m, nn.Hardsigmoid):
66
+ return (ACT_HARDSIGMOID, 0.0, 0.0)
67
+ if isinstance(m, nn.Hardswish):
68
+ return (ACT_HARDSWISH, 0.0, 0.0)
69
+ if isinstance(m, nn.SiLU):
70
+ return (ACT_SILU, 0.0, 0.0)
71
+ if isinstance(m, nn.GELU):
72
+ return (ACT_GELU_TANH if m.approximate == "tanh" else ACT_GELU, 0.0, 0.0)
73
+ if isinstance(m, nn.ELU):
74
+ return (ACT_ELU, float(m.alpha), 0.0)
75
+ return None
76
+
77
+ def arg(i, name, default):
78
+ if len(args) > i:
79
+ return args[i]
80
+ return kwargs.get(name, default)
81
+
82
+ name = target if kind == "call_method" else getattr(target, "__name__", str(target))
83
+ if kind == "call_method":
84
+ table = {"relu": ACT_RELU, "relu_": ACT_RELU, "sigmoid": ACT_SIGMOID, "sigmoid_": ACT_SIGMOID,
85
+ "tanh": ACT_TANH, "tanh_": ACT_TANH}
86
+ if name in table:
87
+ return (table[name], 0.0, 0.0)
88
+ if name in ("clamp", "clamp_", "clip"):
89
+ lo, hi = arg(1, "min", None), arg(2, "max", None)
90
+ if isinstance(lo, (int, float, type(None))) and isinstance(hi, (int, float, type(None))):
91
+ return (ACT_CLAMP, -BIG if lo is None else float(lo), BIG if hi is None else float(hi))
92
+ return None
93
+
94
+ if target in (F.relu,) + _torch_fns("relu", "relu_"):
95
+ return (ACT_RELU, 0.0, 0.0)
96
+ if target is F.relu6:
97
+ return (ACT_CLAMP, 0.0, 6.0)
98
+ if target in (F.hardtanh,):
99
+ return (ACT_CLAMP, float(arg(1, "min_val", -1.0)), float(arg(2, "max_val", 1.0)))
100
+ if target in _torch_fns("clamp", "clip"):
101
+ lo, hi = arg(1, "min", None), arg(2, "max", None)
102
+ if isinstance(lo, (int, float, type(None))) and isinstance(hi, (int, float, type(None))):
103
+ return (ACT_CLAMP, -BIG if lo is None else float(lo), BIG if hi is None else float(hi))
104
+ return None
105
+ if target is F.leaky_relu:
106
+ return (ACT_LEAKY, float(arg(1, "negative_slope", 0.01)), 0.0)
107
+ if target in (torch.sigmoid, F.sigmoid):
108
+ return (ACT_SIGMOID, 0.0, 0.0)
109
+ if target in (torch.tanh, F.tanh):
110
+ return (ACT_TANH, 0.0, 0.0)
111
+ if target is F.hardsigmoid:
112
+ return (ACT_HARDSIGMOID, 0.0, 0.0)
113
+ if target is F.hardswish:
114
+ return (ACT_HARDSWISH, 0.0, 0.0)
115
+ if target is F.silu:
116
+ return (ACT_SILU, 0.0, 0.0)
117
+ if target is F.gelu:
118
+ return (ACT_GELU_TANH if arg(1, "approximate", "none") == "tanh" else ACT_GELU, 0.0, 0.0)
119
+ if target is F.elu:
120
+ return (ACT_ELU, float(arg(1, "alpha", 1.0)), 0.0)
121
+ return None
122
+
123
+
124
+ # ---------------------------------------------------------------- converter
125
+
126
+ class _Converter:
127
+ def __init__(self, gm: fx.GraphModule):
128
+ self.gm = gm
129
+ self.modules = dict(gm.named_modules())
130
+ self.g = Graph()
131
+ self.env: dict = {} # fx node -> ("v", value id) | ("c", tensor) | ("s", python value)
132
+ self.problems: list[str] = []
133
+
134
+ # ---- helpers ----
135
+ def shape(self, node) -> tuple:
136
+ meta = node.meta.get("tensor_meta")
137
+ if meta is None or not hasattr(meta, "shape"):
138
+ raise UnsupportedModelError(f"{node.name}: does not produce a single tensor")
139
+ s = tuple(meta.shape)
140
+ if len(s) >= 2:
141
+ if s[0] != 1:
142
+ raise UnsupportedModelError(f"{node.name}: batch dimension changed to {s[0]}")
143
+ return s[1:]
144
+ return s
145
+
146
+ def val(self, a):
147
+ """Value id for a tensor argument (or raise)."""
148
+ if isinstance(a, fx.Node):
149
+ e = self.env.get(a)
150
+ if e is not None and e[0] == "v":
151
+ return e[1]
152
+ raise UnsupportedModelError("expected a tensor computed from the input")
153
+
154
+ def kind_of(self, a):
155
+ if isinstance(a, fx.Node):
156
+ e = self.env.get(a)
157
+ return e[0] if e else None
158
+ if isinstance(a, (int, float)):
159
+ return "n"
160
+ return None
161
+
162
+ def out(self, node, kind, inputs, attrs=None, tensors=None, act=None):
163
+ vid = self.g.new_value(self.shape(node))
164
+ op = Op(kind, node.name, list(inputs), vid, attrs or {}, tensors or [])
165
+ if act is not None:
166
+ op.act = act
167
+ self.g.ops.append(op)
168
+ self.env[node] = ("v", vid)
169
+ return op
170
+
171
+ # ---- main loop ----
172
+ def run(self) -> Graph:
173
+ skipped = 0
174
+ for node in self.gm.graph.nodes:
175
+ if any(self.env.get(a, (None,))[0] == "x" for a in node.all_input_nodes):
176
+ self.env[node] = ("x", None) # depends on an unsupported node: not a new problem
177
+ skipped += 1
178
+ continue
179
+ try:
180
+ self.visit(node)
181
+ except UnsupportedModelError as e:
182
+ self.problems.append(f" - {node.name} ({self.describe(node)}): {e}")
183
+ self.env[node] = ("x", None)
184
+ if self.problems:
185
+ more = f"\n ({skipped} later nodes depend on these and were not checked)" if skipped else ""
186
+ raise UnsupportedModelError(
187
+ "keypadml cannot export this model:\n" + "\n".join(self.problems) + more
188
+ + "\nSupported: Conv2d, Linear, BatchNorm, ReLU/ReLU6/LeakyReLU/Hardtanh/Sigmoid/Tanh/"
189
+ "Hardsigmoid/Hardswish/SiLU/GELU/ELU, Max/Avg/Adaptive pooling, Dropout, Flatten/view/"
190
+ "reshape, mean over H,W, add/mul (same shape, per channel or scalar), cat on channels, "
191
+ "Softmax/LogSoftmax.")
192
+ g = self.g
193
+ g.fold_batchnorm()
194
+ g.fuse_activations()
195
+ g.remove_dead()
196
+ g.validate()
197
+ return g
198
+
199
+ def describe(self, node):
200
+ if node.op == "call_module":
201
+ return type(self.modules[node.target]).__name__
202
+ if node.op == "call_function":
203
+ return getattr(node.target, "__name__", str(node.target))
204
+ return f"{node.op} {node.target}"
205
+
206
+ def visit(self, node):
207
+ op = node.op
208
+ if op == "placeholder":
209
+ meta = node.meta.get("tensor_meta")
210
+ if meta is None:
211
+ self.env[node] = ("s", None) # extra non-tensor argument with a default
212
+ return
213
+ if self.g.input is not None:
214
+ raise UnsupportedModelError("only models with a single tensor input are supported")
215
+ vid = self.g.new_value(self.shape(node))
216
+ self.g.input = vid
217
+ self.env[node] = ("v", vid)
218
+ return
219
+ if op == "get_attr":
220
+ obj = self.gm
221
+ for part in node.target.split("."):
222
+ obj = getattr(obj, part)
223
+ self.env[node] = ("c", obj.detach()) if isinstance(obj, torch.Tensor) else ("s", obj)
224
+ return
225
+ if op == "output":
226
+ res = node.args[0]
227
+ if not isinstance(res, fx.Node) or self.kind_of(res) != "v":
228
+ raise UnsupportedModelError("the model must return a single tensor")
229
+ self.g.output = self.val(res)
230
+ return
231
+ if op == "call_module":
232
+ return self.visit_module(node, self.modules[node.target])
233
+ if op in ("call_function", "call_method"):
234
+ return self.visit_function(node)
235
+ raise UnsupportedModelError(f"unknown node type {op}")
236
+
237
+ # ---- modules ----
238
+ def visit_module(self, node, m):
239
+ x = node.args[0] if node.args else None
240
+ act = _activation("call_module", None, (), {}, m)
241
+ if act is not None:
242
+ vid = self.val(x)
243
+ self.out(node, "act", [vid], act=act)
244
+ return
245
+ if isinstance(m, (nn.Dropout, nn.Dropout2d, nn.Dropout1d, nn.AlphaDropout, nn.Identity)):
246
+ self.env[node] = self.env[x]
247
+ return
248
+ if isinstance(m, (nn.Flatten, nn.Unflatten)):
249
+ self.env[node] = ("v", self.g.alias(self.val(x), self.shape(node), node.name))
250
+ return
251
+ if isinstance(m, nn.Conv2d):
252
+ if m.padding_mode != "zeros":
253
+ raise UnsupportedModelError(f"padding_mode={m.padding_mode!r} (only 'zeros')")
254
+ pad = self.conv_padding(m.padding, m.kernel_size, m.dilation)
255
+ self.conv(node, x, m.weight, m.bias, m.stride, pad, m.dilation, m.groups)
256
+ return
257
+ if isinstance(m, nn.Linear):
258
+ self.linear(node, x, m.weight, m.bias)
259
+ return
260
+ if isinstance(m, (nn.BatchNorm2d, nn.BatchNorm1d)):
261
+ if m.running_mean is None or m.running_var is None:
262
+ raise UnsupportedModelError("BatchNorm without running statistics")
263
+ self.batchnorm(node, x, m.running_mean, m.running_var, m.weight, m.bias, m.eps)
264
+ return
265
+ if isinstance(m, nn.MaxPool2d):
266
+ if m.return_indices:
267
+ raise UnsupportedModelError("return_indices=True")
268
+ self.maxpool(node, x, m.kernel_size, m.stride, m.padding, m.dilation, m.ceil_mode)
269
+ return
270
+ if isinstance(m, nn.AvgPool2d):
271
+ self.avgpool(node, x, m.kernel_size, m.stride, m.padding, m.ceil_mode,
272
+ m.count_include_pad, m.divisor_override)
273
+ return
274
+ if isinstance(m, nn.AdaptiveAvgPool2d):
275
+ self.adaptive(node, x, "adaptive_avg")
276
+ return
277
+ if isinstance(m, nn.AdaptiveMaxPool2d):
278
+ if m.return_indices:
279
+ raise UnsupportedModelError("return_indices=True")
280
+ self.adaptive(node, x, "adaptive_max")
281
+ return
282
+ if isinstance(m, (nn.Softmax, nn.LogSoftmax)):
283
+ self.softmax(node, x, m.dim, isinstance(m, nn.LogSoftmax))
284
+ return
285
+ raise UnsupportedModelError("layer type not supported")
286
+
287
+ # ---- functions and methods ----
288
+ def visit_function(self, node):
289
+ t, args, kw = node.target, node.args, node.kwargs
290
+ kind = node.op
291
+ name = t if kind == "call_method" else getattr(t, "__name__", "")
292
+
293
+ def arg(i, key, default=None):
294
+ return args[i] if len(args) > i else kw.get(key, default)
295
+
296
+ # shape queries: x.size(), x.shape, x.dim(), and ints derived from them
297
+ if (kind == "call_method" and name in ("size", "dim")) or (t is getattr and arg(1, "") in ("shape",)):
298
+ self.env[node] = ("s", None)
299
+ return
300
+ inputs = node.all_input_nodes
301
+ if inputs and all(self.env.get(a, (None,))[0] == "s" for a in inputs):
302
+ self.env[node] = ("s", None) # arithmetic on sizes (e.g. channels // groups)
303
+ return
304
+
305
+ act = _activation(kind, t, args, kw)
306
+ if act is not None:
307
+ self.out(node, "act", [self.val(args[0])], act=act)
308
+ return
309
+
310
+ # torchvision's stochastic depth: identity at inference time
311
+ if getattr(t, "__name__", "") == "stochastic_depth":
312
+ if arg(3, "training", True):
313
+ raise UnsupportedModelError("stochastic_depth in training mode")
314
+ self.env[node] = self.env[args[0]]
315
+ return
316
+
317
+ # no-ops and views
318
+ if (kind == "call_method" and name in ("contiguous", "clone", "detach", "float")) or t in (
319
+ F.dropout, F.dropout2d, F.alpha_dropout, torch.clone):
320
+ self.env[node] = self.env[args[0]]
321
+ return
322
+ if (kind == "call_method" and name in ("view", "reshape", "flatten", "squeeze", "unsqueeze",
323
+ "view_as", "reshape_as")) or t in (
324
+ torch.flatten, torch.reshape, torch.squeeze, torch.unsqueeze):
325
+ self.env[node] = ("v", self.g.alias(self.val(args[0]), self.shape(node), node.name))
326
+ return
327
+
328
+ if t in (F.conv2d,):
329
+ w, b = arg(1, "weight"), arg(2, "bias")
330
+ stride, pad, dil, groups = arg(3, "stride", 1), arg(4, "padding", 0), arg(5, "dilation", 1), arg(6, "groups", 1)
331
+ wt = self.const(w)
332
+ pad = self.conv_padding(pad, tuple(wt.shape[2:]), _pair(dil))
333
+ self.conv(node, args[0], wt, self.const(b) if b is not None else None, stride, pad, dil, groups)
334
+ return
335
+ if t is F.linear:
336
+ b = arg(2, "bias")
337
+ self.linear(node, args[0], self.const(arg(1, "weight")), self.const(b) if b is not None else None)
338
+ return
339
+ if t is F.batch_norm:
340
+ if arg(5, "training", False):
341
+ raise UnsupportedModelError("batch_norm in training mode")
342
+ w, b = arg(3, "weight"), arg(4, "bias")
343
+ self.batchnorm(node, args[0], self.const(arg(1, "running_mean")), self.const(arg(2, "running_var")),
344
+ self.const(w) if w is not None else None, self.const(b) if b is not None else None,
345
+ arg(7, "eps", 1e-5))
346
+ return
347
+ if t in _MAXPOOL:
348
+ if arg(6, "return_indices", False):
349
+ raise UnsupportedModelError("return_indices=True")
350
+ k = arg(1, "kernel_size")
351
+ self.maxpool(node, args[0], k, arg(2, "stride", None), arg(3, "padding", 0), arg(4, "dilation", 1),
352
+ arg(5, "ceil_mode", False))
353
+ return
354
+ if t in _AVGPOOL:
355
+ self.avgpool(node, args[0], arg(1, "kernel_size"), arg(2, "stride", None), arg(3, "padding", 0),
356
+ arg(4, "ceil_mode", False), arg(5, "count_include_pad", True), arg(6, "divisor_override", None))
357
+ return
358
+ if t is F.adaptive_avg_pool2d:
359
+ self.adaptive(node, args[0], "adaptive_avg")
360
+ return
361
+ if t is F.adaptive_max_pool2d:
362
+ if arg(2, "return_indices", False):
363
+ raise UnsupportedModelError("return_indices=True")
364
+ self.adaptive(node, args[0], "adaptive_max")
365
+ return
366
+ if t is torch.mean or (kind == "call_method" and name == "mean"):
367
+ self.mean(node, args[0], arg(1, "dim"))
368
+ return
369
+ if t in _CAT:
370
+ self.concat(node, arg(0, "tensors"), arg(1, "dim", 0))
371
+ return
372
+ if t in (F.softmax, torch.softmax, F.log_softmax, torch.log_softmax) or (
373
+ kind == "call_method" and name in ("softmax", "log_softmax")):
374
+ log = t in (F.log_softmax, torch.log_softmax) or name == "log_softmax"
375
+ self.softmax(node, args[0], arg(1, "dim"), log)
376
+ return
377
+ if t in (operator.add, operator.iadd, torch.add) or (kind == "call_method" and name in ("add", "add_")):
378
+ if arg(2, "alpha", 1) != 1:
379
+ raise UnsupportedModelError("add with alpha")
380
+ self.binary(node, args[0], args[1], "add")
381
+ return
382
+ if t in (operator.mul, operator.imul, torch.mul) or (kind == "call_method" and name in ("mul", "mul_")):
383
+ self.binary(node, args[0], args[1], "mul")
384
+ return
385
+ if t in (operator.sub, operator.isub, torch.sub) or (kind == "call_method" and name == "sub"):
386
+ a, b = args[0], args[1]
387
+ if self.kind_of(a) == "v" and isinstance(b, (int, float)):
388
+ self.out(node, "scalar", [self.val(a)], {"mul": 1.0, "add": -float(b)})
389
+ return
390
+ if isinstance(a, (int, float)) and self.kind_of(b) == "v":
391
+ self.out(node, "scalar", [self.val(b)], {"mul": -1.0, "add": float(a)})
392
+ return
393
+ raise UnsupportedModelError("subtraction of two tensors")
394
+ if t in (operator.truediv, operator.itruediv, torch.div) or (kind == "call_method" and name == "div"):
395
+ a, b = args[0], args[1]
396
+ if self.kind_of(a) == "v" and isinstance(b, (int, float)) and b != 0:
397
+ self.out(node, "scalar", [self.val(a)], {"mul": 1.0 / float(b), "add": 0.0})
398
+ return
399
+ raise UnsupportedModelError("division (only tensor / number)")
400
+ if t is operator.neg or (kind == "call_method" and name == "neg"):
401
+ self.out(node, "scalar", [self.val(args[0])], {"mul": -1.0, "add": 0.0})
402
+ return
403
+ raise UnsupportedModelError("operation not supported")
404
+
405
+ # ---- op builders ----
406
+ def const(self, a) -> torch.Tensor:
407
+ if isinstance(a, torch.Tensor):
408
+ return a.detach()
409
+ if isinstance(a, fx.Node) and self.env.get(a, (None,))[0] == "c":
410
+ return self.env[a][1]
411
+ raise UnsupportedModelError("weights must be parameters, not computed tensors")
412
+
413
+ @staticmethod
414
+ def conv_padding(padding, kernel, dilation):
415
+ kh, kw = _pair(kernel)
416
+ dh, dw = _pair(dilation)
417
+ if isinstance(padding, str):
418
+ if padding == "valid":
419
+ return (0, 0)
420
+ if padding == "same":
421
+ th, tw = dh * (kh - 1), dw * (kw - 1)
422
+ if th % 2 or tw % 2:
423
+ raise UnsupportedModelError("padding='same' with an even kernel (asymmetric padding)")
424
+ return (th // 2, tw // 2)
425
+ raise UnsupportedModelError(f"padding={padding!r}")
426
+ return _pair(padding)
427
+
428
+ def conv(self, node, x, weight, bias, stride, pad, dilation, groups):
429
+ vid = self.val(x)
430
+ c, h, w = self.g.values[vid].chw()
431
+ if len(self.g.values[vid].shape) != 3:
432
+ raise UnsupportedModelError("Conv2d input must be (N, C, H, W)")
433
+ wt = _f32(weight)
434
+ b = _f32(bias) if bias is not None else np.zeros(0, np.float32)
435
+ op = self.out(node, "conv", [vid], {
436
+ "stride": _pair(stride), "padding": _pair(pad), "dilation": _pair(dilation), "groups": int(groups),
437
+ }, [wt, b])
438
+ oc, oh, ow = self.g.values[op.output].chw()
439
+ if wt.shape[0] != oc or wt.shape[1] * groups != c:
440
+ raise UnsupportedModelError("unexpected weight shape")
441
+
442
+ def linear(self, node, x, weight, bias):
443
+ vid = self.val(x)
444
+ shp = self.g.values[vid].shape
445
+ if len(shp) != 1 and not all(d == 1 for d in shp[:-1]):
446
+ raise UnsupportedModelError(f"Linear on a tensor of shape {shp} (flatten it first)")
447
+ wt = _f32(weight)
448
+ b = _f32(bias) if bias is not None else np.zeros(0, np.float32)
449
+ self.out(node, "linear", [vid], {}, [wt, b])
450
+
451
+ def batchnorm(self, node, x, mean, var, weight, bias, eps):
452
+ vid = self.val(x)
453
+ mean, var = mean.double(), var.double()
454
+ gamma = weight.double() if weight is not None else torch.ones_like(mean)
455
+ beta = bias.double() if bias is not None else torch.zeros_like(mean)
456
+ scale = gamma / torch.sqrt(var + eps)
457
+ shift = beta - mean * scale
458
+ self.out(node, "affine", [vid], {"from_bn": True}, [_f32(scale), _f32(shift)])
459
+
460
+ def maxpool(self, node, x, k, stride, pad, dil, ceil_mode):
461
+ vid = self.val(x)
462
+ k = _pair(k)
463
+ self.out(node, "maxpool", [vid], {
464
+ "kernel": k, "stride": _pair(stride if stride not in (None, [], ()) else k), "padding": _pair(pad),
465
+ "dilation": _pair(dil), "ceil_mode": bool(ceil_mode)})
466
+
467
+ def avgpool(self, node, x, k, stride, pad, ceil_mode, cip, divisor):
468
+ vid = self.val(x)
469
+ k = _pair(k)
470
+ self.out(node, "avgpool", [vid], {
471
+ "kernel": k, "stride": _pair(stride if stride not in (None, [], ()) else k), "padding": _pair(pad),
472
+ "ceil_mode": bool(ceil_mode), "count_include_pad": bool(cip),
473
+ "divisor": int(divisor) if divisor else 0})
474
+
475
+ def adaptive(self, node, x, kind):
476
+ vid = self.val(x)
477
+ if len(self.g.values[vid].shape) != 3:
478
+ raise UnsupportedModelError("adaptive pooling input must be (N, C, H, W)")
479
+ self.out(node, kind, [vid])
480
+
481
+ def mean(self, node, x, dim):
482
+ vid = self.val(x)
483
+ if len(self.g.values[vid].shape) != 3:
484
+ raise UnsupportedModelError("mean is only supported over H and W of an (N, C, H, W) tensor")
485
+ dims = dim if isinstance(dim, (tuple, list)) else [dim]
486
+ dims = sorted(int(d) % 4 for d in dims)
487
+ if dims != [2, 3]:
488
+ raise UnsupportedModelError(f"mean over dims {dim} (only H and W)")
489
+ self.out(node, "adaptive_avg", [vid])
490
+
491
+ def concat(self, node, tensors, dim):
492
+ vids = [self.val(t) for t in tensors]
493
+ rank = len(self.g.values[vids[0]].shape) + 1
494
+ if int(dim) % rank != 1:
495
+ raise UnsupportedModelError("cat is only supported along the channel dimension")
496
+ self.out(node, "concat", vids)
497
+
498
+ def softmax(self, node, x, dim, log):
499
+ vid = self.val(x)
500
+ shp = self.g.values[vid].shape
501
+ rank = len(shp) + 1
502
+ if dim is None or int(dim) % rank != 1 or any(d != 1 for d in shp[1:]):
503
+ raise UnsupportedModelError("softmax is only supported over classes (dim=1 of (N, K))")
504
+ self.out(node, "log_softmax" if log else "softmax", [vid])
505
+
506
+ def binary(self, node, a, b, kind):
507
+ ka, kb = self.kind_of(a), self.kind_of(b)
508
+ if ka != "v" and kb == "v":
509
+ a, b, ka, kb = b, a, kb, ka
510
+ if ka != "v":
511
+ raise UnsupportedModelError(f"{kind} without a tensor computed from the input")
512
+ va = self.val(a)
513
+ shape_a = self.g.values[va].shape
514
+ if isinstance(b, (int, float)):
515
+ attrs = {"mul": float(b), "add": 0.0} if kind == "mul" else {"mul": 1.0, "add": float(b)}
516
+ self.out(node, "scalar", [va], attrs)
517
+ return
518
+ if kb == "c":
519
+ ct = self.env[b][1].to(torch.float32)
520
+ c = self.g.values[va].chw()[0]
521
+ if ct.numel() == 1:
522
+ v = float(ct.reshape(-1)[0])
523
+ attrs = {"mul": v, "add": 0.0} if kind == "mul" else {"mul": 1.0, "add": v}
524
+ self.out(node, "scalar", [va], attrs)
525
+ return
526
+ if ct.numel() == c and (ct.dim() <= 1 or all(d == 1 for d in ct.shape[-2:])):
527
+ ones, zeros = np.ones(c, np.float32), np.zeros(c, np.float32)
528
+ v = _f32(ct.reshape(-1))
529
+ tensors = [v, zeros] if kind == "mul" else [ones, v]
530
+ self.out(node, "affine", [va], {}, tensors)
531
+ return
532
+ raise UnsupportedModelError(f"{kind} with a constant of shape {tuple(ct.shape)}")
533
+ if kb != "v":
534
+ raise UnsupportedModelError(f"{kind} with an unsupported operand")
535
+ vb = self.val(b)
536
+ shape_b = self.g.values[vb].shape
537
+ out_shape = self.shape(node)
538
+ if shape_a == shape_b:
539
+ self.out(node, kind, [va, vb], {"mode": 0})
540
+ return
541
+ # one operand per channel: (C,1,1) against (C,H,W)
542
+ for big, small, sb in ((va, vb, shape_b), (vb, va, shape_a)):
543
+ big_shape = self.g.values[big].shape
544
+ if (len(big_shape) == 3 and tuple(out_shape) == tuple(big_shape)
545
+ and int(np.prod(sb)) == big_shape[0] and (len(sb) == 1 or all(d == 1 for d in sb[1:]))):
546
+ self.out(node, kind, [big, small], {"mode": 1})
547
+ return
548
+ raise UnsupportedModelError(f"{kind} of shapes {shape_a} and {shape_b} (only equal or per-channel)")
549
+
550
+
551
+ def convert(model: nn.Module, example: torch.Tensor) -> Graph:
552
+ """Traces `model` (in eval mode, on CPU) with a batch-1 example input and builds the Graph."""
553
+ try:
554
+ gm = fx.symbolic_trace(model)
555
+ except Exception as e: # noqa: BLE001 - fx raises many kinds of errors
556
+ raise UnsupportedModelError(
557
+ f"torch.fx could not trace the model ({type(e).__name__}: {e}).\n"
558
+ "keypadml needs a model whose forward() has no data-dependent Python control flow. "
559
+ "You can also pass an already traced torch.fx.GraphModule.") from e
560
+ ShapeProp(gm).propagate(example)
561
+ return _Converter(gm).run()
562
+
563
+
564
+ def macs(g: Graph, op: Op) -> int:
565
+ """Multiply-accumulates of one op (0 for cheap element-wise ops)."""
566
+ if op.kind == "conv":
567
+ oc, oh, ow = g.values[op.output].chw()
568
+ w = op.tensors[0]
569
+ return int(oc * oh * ow * w.shape[1] * w.shape[2] * w.shape[3])
570
+ if op.kind == "linear":
571
+ w = op.tensors[0]
572
+ return int(w.shape[0] * w.shape[1])
573
+ return 0
574
+
575
+
576
+ __all__ = ["convert", "UnsupportedModelError", "macs"]