| from __future__ import annotations |
|
|
| import json |
| import math |
| from pathlib import Path |
|
|
| import pandas as pd |
| import torch |
| import trackio |
| from model import MatchedMLP, SplineKAN, parameter_count |
| from safetensors.torch import save_file |
| from torch.nn import functional as F |
|
|
| PROJECT_DIR = Path(__file__).resolve().parent |
| ARTIFACT_DIR = PROJECT_DIR / "artifacts" / "spline-kan-pocket" |
| DATA_DIR = PROJECT_DIR / "data" |
| SEED = 2161 |
|
|
|
|
| def target_function(inputs: torch.Tensor) -> torch.Tensor: |
| x = inputs[:, :1] |
| y = inputs[:, 1:] |
| return ( |
| torch.sin(math.pi * x * y) |
| + 0.35 * (x.pow(3) - y.square()) |
| + 0.2 * torch.cos(2 * math.pi * x) |
| ) |
|
|
|
|
| @torch.inference_mode() |
| def evaluate(model: torch.nn.Module, *, extrapolation: bool) -> dict: |
| generator = torch.Generator().manual_seed(SEED + int(extrapolation) + 10_000) |
| if extrapolation: |
| values = [] |
| while sum(len(batch) for batch in values) < 20_000: |
| candidate = -1.5 + 3 * torch.rand(25_000, 2, generator=generator) |
| values.append(candidate[(candidate.abs() > 1).any(dim=1)]) |
| inputs = torch.cat(values)[:20_000] |
| else: |
| inputs = -1 + 2 * torch.rand(20_000, 2, generator=generator) |
| target = target_function(inputs) |
| prediction = model(inputs) |
| error = prediction - target |
| return { |
| "rmse": float(error.square().mean().sqrt()), |
| "mae": float(error.abs().mean()), |
| "maximum_absolute_error": float(error.abs().max()), |
| "examples": len(inputs), |
| "domain": "outside training square" if extrapolation else "training square", |
| } |
|
|
|
|
| def train_variant(name: str, model: torch.nn.Module) -> tuple[torch.nn.Module, int]: |
| optimizer = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-6) |
| best = float("inf") |
| best_state = None |
| best_step = 0 |
| validation_generator = torch.Generator().manual_seed(SEED + 5_000) |
| validation_inputs = -1 + 2 * torch.rand( |
| 5_000, 2, generator=validation_generator |
| ) |
| validation_target = target_function(validation_inputs) |
| for step in range(1, 4_001): |
| generator = torch.Generator().manual_seed(SEED + step) |
| inputs = -1 + 2 * torch.rand(512, 2, generator=generator) |
| prediction = model(inputs) |
| loss = F.mse_loss(prediction, target_function(inputs)) |
| if name == "spline_kan": |
| spline_l1 = model.first.coefficients.abs().mean() |
| spline_l1 = spline_l1 + model.second.coefficients.abs().mean() |
| loss = loss + 1e-6 * spline_l1 |
| optimizer.zero_grad(set_to_none=True) |
| loss.backward() |
| optimizer.step() |
| if step % 200 == 0: |
| with torch.inference_mode(): |
| validation_rmse = float( |
| (model(validation_inputs) - validation_target) |
| .square() |
| .mean() |
| .sqrt() |
| ) |
| trackio.log( |
| { |
| "variant": name, |
| "training_step": step, |
| "training_mse": float(loss.detach()), |
| "validation_rmse": validation_rmse, |
| } |
| ) |
| if validation_rmse < best: |
| best = validation_rmse |
| best_step = step |
| best_state = { |
| key: value.detach().cpu().clone() |
| for key, value in model.state_dict().items() |
| } |
| assert best_state is not None |
| model.load_state_dict(best_state) |
| return model, best_step |
|
|
|
|
| def main() -> None: |
| torch.manual_seed(SEED) |
| torch.set_num_threads(1) |
| models = {"spline_kan": SplineKAN(), "matched_mlp": MatchedMLP()} |
| assert parameter_count(models["spline_kan"]) == parameter_count( |
| models["matched_mlp"] |
| ) |
| trackio.init( |
| project="spline-kan-pocket", |
| name="edge-splines-versus-mlp-v1", |
| config={ |
| "parameters_per_model": parameter_count(models["spline_kan"]), |
| "training_steps": 4_000, |
| "training_domain": "[-1, 1]^2", |
| }, |
| ) |
| results = {} |
| ARTIFACT_DIR.mkdir(parents=True, exist_ok=True) |
| DATA_DIR.mkdir(parents=True, exist_ok=True) |
| for name, model in models.items(): |
| model, best_step = train_variant(name, model) |
| results[name] = { |
| "parameters": parameter_count(model), |
| "best_step": best_step, |
| "interpolation": evaluate(model, extrapolation=False), |
| "extrapolation": evaluate(model, extrapolation=True), |
| } |
| save_file(model.state_dict(), ARTIFACT_DIR / f"{name}.safetensors") |
| generator = torch.Generator().manual_seed(SEED + 30_000) |
| inputs = -1.5 + 3 * torch.rand(10_000, 2, generator=generator) |
| with torch.inference_mode(): |
| frame = { |
| "x": inputs[:, 0].numpy(), |
| "y": inputs[:, 1].numpy(), |
| "target": target_function(inputs)[:, 0].numpy(), |
| "spline_kan": models["spline_kan"](inputs)[:, 0].numpy(), |
| "matched_mlp": models["matched_mlp"](inputs)[:, 0].numpy(), |
| } |
| report = { |
| "experiment": "Spline KAN versus exactly parameter-matched MLP", |
| "target": "sin(pi*x*y) + 0.35*(x^3-y^2) + 0.2*cos(2*pi*x)", |
| "results": results, |
| } |
| (ARTIFACT_DIR / "evaluation.json").write_text( |
| json.dumps(report, indent=2), encoding="utf-8" |
| ) |
| pd.DataFrame(frame).to_parquet(DATA_DIR / "surface_predictions.parquet", index=False) |
| trackio.log( |
| { |
| "kan_interpolation_rmse": results["spline_kan"]["interpolation"]["rmse"], |
| "mlp_interpolation_rmse": results["matched_mlp"]["interpolation"]["rmse"], |
| "kan_extrapolation_rmse": results["spline_kan"]["extrapolation"]["rmse"], |
| "mlp_extrapolation_rmse": results["matched_mlp"]["extrapolation"]["rmse"], |
| } |
| ) |
| trackio.finish() |
| print(json.dumps(report, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|