Download source/train.py from ARotting/liquid-time-large-gap-forecasts: direct link, hf CLI and curl.
- Browser
- Download file 5.34 kB
-
https://huggingface.co/datasets/ARotting/liquid-time-large-gap-forecasts/resolve/main/source/train.py
- Command line
-
hf download hf://datasets/ARotting/liquid-time-large-gap-forecasts/source/train.py
-
curl -L -o train.py https://huggingface.co/datasets/ARotting/liquid-time-large-gap-forecasts/resolve/main/source/train.py
5.34 kB
| 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 | |
| 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() | |