File size: 2,811 Bytes
bd894ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from __future__ import annotations

import json
from pathlib import Path

import gradio as gr
import numpy as np
import plotly.graph_objects as go
import torch
from model import MatchedMLP, SplineKAN
from plotly.subplots import make_subplots
from safetensors.torch import load_file

ARTIFACT_DIR = Path(__file__).resolve().parent / "artifacts" / "spline-kan-pocket"
REPORT = json.loads((ARTIFACT_DIR / "evaluation.json").read_text(encoding="utf-8"))
MODELS = {
    "Spline KAN": (SplineKAN(), "spline_kan"),
    "Matched MLP": (MatchedMLP(), "matched_mlp"),
}
for model, key in MODELS.values():
    model.load_state_dict(load_file(ARTIFACT_DIR / f"{key}.safetensors"))
    model.eval()


def target(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    return (
        np.sin(np.pi * x * y)
        + 0.35 * (x**3 - y**2)
        + 0.2 * np.cos(2 * np.pi * x)
    )


@torch.inference_mode()
def render_surface(model_name: str, domain: float) -> tuple[go.Figure, dict]:
    axis = np.linspace(-float(domain), float(domain), 60, dtype=np.float32)
    x, y = np.meshgrid(axis, axis)
    inputs = torch.from_numpy(np.stack([x.ravel(), y.ravel()], axis=1))
    model, key = MODELS[model_name]
    prediction = model(inputs)[:, 0].numpy().reshape(x.shape)
    truth = target(x, y)
    figure = make_subplots(
        rows=1,
        cols=2,
        specs=[[{"type": "surface"}, {"type": "surface"}]],
        subplot_titles=["True surface", model_name],
    )
    figure.add_trace(go.Surface(x=x, y=y, z=truth, showscale=False), row=1, col=1)
    figure.add_trace(
        go.Surface(x=x, y=y, z=prediction, showscale=False), row=1, col=2
    )
    figure.update_layout(template="plotly_dark", height=560)
    metrics = {
        "parameters": REPORT["results"][key]["parameters"],
        "interpolation_rmse": REPORT["results"][key]["interpolation"]["rmse"],
        "extrapolation_rmse": REPORT["results"][key]["extrapolation"]["rmse"],
        "live_surface_rmse": float(np.sqrt(np.mean((prediction - truth) ** 2))),
    }
    return figure, metrics


with gr.Blocks(title="Spline KAN Pocket") as demo:
    gr.Markdown(
        "# Spline KAN Pocket\n"
        "Explore a learnable edge-spline network and its exactly parameter-matched "
        "MLP control on a nonlinear symbolic surface."
    )
    with gr.Row():
        model_name = gr.Dropdown(list(MODELS), value="Spline KAN", label="Model")
        domain = gr.Slider(1.0, 1.5, value=1.0, step=0.1, label="Displayed domain")
    initial = render_surface("Spline KAN", 1.0)
    surface = gr.Plot(value=initial[0])
    metrics = gr.JSON(value=initial[1])
    button = gr.Button("Render learned surface", variant="primary")
    button.click(render_surface, inputs=[model_name, domain], outputs=[surface, metrics])


if __name__ == "__main__":
    demo.launch()