File size: 5,338 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from __future__ import annotations

import json
from pathlib import Path

import pandas as pd
import torch
import trackio
from data import irregular_batch
from model import (
    LiquidTimeConstantRNN,
    MatchedGRU,
    MatchedRNN,
    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" / "liquid-time-pocket"
DATA_DIR = PROJECT_DIR / "data"
SEED = 2203


@torch.inference_mode()
def evaluate(model: torch.nn.Module, *, large_gaps: bool) -> dict:
    inputs, targets, _ = irregular_batch(
        2_000,
        128,
        SEED + 10_000 + int(large_gaps),
        large_gaps=large_gaps,
    )
    prediction = model(inputs)
    error = prediction - targets
    return {
        "rmse": float(error.square().mean().sqrt()),
        "mae": float(error.abs().mean()),
        "examples": len(inputs),
        "sequence_length": inputs.shape[1],
        "delta_time_range": [0.12, 0.40] if large_gaps else [0.02, 0.12],
    }


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-5)
    best = float("inf")
    best_step = 0
    best_state = None
    for step in range(1, 2_501):
        inputs, targets, _ = irregular_batch(
            96, 64, SEED + step, large_gaps=False
        )
        prediction = model(inputs)
        loss = F.mse_loss(prediction, targets)
        optimizer.zero_grad(set_to_none=True)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 5)
        optimizer.step()
        if step % 125 == 0:
            validation = evaluate(model, large_gaps=False)
            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 = {
        "liquid_time_constant": LiquidTimeConstantRNN(),
        "matched_gru": MatchedGRU(),
        "matched_rnn": MatchedRNN(),
    }
    assert {parameter_count(model) for model in models.values()} == {1_887}
    trackio.init(
        project="liquid-time-pocket",
        name="irregular-gap-ltc-v1",
        config={
            "parameters_per_model": 1_887,
            "training_steps": 2_500,
            "training_delta_time": [0.02, 0.12],
            "unseen_delta_time": [0.12, 0.40],
        },
    )
    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,
            "normal_gaps": evaluate(model, large_gaps=False),
            "unseen_large_gaps": evaluate(model, large_gaps=True),
        }
        save_file(model.state_dict(), ARTIFACT_DIR / f"{name}.safetensors")
    inputs, targets, time = irregular_batch(
        100, 128, SEED + 30_000, large_gaps=True
    )
    frame = {
        "task": [],
        "time": [],
        "target": [],
        **{name: [] for name in models},
    }
    with torch.inference_mode():
        predictions = {name: model(inputs) for name, model in models.items()}
    for task in range(len(inputs)):
        for step in range(inputs.shape[1]):
            frame["task"].append(task)
            frame["time"].append(float(time[task, step]))
            frame["target"].append(float(targets[task, step, 0]))
            for name in models:
                frame[name].append(float(predictions[name][task, step, 0]))
    report = {
        "experiment": "Liquid time-constant irregular forecasting",
        "learned_time_constants": {
            "minimum": float(
                (F.softplus(models["liquid_time_constant"].log_time_constant) + 0.03)
                .min()
            ),
            "mean": float(
                (F.softplus(models["liquid_time_constant"].log_time_constant) + 0.03)
                .mean()
            ),
            "maximum": float(
                (F.softplus(models["liquid_time_constant"].log_time_constant) + 0.03)
                .max()
            ),
        },
        "results": results,
    }
    (ARTIFACT_DIR / "evaluation.json").write_text(
        json.dumps(report, indent=2), encoding="utf-8"
    )
    pd.DataFrame(frame).to_parquet(DATA_DIR / "large_gap_forecasts.parquet", index=False)
    trackio.log(
        {
            f"{name}_large_gap_rmse": result["unseen_large_gaps"]["rmse"]
            for name, result in results.items()
        }
    )
    trackio.finish()
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()