Kolmogorov-Arnold Network Edge Splines: PyTorch Architecture¶
Navigation:
Mathematical Theory: See KAN.md
Spectrum API Overview: See The Spectrum API
Overview & Formula Tokens¶
Kolmogorov-Arnold edge splines are exposed via kan():
# Kolmogorov-Arnold Network edge splines with scale-stable inner nodes
formula = "Y ~ kan(x1, others='x2|x3', n_nodes=6, k_inner=6, k_outer=10)"
Parameter Specification¶
KANEffect (kan())¶
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
|
|
Secondary features separated by |
|
|
|
Number of inner aggregation nodes \(Q\). |
|
|
|
Inner edge spline knots per feature. |
|
|
|
Outer univariate spline knots per node. |
|
|
|
Inner-edge roughness multiplier \(\alpha_{\text{edge}}\) weighting \(\mathcal{E}_q\). |
Complexity & Performance¶
Linear Parameter Scaling:
KANEffectscales as \(\mathcal{O}(Q k_{\text{outer}})\) coefficients instead of \(\mathcal{O}(k^d)\) tensor products, with per-feature standardization and frozen \((\hat{\mu}_q, \hat{\sigma}_q)\) pre-tanh normalization preventing saturation.
State, Complexity and Limits¶
Class and file:
KANEffect,src/tam/model/spectrum/_kan.py. Label: (BETA).State: none (
stateful = False).Layout:
(B, T, d)or(N, d)rows (a tensor-product margin); one column may also be given as(B, T). One row of the input gives one row of features.Time and memory: \(\mathcal{O}(B\,T\,Q\,(d\,k_{\text{in}} + k_{\text{out}}))\); the groups are rows of one batch.
Extrapolation: all modes of the router are available (the effect has no memory).
Limits: the inner edges are drawn from
seedand not trained: two seeds give two different, equally valid, feature maps; useseedto reproduce a fit.Penalty ridge: each node block is
weight * D2.T @ D2 + 1e-6 * I(eps_ridgeinbuild_penalty_matrix). The ridge is kept on purpose: it makes the penalty positive definite so that the REML log-determinant is defined, and it is part of the numbers of the benchmarks.
Code¶
Feature map of KANEffect (build_feature_map):
def build_feature_map(self, x_col: torch.Tensor, state_in: Optional[Dict[str, Any]] = None) -> torch.Tensor:
r"""Constructs the explicit Primal KAN design matrix.
Args:
x_col: ``(B, T, d)``, ``(B, T)`` for one input column, or ``(N, d)`` rows (a tensor-product margin).
Returns:
Design matrix ``(B, T, Q * k_outer)`` (``(N, Q * k_outer)`` for rows). KAN reads one row at a time: no state.
"""
if self._x_mean is None:
self.initialize(x_col)
x_in, shape, layout, B, T = self._rows(x_col)
if x_in.shape[1] != self.n_in_features:
raise ValueError(f"kan expects {self.n_in_features} input column(s), got {x_in.shape[1]}")
x_std_in = self._standardize(x_in)
u = self._nodes(x_std_in)
u_mean = self._u_mean.to(device=u.device, dtype=u.dtype)
u_std = self._u_std.to(device=u.device, dtype=u.dtype)
z = torch.tanh(0.28 * (u - u_mean) / u_std) # (N_rows, Q)
knots_out = self.knots_out.to(device=x_in.device, dtype=x_in.dtype)
phi_kan = torch.cat([_cox_de_boor(z[:, q], knots_out, self.spline_degree) for q in range(self.n_nodes)], dim=-1)
return from_btk(phi_kan.reshape(B, T, self.n_nodes * self.k_outer), shape, layout)
Penalty of KANEffect (build_penalty_matrix):
def build_penalty_matrix(self) -> torch.Tensor:
r"""Constructs block-diagonal second-difference Sobolev penalty weighted by inner-edge roughness:
.. math::
P_{\text{kan}} = \operatorname{blkdiag}_{q=1}^Q \left( (1 + \alpha_{\text{edge}} \mathcal{E}_q) D_{\text{order}}^\top D_{\text{order}} + \varepsilon_{\text{ridge}} I \right) \cdot \lambda_p
"""
dtype = torch.get_default_dtype()
I_sub = torch.eye(self.n_outer_coeffs, device=TORCH_DEVICE, dtype=dtype)
if self.penalty_order == 0:
D = I_sub
else:
D = torch.diff(I_sub, n=self.penalty_order, dim=0)
D2_outer = D.T @ D
eps_ridge = 1e-6 * I_sub
if self.c_spline is None:
self._init_inner_parameters(self.n_in_features, dtype, TORCH_DEVICE)
c_sp = self.c_spline.to(device=TORCH_DEVICE, dtype=dtype) # (Q, d, k_inner)
if self.k_inner > 2:
I_in = torch.eye(self.k_inner, device=TORCH_DEVICE, dtype=dtype)
D_in = torch.diff(I_in, n=min(2, self.k_inner - 1), dim=0)
# c_sp @ D_in.T has shape (Q, d, k_inner - 2)
rough_in = torch.matmul(c_sp, D_in.T)
e_q = torch.mean(torch.sum(rough_in ** 2, dim=-1), dim=-1) # (Q,)
else:
e_q = torch.mean(torch.sum(c_sp ** 2, dim=-1), dim=-1)
blocks = []
for q in range(self.n_nodes):
weight_q = 1.0 + self.edge_pen * float(e_q[q].item())
blocks.append((weight_q * D2_outer + eps_ridge) * self.lambda_p)
return torch.block_diag(*blocks)
Parsing of the kan(...) token in the factory:
elif ttype == 'kan':
n_nodes = int(params_resolved.get('n_nodes', params_resolved.get('q', 8)))
k_inner = int(params_resolved.get('k_inner', 6))
k_outer = int(params_resolved.get('k_outer', 8))
deg = int(params_resolved.get('degree', 3))
p = int(params_resolved.get('penalty_order', 2))
edge_pen = float(params_resolved.get('edge_pen', 0.1))
seed = int(params_resolved.get('seed', 42))
extrap_val = params_resolved.get('extrapolate', 'continue')
additional_features = _parse_additional_features(params_resolved)
effects_list.append(KANEffect(
feature_name=feature_name,
additional_features=additional_features,
n_nodes=n_nodes,
k_inner=k_inner,
k_outer=k_outer,
spline_degree=deg,
penalty_order=p,
edge_pen=edge_pen,
lambda_p=lambda_p,
seed=seed,
extrapolate=extrap_val,
))