File size: 2,514 Bytes
477b01d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
from pathlib import Path

import gradio as gr
import plotly.graph_objects as go
import torch
from data import irregular_batch
from model import LiquidTimeConstantRNN, MatchedGRU, MatchedRNN
from safetensors.torch import load_file

ARTIFACT_DIR = Path(__file__).resolve().parent / "artifacts" / "liquid-time-pocket"
REPORT = json.loads((ARTIFACT_DIR / "evaluation.json").read_text(encoding="utf-8"))
MODELS = {
    "Liquid time constant": (LiquidTimeConstantRNN(), "liquid_time_constant"),
    "Matched GRU": (MatchedGRU(), "matched_gru"),
    "Matched RNN": (MatchedRNN(), "matched_rnn"),
}
for model, key in MODELS.values():
    model.load_state_dict(load_file(ARTIFACT_DIR / f"{key}.safetensors"))
    model.eval()


@torch.inference_mode()
def forecast(seed: int, large_gaps: bool) -> tuple[go.Figure, dict]:
    inputs, targets, time = irregular_batch(
        1, 128, int(seed), large_gaps=bool(large_gaps)
    )
    figure = go.Figure()
    figure.add_trace(
        go.Scatter(x=time[0], y=targets[0, :, 0], name="Target", line={"width": 4})
    )
    metrics = {}
    for label, (model, key) in MODELS.items():
        prediction = model(inputs)[0, :, 0]
        figure.add_trace(go.Scatter(x=time[0], y=prediction, name=label))
        metrics[label] = {
            "live_rmse": float(
                (prediction - targets[0, :, 0]).square().mean().sqrt()
            ),
            "verified_large_gap_rmse": REPORT["results"][key][
                "unseen_large_gaps"
            ]["rmse"],
        }
    figure.update_layout(
        template="plotly_dark",
        title="Irregularly sampled multiscale forecast",
        xaxis_title="Continuous time",
        yaxis_title="Signal",
    )
    return figure, metrics


with gr.Blocks(title="Liquid Time Pocket") as demo:
    gr.Markdown(
        "# Liquid Time Pocket\n"
        "Compare a learned continuous decay cell with exactly parameter-matched "
        "GRU and RNN controls under irregular time gaps."
    )
    with gr.Row():
        seed = gr.Slider(0, 100_000, value=2203, step=1, label="Task seed")
        large_gaps = gr.Checkbox(True, label="Use unseen large time gaps")
    initial = forecast(2203, True)
    chart = gr.Plot(value=initial[0])
    metrics = gr.JSON(value=initial[1])
    button = gr.Button("Forecast irregular telemetry", variant="primary")
    button.click(forecast, inputs=[seed, large_gaps], outputs=[chart, metrics])


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