Skip to content

Training and reproduction

itsminni edited this page Nov 25, 2026 · 2 revisions

Train and evaluate Giano

This guide starts with the original weather files and ends with the weights you trained, a reconstructed NetCDF and a table of errors on measured temperatures, humidity, pressure, precipitation and wind where available. Everything can run locally. The four notebooks introduce the same steps on small inputs.

Install and choose a starting point

Install Git, Python 3.11 and uv. Clone the repository, open a terminal in the checkout and create the locked environment. The examples below use paths relative to the checkout. Enclose paths containing spaces in double quotes. Git · uv installation

git clone --branch v2.0.0 https://github.com/itsminni/giano.git
cd giano
uv sync --locked --python 3.11 --group notebooks
uv run --locked --group notebooks jupyter lab notebooks/

Open the notebooks in numerical order and choose Run All Cells. They include a year of Swiss measurements, the Trentino coverage table and eight real Trentino windows from each of training and development. Notebook 02 trains both members from their original random initialisations and loads the exported ensemble into inference. This little run demonstrates the mechanics. To reproduce the published weights or to score the original 480 outages, continue with the Drive files below.

Get the original observations

Download both folders from the shared Meteotrentino dataset and extract them under one directory. If Drive splits the download into multiple ZIPs, merge their contents using the existing directory names. Set the argument to the directory that contains both folders. Download the dataset on Google Drive

data/
  1-raw/
    dump/                  original station readings and quality flags
    era5/                  gridded external weather at station locations
  2-processed-v2/
    train/                 hourly NetCDF files, one station and variable per file
    val/
    test/

The three subdirectories of processed files group stations. A temperature file in the directory named test can hold observations from many years. The Giano training protocol selects hours by calendar date across the station files. It uses 2009–2010 for optimisation, 2011 for development and 2020 for the historical evaluation. The source reader checks the processed files and the ERA5 inputs it uses against their recorded SHA-256 digests.

What the Trentino files contain

Each processed NetCDF holds one station and variable in 2-processed-v2/<group>/<station>_<variable>_merged.nc. The hourly series is value(time), with missing observations stored as NaN. Files can also carry quality codes, auxiliary weather fields and wind components. The processed timestamps retain the source clock. The coordinates used by the model correspond to reanalysis grid points. The station catalogue supplies the locations used on the map.

In the raw Meteotrentino observations, codes 151 and 255 mark missing values. Hourly processing averages valid temperature, humidity, pressure and wind-speed samples. Direction uses a circular mean, so readings near 359° and 1° average near north. Rainfall uses a sum and an empty or invalid partial hour stays missing. Sample counts and valid fractions describe how much of each hour was observed. Availability masks distinguish missing measurements from missing external inputs. Meteotrentino observations · ERA5-Land dataset and methods

Prepare the training data

uv run --locked giano-prepare --data data --output runs/windows

Expect 14,817 training windows and 7,611 development windows, each spanning 72 hours with 24 station slots. Preparation verifies each reconstructed source window against the original experiment, applies the quality mask to the labels and adds the calibrated surface pressure input. The local cache takes about 4 GB. It is shared by both seeds. For a quick check of the Drive download, run the same command with --preview --output runs/preview-windows. That cache contains eight windows per split.

Outages cover 7, 30 and 90 days. Target-station, external-only and no-contemporary-input scenarios change what is visible throughout each simulated outage. Its hidden observations are excluded from training references. The protocol includes the chosen station-hours, quality flags, pressure offsets and seeded initial tensors. Training reuses the release’s frozen physical calibrations. The window checks compare numerical inputs with the reference run on CPU. The model learns four outputs from six input variables. Wind speed and direction retain the physical reference.

The distributed inference calibration fits humidity references on 2009–2010 only. It excludes missing quality flags, processed codes 140, 151 and 255 and readings outside 0–100%. Where a station has fewer than four eligible readings it uses the regional reference. This updates station statistics while preserving the original training windows. To reproduce the reference asset, run python examples/trentino/calibrate_humidity.py --data data --base src/giano/weights/trentino.npz --output runs/trentino-checked.npz and compare the output checksum with src/giano/weights/product.json.

Train the two ensemble members

To train with the stopping rounds already selected on development data, run the following command.

uv run --locked giano-train --cache runs/windows --output runs/training --fixed-rounds

Seed 42 runs for 32 rounds and seed 43 for 20. Both start from their original untrained parameters. Each round covers 1,860 sampled windows, with balanced replay of the original and seasonally extended sets. Batches contain up to eight windows. Adam uses a learning rate of 0.001 and gradient clipping limits the norm to 1. The objective averages the mean absolute errors over the supervised variables with measured targets in the batch, after normalising by training scale.

