torchtangents 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.

Potentially problematic release.


This version of torchtangents might be problematic. Click here for more details.

@@ -0,0 +1,18 @@
1
+ from . import nn
2
+ from . import stax
3
+ from . import predict
4
+ from . import convert
5
+ from ._src.convert import lift, kernel, empirical_ntk
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "nn",
11
+ "stax",
12
+ "predict",
13
+ "convert",
14
+ "lift",
15
+ "kernel",
16
+ "empirical_ntk",
17
+ "__version__",
18
+ ]
File without changes
@@ -0,0 +1,634 @@
1
+ import math
2
+ import operator
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from typing import Callable, Any, Dict, Type, Optional, Union, List, Tuple
7
+ from .nn.modules import (
8
+ Sequential,
9
+ Linear,
10
+ ReLU,
11
+ Conv1d,
12
+ Conv2d,
13
+ Conv3d,
14
+ ConvTranspose1d,
15
+ ConvTranspose2d,
16
+ ConvTranspose3d,
17
+ AdaptiveAvgPool1d,
18
+ AdaptiveAvgPool2d,
19
+ AdaptiveAvgPool3d,
20
+ AvgPool1d,
21
+ AvgPool2d,
22
+ AvgPool3d,
23
+ SumPool1d,
24
+ SumPool2d,
25
+ SumPool3d,
26
+ LayerNorm,
27
+ Dropout,
28
+ StaxModule,
29
+ Flatten,
30
+ Identity,
31
+ StaxModuleMixin,
32
+ LeakyReLU,
33
+ GELU,
34
+ Abs,
35
+ SigmoidLike,
36
+ Erf,
37
+ compute_empirical_ntk,
38
+ )
39
+ from .. import stax as _stax
40
+ from .utils.kernel import Kernel, _combine_kernels_sum
41
+ from .stax.requirements import StaxKernelModule
42
+
43
+ # Registry mapping standard PyTorch modules to Tangential modules
44
+ _CONVERSION_REGISTRY: Dict[Type[nn.Module], Callable[[Any], nn.Module]] = {}
45
+
46
+
47
+ def register_conversion(torch_layer_type: Type[nn.Module], conversion_fn: Callable[[Any], nn.Module]):
48
+ """Registers a mapping allowing Torchtangents to parse standard modules iteratively."""
49
+ _CONVERSION_REGISTRY[torch_layer_type] = conversion_fn
50
+
51
+
52
+ def _add_kernels(args, kw, get):
53
+ k1, k2 = args[0], args[1]
54
+ if isinstance(k1, Kernel) and isinstance(k2, Kernel):
55
+ res = _combine_kernels_sum(k1, k2)
56
+ return _stax.Identity().kernel_fn(res, get=get) if get is not None else res
57
+ return operator.add(k1, k2)
58
+
59
+
60
+ # Functional mapping for torch.fx call_function nodes operating on Kernel objects
61
+ _FUNCTIONAL_KERNEL_MAP: Dict[Any, Callable[..., Any]] = {
62
+ torch.relu: lambda args, kw, get: _stax.ReLU().kernel_fn(args[0], get=get),
63
+ F.relu: lambda args, kw, get: _stax.ReLU().kernel_fn(args[0], get=get),
64
+ F.leaky_relu: lambda args, kw, get: _stax.LeakyReLU(kw.get('negative_slope', args[1] if len(args) > 1 else 0.01)).kernel_fn(args[0], get=get),
65
+ F.gelu: lambda args, kw, get: _stax.GeLU(approximate=kw.get('approximate', 'none')).kernel_fn(args[0], get=get),
66
+ torch.sigmoid: lambda args, kw, get: _stax.Sigmoid_like().kernel_fn(args[0], get=get),
67
+ F.sigmoid: lambda args, kw, get: _stax.Sigmoid_like().kernel_fn(args[0], get=get),
68
+ torch.erf: lambda args, kw, get: _stax.Erf().kernel_fn(args[0], get=get),
69
+ torch.abs: lambda args, kw, get: _stax.Abs().kernel_fn(args[0], get=get),
70
+ torch.sin: lambda args, kw, get: _stax.Sin().kernel_fn(args[0], get=get),
71
+ torch.cos: lambda args, kw, get: _stax.Cos().kernel_fn(args[0], get=get),
72
+ torch.exp: lambda args, kw, get: _stax.Exp().kernel_fn(args[0], get=get),
73
+ torch.sign: lambda args, kw, get: _stax.Sign().kernel_fn(args[0], get=get),
74
+ torch.flatten: lambda args, kw, get: _stax.Flatten().kernel_fn(args[0], get=get),
75
+ operator.add: _add_kernels,
76
+ torch.add: _add_kernels,
77
+ operator.mul: lambda args, kw, get: _stax.FanInProd().kernel_fn([args[0], args[1]], get=get),
78
+ torch.mul: lambda args, kw, get: _stax.FanInProd().kernel_fn([args[0], args[1]], get=get),
79
+ torch.cat: lambda args, kw, get: _stax.FanInConcat(axis=kw.get('dim', args[1] if len(args) > 1 else 1)).kernel_fn(args[0], get=get),
80
+ torch.concat: lambda args, kw, get: _stax.FanInConcat(axis=kw.get('dim', args[1] if len(args) > 1 else 1)).kernel_fn(args[0], get=get),
81
+ }
82
+
83
+
84
+ def _copy_linear_params(src: nn.Linear, dst: Linear) -> Linear:
85
+ dst.to(device=src.weight.device, dtype=src.weight.dtype)
86
+ with torch.no_grad():
87
+ if dst.parameterization == 'ntk':
88
+ dst.weight.copy_(src.weight * ((src.in_features ** 0.5) / dst.W_std))
89
+ if src.bias is not None and dst.bias is not None and dst.b_std:
90
+ dst.bias.copy_(src.bias / dst.b_std)
91
+ else:
92
+ dst.weight.copy_(src.weight)
93
+ if src.bias is not None and dst.bias is not None:
94
+ dst.bias.copy_(src.bias)
95
+ return dst
96
+
97
+
98
+ def _copy_conv_params(src: nn.Module, dst: nn.Module) -> Any:
99
+ dst.to(device=src.weight.device, dtype=src.weight.dtype)
100
+ with torch.no_grad():
101
+ if getattr(dst, 'parameterization', 'ntk') == 'ntk':
102
+ fan_in = src.in_channels * math.prod(src.kernel_size)
103
+ dst.weight.copy_(src.weight * ((fan_in ** 0.5) / dst.W_std))
104
+ if src.bias is not None and dst.bias is not None and dst.b_std:
105
+ dst.bias.copy_(src.bias / dst.b_std)
106
+ else:
107
+ dst.weight.copy_(src.weight)
108
+ if src.bias is not None and dst.bias is not None:
109
+ dst.bias.copy_(src.bias)
110
+ return dst
111
+
112
+
113
+ # Core Conversions
114
+ def _convert_linear(m: nn.Linear) -> Linear:
115
+ has_bias = m.bias is not None
116
+ out = Linear(
117
+ in_features=m.in_features,
118
+ out_features=m.out_features,
119
+ b_std=1.0 if has_bias else None,
120
+ parameterization='ntk'
121
+ )
122
+ return _copy_linear_params(m, out)
123
+
124
+
125
+ def _convert_relu(m: nn.ReLU) -> ReLU:
126
+ return ReLU()
127
+
128
+
129
+ def _convert_leaky_relu(m: nn.LeakyReLU) -> LeakyReLU:
130
+ return LeakyReLU(negative_slope=m.negative_slope)
131
+
132
+
133
+ def _convert_gelu(m: nn.GELU) -> GELU:
134
+ return GELU(approximate=m.approximate)
135
+
136
+
137
+ def _convert_abs(m: nn.Module) -> Abs:
138
+ return Abs()
139
+
140
+
141
+ def _convert_erf(m: nn.Module) -> Erf:
142
+ a = getattr(m, 'a', 1.0)
143
+ b = getattr(m, 'b', 1.0)
144
+ c = getattr(m, 'c', 0.0)
145
+ return Erf(a=a, b=b, c=c)
146
+
147
+
148
+ def _convert_sigmoid(m: nn.Sigmoid) -> SigmoidLike:
149
+ return SigmoidLike()
150
+
151
+
152
+ def _convert_conv1d(m: nn.Conv1d) -> Conv1d:
153
+ has_bias = m.bias is not None
154
+ padding_val = 'VALID'
155
+ if m.padding == 'same' or (isinstance(m.padding, tuple) and any(p > 0 for p in m.padding)):
156
+ padding_val = 'SAME'
157
+ out = Conv1d(
158
+ in_channels=m.in_channels,
159
+ out_channels=m.out_channels,
160
+ kernel_size=m.kernel_size[0],
161
+ strides=m.stride[0],
162
+ padding=padding_val,
163
+ b_std=1.0 if has_bias else None
164
+ )
165
+ return _copy_conv_params(m, out)
166
+
167
+
168
+ def _convert_conv2d(m: nn.Conv2d) -> Conv2d:
169
+ has_bias = m.bias is not None
170
+ padding_val = 'VALID'
171
+ if m.padding == 'same' or (isinstance(m.padding, tuple) and any(p > 0 for p in m.padding)):
172
+ padding_val = 'SAME'
173
+ out = Conv2d(
174
+ in_channels=m.in_channels,
175
+ out_channels=m.out_channels,
176
+ kernel_size=m.kernel_size,
177
+ strides=m.stride,
178
+ padding=padding_val,
179
+ b_std=1.0 if has_bias else None
180
+ )
181
+ return _copy_conv_params(m, out)
182
+
183
+
184
+ def _convert_conv3d(m: nn.Conv3d) -> Conv3d:
185
+ has_bias = m.bias is not None
186
+ padding_val = 'VALID'
187
+ if m.padding == 'same' or (isinstance(m.padding, tuple) and any(p > 0 for p in m.padding)):
188
+ padding_val = 'SAME'
189
+ out = Conv3d(
190
+ in_channels=m.in_channels,
191
+ out_channels=m.out_channels,
192
+ kernel_size=m.kernel_size,
193
+ strides=m.stride,
194
+ padding=padding_val,
195
+ b_std=1.0 if has_bias else None
196
+ )
197
+ return _copy_conv_params(m, out)
198
+
199
+
200
+ def _convert_conv_transpose1d(m: nn.ConvTranspose1d) -> ConvTranspose1d:
201
+ has_bias = m.bias is not None
202
+ padding_val = 'VALID'
203
+ if m.padding != 0 and m.padding != (0,):
204
+ padding_val = 'SAME'
205
+ out = ConvTranspose1d(
206
+ in_channels=m.in_channels,
207
+ out_channels=m.out_channels,
208
+ kernel_size=m.kernel_size[0],
209
+ strides=m.stride[0],
210
+ padding=padding_val,
211
+ b_std=1.0 if has_bias else None
212
+ )
213
+ return _copy_conv_params(m, out)
214
+
215
+
216
+ def _convert_conv_transpose2d(m: nn.ConvTranspose2d) -> ConvTranspose2d:
217
+ has_bias = m.bias is not None
218
+ padding_val = 'VALID'
219
+ if m.padding != 0 and m.padding != (0, 0):
220
+ padding_val = 'SAME'
221
+ out = ConvTranspose2d(
222
+ in_channels=m.in_channels,
223
+ out_channels=m.out_channels,
224
+ kernel_size=m.kernel_size,
225
+ strides=m.stride,
226
+ padding=padding_val,
227
+ b_std=1.0 if has_bias else None
228
+ )
229
+ return _copy_conv_params(m, out)
230
+
231
+
232
+ def _convert_conv_transpose3d(m: nn.ConvTranspose3d) -> ConvTranspose3d:
233
+ has_bias = m.bias is not None
234
+ padding_val = 'VALID'
235
+ if m.padding != 0 and m.padding != (0, 0, 0):
236
+ padding_val = 'SAME'
237
+ out = ConvTranspose3d(
238
+ in_channels=m.in_channels,
239
+ out_channels=m.out_channels,
240
+ kernel_size=m.kernel_size,
241
+ strides=m.stride,
242
+ padding=padding_val,
243
+ b_std=1.0 if has_bias else None
244
+ )
245
+ return _copy_conv_params(m, out)
246
+
247
+
248
+ def _convert_avgpool1d_adaptive(m: nn.AdaptiveAvgPool1d) -> AdaptiveAvgPool1d:
249
+ return AdaptiveAvgPool1d()
250
+
251
+
252
+ def _convert_avgpool2d_adaptive(m: nn.AdaptiveAvgPool2d) -> AdaptiveAvgPool2d:
253
+ return AdaptiveAvgPool2d()
254
+
255
+
256
+ def _convert_avgpool3d_adaptive(m: nn.AdaptiveAvgPool3d) -> AdaptiveAvgPool3d:
257
+ return AdaptiveAvgPool3d()
258
+
259
+
260
+ def _convert_avgpool1d(m: nn.AvgPool1d) -> AvgPool1d:
261
+ padding_val = 'VALID'
262
+ if m.padding != 0 and m.padding != (0,):
263
+ padding_val = 'SAME'
264
+ return AvgPool1d(kernel_size=m.kernel_size, stride=m.stride, padding=padding_val)
265
+
266
+
267
+ def _convert_avgpool2d(m: nn.AvgPool2d) -> AvgPool2d:
268
+ padding_val = 'VALID'
269
+ if m.padding != 0 and m.padding != (0, 0):
270
+ padding_val = 'SAME'
271
+ return AvgPool2d(kernel_size=m.kernel_size, stride=m.stride, padding=padding_val)
272
+
273
+
274
+ def _convert_avgpool3d(m: nn.AvgPool3d) -> AvgPool3d:
275
+ padding_val = 'VALID'
276
+ if m.padding != 0 and m.padding != (0, 0, 0):
277
+ padding_val = 'SAME'
278
+ return AvgPool3d(kernel_size=m.kernel_size, stride=m.stride, padding=padding_val)
279
+
280
+
281
+ def _convert_layernorm(m: nn.LayerNorm) -> LayerNorm:
282
+ out = LayerNorm(normalized_shape=m.normalized_shape, eps=m.eps, elementwise_affine=m.elementwise_affine)
283
+ if m.elementwise_affine and m.weight is not None:
284
+ out.to(device=m.weight.device, dtype=m.weight.dtype)
285
+ with torch.no_grad():
286
+ out.weight.copy_(m.weight)
287
+ if m.bias is not None and out.bias is not None:
288
+ out.bias.copy_(m.bias)
289
+ return out
290
+
291
+
292
+ def _convert_dropout(m: nn.Dropout) -> Dropout:
293
+ return Dropout(p=m.p)
294
+
295
+
296
+ def _convert_flatten(m: nn.Flatten) -> Flatten:
297
+ return Flatten(start_dim=m.start_dim, end_dim=m.end_dim)
298
+
299
+
300
+ def _convert_identity(m: nn.Identity) -> Identity:
301
+ return Identity()
302
+
303
+
304
+ # Registering
305
+ register_conversion(nn.Linear, _convert_linear)
306
+ register_conversion(nn.ReLU, _convert_relu)
307
+ register_conversion(nn.LeakyReLU, _convert_leaky_relu)
308
+ register_conversion(nn.GELU, _convert_gelu)
309
+ register_conversion(nn.Sigmoid, _convert_sigmoid)
310
+ register_conversion(nn.Conv1d, _convert_conv1d)
311
+ register_conversion(nn.Conv2d, _convert_conv2d)
312
+ register_conversion(nn.Conv3d, _convert_conv3d)
313
+ register_conversion(nn.ConvTranspose1d, _convert_conv_transpose1d)
314
+ register_conversion(nn.ConvTranspose2d, _convert_conv_transpose2d)
315
+ register_conversion(nn.ConvTranspose3d, _convert_conv_transpose3d)
316
+ register_conversion(nn.AdaptiveAvgPool1d, _convert_avgpool1d_adaptive)
317
+ register_conversion(nn.AdaptiveAvgPool2d, _convert_avgpool2d_adaptive)
318
+ register_conversion(nn.AdaptiveAvgPool3d, _convert_avgpool3d_adaptive)
319
+ register_conversion(nn.AvgPool1d, _convert_avgpool1d)
320
+ register_conversion(nn.AvgPool2d, _convert_avgpool2d)
321
+ register_conversion(nn.AvgPool3d, _convert_avgpool3d)
322
+ register_conversion(nn.LayerNorm, _convert_layernorm)
323
+ register_conversion(nn.Dropout, _convert_dropout)
324
+ register_conversion(nn.Flatten, _convert_flatten)
325
+ register_conversion(nn.Identity, _convert_identity)
326
+ register_conversion(Abs, _convert_abs)
327
+ register_conversion(Erf, _convert_erf)
328
+
329
+
330
+ class LiftedModule(StaxModule):
331
+ final_output: Any
332
+
333
+ def __init__(self, original_model: nn.Module, force: bool = False):
334
+ import torch.fx
335
+ import warnings
336
+
337
+ def init_fn(rng, input_shape): return input_shape, ()
338
+ def apply_fn(params, x, **kwargs): return self._forward_impl(x, **kwargs)
339
+ def kernel_fn(x1, x2=None, get=None, **kwargs): return self._kernel_impl(x1, x2, get, **kwargs)
340
+
341
+ super().__init__((init_fn, apply_fn, kernel_fn), input_shape=(1,))
342
+ self.params_list = nn.ParameterList()
343
+ self.registry = nn.ModuleDict()
344
+ self.steps: List[Tuple[str, str, Any]] = []
345
+ self.arg_map: Dict[str, Tuple[List[Any], Dict[str, Any]]] = {}
346
+ self.input_nodes: List[str] = []
347
+ self.final_output = None
348
+ self._original = original_model
349
+ self._use_direct_dispatch = False
350
+
351
+ try:
352
+ traced = torch.fx.symbolic_trace(original_model)
353
+ except Exception:
354
+ # Dynamic control flow (if/else, loops) that torch.fx cannot symbolically trace:
355
+ # fall back to direct Kernel.__torch_function__ dispatch on original_model.
356
+ self._use_direct_dispatch = True
357
+ return
358
+
359
+ node_to_var = {}
360
+ for node in traced.graph.nodes:
361
+ if node.op == 'placeholder':
362
+ node_id = node.name
363
+ node_to_var[node] = node_id
364
+ self.input_nodes.append(node_id)
365
+ self.arg_map[node_id] = ([], {})
366
+ elif node.op in ['call_module', 'call_function', 'call_method']:
367
+ node_id = node.name
368
+ if node.op == 'call_module':
369
+ submodule = original_model.get_submodule(str(node.target))
370
+ sub_type = type(submodule)
371
+ if sub_type in _CONVERSION_REGISTRY:
372
+ stax_mod = _CONVERSION_REGISTRY[sub_type](submodule)
373
+ self.registry[node_id] = stax_mod
374
+ target = node_id
375
+ elif isinstance(submodule, (StaxModule, StaxModuleMixin)):
376
+ self.registry[node_id] = submodule
377
+ target = node_id
378
+ elif force:
379
+ warnings.warn(f"Module {sub_type} unmapped; retaining standard behavior.")
380
+ self.registry[node_id] = submodule
381
+ target = node_id
382
+ else:
383
+ raise NotImplementedError(f"No conversion for {sub_type}. Use force=True.")
384
+ else:
385
+ target = node.target
386
+ self.steps.append((node_id, node.op, target))
387
+ inputs = [node_to_var[arg] if isinstance(arg, torch.fx.Node) else arg for arg in node.args]
388
+ kwargs_dict = {k: node_to_var[v] if isinstance(v, torch.fx.Node) else v for k, v in node.kwargs.items()}
389
+ self.arg_map[node_id] = (inputs, kwargs_dict)
390
+ node_to_var[node] = node_id
391
+ elif node.op == 'output':
392
+ output_node = node.args[0]
393
+ if isinstance(output_node, torch.fx.Node):
394
+ self.final_output = node_to_var[output_node]
395
+ elif isinstance(output_node, (tuple, list)):
396
+ self.final_output = tuple(node_to_var[v] if isinstance(v, torch.fx.Node) else v for v in output_node)
397
+ else:
398
+ self.final_output = output_node
399
+
400
+ def visualize(self):
401
+ """Displays the physical execution graph using networkx / trace visualizer"""
402
+ try:
403
+ dg, _ = map_module_to_graph(self._original)
404
+ visualize_graph(dg)
405
+ except Exception as e:
406
+ print(f"Could not visualize execution graph explicitly: {e}")
407
+
408
+ def _forward_impl(self, x, **kwargs):
409
+ if self._use_direct_dispatch:
410
+ return self._original(x, **kwargs)
411
+ cache = {}
412
+ if len(self.input_nodes) == 1:
413
+ cache[self.input_nodes[0]] = x
414
+ else:
415
+ for i, in_name in enumerate(self.input_nodes):
416
+ cache[in_name] = x[i]
417
+ for node_id, op_type, target in self.steps:
418
+ args_names, call_kwargs = self.arg_map[node_id]
419
+ args = [cache[n] if isinstance(n, str) and n in cache else n for n in args_names]
420
+ res_kwargs = {k: cache[v] if isinstance(v, str) and v in cache else v for k, v in call_kwargs.items()}
421
+ if op_type == 'call_module':
422
+ cache[node_id] = self.registry[target](*args, **res_kwargs)
423
+ elif op_type == 'call_function':
424
+ cache[node_id] = target(*args, **res_kwargs)
425
+ elif op_type == 'call_method':
426
+ cache[node_id] = getattr(args[0], str(target))(*args[1:], **res_kwargs)
427
+ if isinstance(self.final_output, tuple):
428
+ return tuple(cache[v] if isinstance(v, str) and v in cache else v for v in self.final_output)
429
+ return cache[self.final_output] if isinstance(self.final_output, str) and self.final_output in cache else self.final_output
430
+
431
+ def _kernel_impl(self, x1, x2=None, get=None, **kwargs):
432
+ if self._use_direct_dispatch:
433
+ k_in = x1 if isinstance(x1, Kernel) else Kernel.from_inputs(
434
+ x1, x2, compute_ntk=(get is None) or ('ntk' in get), **kwargs
435
+ )
436
+ k_out = self._original(k_in)
437
+ return _stax.Identity().kernel_fn(k_out, get=get) if get is not None else k_out
438
+
439
+ cache = {}
440
+ if len(self.input_nodes) == 1:
441
+ cache[self.input_nodes[0]] = x1
442
+ else:
443
+ for i, in_name in enumerate(self.input_nodes):
444
+ cache[in_name] = x1[i]
445
+ for i, (node_id, op_type, target) in enumerate(self.steps):
446
+ args_n, call_kw = self.arg_map[node_id]
447
+ args = [cache[n] if isinstance(n, str) and n in cache else n for n in args_n]
448
+ res_kw = {k: cache[v] if isinstance(v, str) and v in cache else v for k, v in call_kw.items()}
449
+ is_last = (i == len(self.steps) - 1)
450
+ layer_get = get if is_last else None
451
+ if op_type == 'call_module':
452
+ stax_m = self.registry[target]
453
+ if hasattr(stax_m, 'kernel_fn'):
454
+ if isinstance(args[0], Kernel):
455
+ cache[node_id] = stax_m.kernel_fn(args[0], get=layer_get, **res_kw)
456
+ else:
457
+ cache[node_id] = stax_m.kernel_fn(args[0], x2, get=layer_get, **res_kw)
458
+ else:
459
+ raise NotImplementedError(
460
+ f"Module {type(stax_m)} does not support infinite-width kernel computation."
461
+ )
462
+ elif op_type == 'call_function':
463
+ has_kernel_arg = any(
464
+ isinstance(a, Kernel) or (isinstance(a, (list, tuple)) and any(isinstance(x, Kernel) for x in a))
465
+ for a in args
466
+ )
467
+ if has_kernel_arg and target in _FUNCTIONAL_KERNEL_MAP:
468
+ cache[node_id] = _FUNCTIONAL_KERNEL_MAP[target](args, res_kw, layer_get)
469
+ else:
470
+ cache[node_id] = target(*args, **res_kw)
471
+ elif op_type == 'call_method':
472
+ obj = args[0]
473
+ method_name = str(target)
474
+ if isinstance(obj, Kernel):
475
+ if method_name == 'size':
476
+ if len(args) > 1 and isinstance(args[1], int):
477
+ cache[node_id] = obj.shape1[args[1]]
478
+ else:
479
+ cache[node_id] = obj.shape1
480
+ continue
481
+ elif method_name in ('view', 'reshape', 'flatten'):
482
+ if len(obj.shape1) > 2 or layer_get is not None:
483
+ cache[node_id] = _stax.Flatten().kernel_fn(obj, get=layer_get)
484
+ else:
485
+ cache[node_id] = obj
486
+ continue
487
+ cache[node_id] = getattr(obj, method_name)(*args[1:], **res_kw)
488
+ if isinstance(self.final_output, tuple):
489
+ return tuple(cache[v] if isinstance(v, str) and v in cache else v for v in self.final_output)
490
+ return cache[self.final_output] if isinstance(self.final_output, str) and self.final_output in cache else self.final_output
491
+
492
+
493
+ def inject(module: nn.Module, input_shape: Optional[tuple] = None):
494
+ if type(module) in _CONVERSION_REGISTRY:
495
+ original_cls = type(module)
496
+ class InjectedModule(original_cls, StaxModuleMixin):
497
+ def forward(self, x, **kwargs):
498
+ if isinstance(x, Kernel):
499
+ return self.inf_kernel(x, **kwargs)
500
+ return original_cls.forward(self, x, **kwargs)
501
+ stax_module = _CONVERSION_REGISTRY[original_cls](module)
502
+ module.__class__ = InjectedModule
503
+ module.setup_stax_module(stax_module, input_shape or getattr(stax_module, 'input_shape', None), register_params=False)
504
+ return module
505
+ for name, child in module.named_children():
506
+ inject(child)
507
+ return module
508
+
509
+
510
+ def make_tangential(module: nn.Module) -> nn.Module:
511
+ if type(module) in _CONVERSION_REGISTRY:
512
+ return _CONVERSION_REGISTRY[type(module)](module)
513
+ if isinstance(module, nn.Sequential):
514
+ return Sequential(*[make_tangential(c) for c in module])
515
+ raise NotImplementedError(f"No conversion for {type(module)}.")
516
+
517
+
518
+ def lift(module: torch.nn.Module, force: bool = False) -> 'StaxModule':
519
+ return LiftedModule(module, force=force)
520
+
521
+
522
+ def infinite_analog(module: torch.nn.Module) -> 'StaxKernelModule':
523
+ """Returns the analytical kernel_fn equivalent of the standard PyTorch module."""
524
+ try:
525
+ tangential = make_tangential(module)
526
+ return StaxKernelModule(tangential.kernel_fn, name=f"Infinite{type(module).__name__}")
527
+ except (NotImplementedError, AttributeError):
528
+ lifting = lift(module)
529
+ return StaxKernelModule(lifting.kernel_fn, name=f"Infinite{type(module).__name__}")
530
+
531
+
532
+ def kernel(
533
+ model: Any,
534
+ x1: Union[torch.Tensor, Kernel],
535
+ x2: Optional[torch.Tensor] = None,
536
+ get: Optional[Any] = ('nngp', 'ntk'),
537
+ **kwargs,
538
+ ):
539
+ """
540
+ Computes the infinite-width NNGP / NTK kernel for any PyTorch nn.Module,
541
+ tt.nn module, or tt.stax module without requiring model rewrites.
542
+ """
543
+ if hasattr(model, 'inf_kernel'):
544
+ return model.inf_kernel(x1, x2, get=get, **kwargs)
545
+ if hasattr(model, 'kernel_fn'):
546
+ return model.kernel_fn(x1, x2, get=get, **kwargs)
547
+ compute_ntk = (get is None) or (get == 'ntk') or (isinstance(get, (tuple, list)) and 'ntk' in get)
548
+ k_in = x1 if isinstance(x1, Kernel) else Kernel.from_inputs(
549
+ x1, x2, compute_ntk=compute_ntk, **kwargs
550
+ )
551
+ k_out = model(k_in)
552
+ return _stax.Identity().kernel_fn(k_out, get=get) if get is not None else k_out
553
+
554
+
555
+ def empirical_ntk(
556
+ model: nn.Module,
557
+ x1: torch.Tensor,
558
+ x2: Optional[torch.Tensor] = None,
559
+ ) -> torch.Tensor:
560
+ """
561
+ Computes the finite-width empirical NTK for any PyTorch nn.Module from its current parameters.
562
+ """
563
+ if hasattr(model, 'empirical_ntk') and callable(model.empirical_ntk):
564
+ return model.empirical_ntk(x1, x2)
565
+ return compute_empirical_ntk(model, x1, x2)
566
+
567
+
568
+ def optimize_model(model: Any, backend: str = "inductor") -> Any:
569
+ """Wraps kernel with torch.compile if supported."""
570
+ import sys
571
+ if sys.platform == "win32":
572
+ return model
573
+ if hasattr(model, 'kernel_fn'):
574
+ model.kernel_fn = torch.compile(model.kernel_fn, backend=backend)
575
+ return model
576
+
577
+
578
+ def map_module_to_graph(model: torch.nn.Module):
579
+ import torch.fx
580
+ import networkx as nx
581
+ traced = torch.fx.symbolic_trace(model)
582
+ dg = nx.DiGraph()
583
+ for node in traced.graph.nodes:
584
+ dg.add_node(node.name, op=node.op, target=str(node.target))
585
+ for input_node in node.all_input_nodes:
586
+ dg.add_edge(input_node.name, node.name)
587
+ return dg, traced
588
+
589
+
590
+ def visualize_graph(dg, title="Model Architecture Graph (Operational Flow)"):
591
+ import networkx as nx
592
+ import matplotlib.pyplot as plt
593
+ import os, sys
594
+ if sys.platform == "win32" or sys.platform == "win64":
595
+ os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
596
+ try:
597
+ from networkx.drawing.nx_agraph import graphviz_layout
598
+ pos = graphviz_layout(dg, prog='dot', args='-Grankdir=LR')
599
+ except Exception:
600
+ for layer, nodes in enumerate(nx.topological_generations(dg)):
601
+ for node in nodes:
602
+ dg.nodes[node]["layer"] = layer
603
+ pos = nx.multipartite_layout(dg, subset_key="layer", align="vertical")
604
+
605
+ color_map = []
606
+ labels = {}
607
+ for node in dg.nodes():
608
+ node_data = dg.nodes[node]
609
+ op = node_data.get('op', '')
610
+ if op == 'placeholder':
611
+ color_map.append('lightgreen')
612
+ elif op == 'output':
613
+ color_map.append('lightcoral')
614
+ elif op == 'call_module':
615
+ color_map.append('skyblue')
616
+ else:
617
+ color_map.append('lightgrey')
618
+ target = node_data.get('target', '')
619
+ if op == 'call_module':
620
+ labels[node] = f"{node}"
621
+ elif op == 'placeholder':
622
+ labels[node] = f"INPUT\n{node}"
623
+ elif op == 'output':
624
+ labels[node] = "OUTPUT"
625
+ else:
626
+ labels[node] = str(target) if target and str(target) != "None" else node
627
+
628
+ plt.figure(figsize=(10, 8))
629
+ nx.draw_networkx(dg, pos, labels=labels, node_size=3000, node_color=color_map,
630
+ font_size=9, font_weight="bold", arrows=True, arrowsize=10, edge_color="gray")
631
+ plt.title(title)
632
+ plt.axis('off')
633
+ plt.tight_layout()
634
+ plt.show()
File without changes