To repeat checkpoint selection, omit --fixed-rounds and choose a new output directory. This fits 36 rounds for each seed, evaluates after each round, includes the initial physical-reference prediction and takes the earliest minimum. The score averages four variable-specific, scale-normalised physical MAEs over the full 2011 cohort and its original 879-window subset. Wind has no learned correction. The protocol's two development curves are included for comparison. The retained pair minimises this aggregate development score. Some individual rainfall and other physical-error criteria worsened at those stopping points.

Training output Contents and use
ensemble.pt The two selected members, ready for inference or evaluation with --ensemble.
training.json Training device, precision, loss by round, development scores when evaluated, selected rounds and the full run’s parameter comparison.
seed-42.pt, seed-43.pt The latest model, Adam optimiser state and best member so far, used to resume training.

To resume after interruption, repeat the original command with --resume. Keep the cache and training mode the same. After fitting both members, the full run compares their tensors with the packaged weights. In training.json, max_parameter_difference_from_release equal to zero for both seeds means every parameter matched. The Python 3.11 CPU verification reproduced all 52 fixed rounds with the same per-round losses and a maximum parameter difference of zero for both seeds. The learner never reads the fitted release weights to initialise or select a member.

Training hardware and precision

The default --device auto selects CUDA first, Apple Metal (MPS) next and CPU otherwise. The trainer prints the choice at startup. To require an accelerator, pass its name explicitly. A request for an unavailable device stops before creating the run directory.

Hardware Trainer options Behaviour
NVIDIA GPU --device cuda Uses fused Adam and mixed bfloat16 for the forward pass on GPUs with native BF16 support. Other CUDA GPUs use float32. Choose --precision fp32 to run the forward pass in float32 on any supported CUDA device.
Mac with an available Metal GPU --device mps Runs the neural network and its gradient updates on the GPU in float32.
Reference CPU run --device cpu --fixed-rounds Uses the original two-thread CPU reductions and stopping rounds used for the published weight comparison.

Check what the project environment can see with uv run --locked python -c "import torch; print('CUDA:', torch.cuda.is_available(), 'MPS:', torch.backends.mps.is_available())". NVIDIA requires a CUDA-enabled PyTorch build and a compatible driver. PyTorch installation selector · PyTorch on Metal

Both accelerator paths use the original batches of eight and the same window order. Validation runs the network in float32 and accumulates physical errors on the CPU in float64. Different devices and precisions can produce different parameters and development scores. Match the original device and precision when resuming an interrupted run. For checkpoints predating device selection, use --device cpu. The exported ensemble.pt contains CPU tensors and can be used by the standard reconstruction command on another machine.

On the Apple Silicon machine used for the training preview, Metal processed 160 windows/s and the two-thread CPU processed 124 windows/s (1.29× throughput). Both used float32, the same eight real training windows and five warm-up steps. The figures are medians of three timed runs of 16 optimiser steps, with GPU work synchronised before stopping the timer. They cover training steps only. CUDA throughput and end-to-end training time were not measured.

Reconstruct real gaps with your weights

Convert a short interval of the Drive dataset into a network NetCDF. Include context on both sides of the day you want to reconstruct.

uv run --locked giano-import-trentino --data data --start 2020-02-20 --end-exclusive 2020-03-15 --output runs/network.nc
uv run --locked giano --input runs/network.nc --trentino-calibration --start 2020-03-01 --end-exclusive 2020-03-02 --variables humidity --ensemble runs/training/ensemble.pt --output runs/humidity.nc

Open the result with xarray. Inspect humidity, humidity_filled, humidity_method and humidity_reference. A finite observation should remain identical in both series. A missing observation can have an estimate or a reason for withholding it. The NetCDF records the SHA-256 digest of the ensemble used. Omit --ensemble to use the official packaged weights. For another network, supply its hourly CSV and station catalogue or its own NetCDF. Input and output

Measure error on known targets

uv run --locked giano-evaluate --data data --ensemble runs/training/ensemble.pt --local-context --station-reference --output runs/evaluation
uv run --locked python examples/evaluate_temperature.py --ensemble runs/training/ensemble.pt

The first command reconstructs the 480 fixed 2020 outages in Trentino with the same two station options used for the website results. Compare its output with examples/trentino/station-context-scores.csv. To reproduce historical-scores.csv, omit both options and choose a separate output directory. It writes episodes.csv (station, date, duration, regime and variable), scores.csv (paired counts and MAEs) and rain-totals.csv (observed and estimated rainfall volume on comparable hours). Missing observations have no scoring target. The frozen target mask records which observations survived the historical quality-code comparison. Calculate pooled MAE by summing absolute errors and dividing by the corresponding total number of paired hours. A cell with zero paired hours has an undefined error.

The second command measures temperature transfer at three Swiss stations in 2024, against linear interpolation on identical hidden hours. It uses the CSVs included in the checkout. Results from these two networks answer different questions. The 2020 dates had been consulted earlier in the project. Model and evidence