File size: 47,451 Bytes
8bcb60f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
---
language: en
tags:
- weather
- time-series
- pytorch
- climate
license: apache-2.0
model-index:
- name: LILITH
  results: []
---

# L.I.L.I.T.H. (Long-range Intelligent Learning for Integrated Trend Hindcasting)

**A lightweight, open-source weather prediction model trained on GHCN data.**

<p align="center">
  <img src="https://img.shields.io/badge/python-3.10+-blue.svg" alt="Python 3.10+">
  <img src="https://img.shields.io/badge/PyTorch-2.1+-ee4c2c.svg" alt="PyTorch">
  <img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License">
</p>

## Model Description

LILITH is a transformer-based weather forecasting model designed to run on consumer hardware (e.g., RTX 3060). It learns from 150+ years of station-based observations (GHCN-Daily) to predict 90-day temperature and precipitation trends with uncertainty quantification.

<p align="center">
  <a href="#why-lilith">Why LILITH</a> β€’
  <a href="#features">Features</a> β€’
  <a href="#quick-start">Quick Start</a> β€’
  <a href="#architecture">Architecture</a> β€’
  <a href="#contributing">Contributing</a>
</p>

---

## The Weather Belongs to Everyone

Every day, corporations charge billions of dollars for weather forecasts built on **freely available public data**. The Global Historical Climatology Network (GHCN)β€”maintained by NOAA with taxpayer fundingβ€”contains over **150 years** of weather observations from **100,000+ stations worldwide**. This data is public domain. It belongs to humanity.

Yet somehow, we've accepted that accurate long-range forecasting should be locked behind enterprise paywalls and proprietary black boxes.

**LILITH exists to change that.**

With a single consumer GPU (RTX 3060, 12GB), you can now train and run a weather prediction model that delivers **90-day forecasts** with uncertainty quantificationβ€”the same capabilities that corporations charge premium prices for. No cloud subscriptions. No API limits. No black boxes.

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                                                                            β”‚
β”‚   "The same public data that corporations use to train billion-dollar     β”‚
β”‚    weather systems is available to anyone with a GPU and curiosity."      β”‚
β”‚                                                                            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### The Data is Free. The Science is Open. The Code is Yours

| What Corporations Charge For | What LILITH Provides Free |
|------------------------------|---------------------------|
| 90-day extended forecasts | 90-day forecasts with uncertainty bands |
| "Proprietary" ML models | Fully transparent architecture |
| Enterprise API access | Self-hosted, unlimited queries |
| Historical climate analytics | 150+ years of GHCN data access |
| Per-query pricing | Run on your own hardware |

---

## Why LILITH

### The Problem

Modern weather AI (GraphCast, Pangu-Weather, FourCastNet) achieves remarkable accuracy, but:

- **Requires ERA5 reanalysis data** β€” computationally expensive to generate, controlled by ECMWF
- **Needs massive compute** β€” training requires hundreds of TPUs/GPUs
- **Inference is heavy** β€” full global models need 80GB+ VRAM
- **Closed ecosystems** β€” weights available, but practical deployment requires significant resources

### The Solution

LILITH takes a different approach:

1. **Station-Native Architecture** β€” Learns directly from sparse GHCN station observations instead of requiring gridded reanalysis
2. **Hierarchical Processing** β€” Graph attention for spatial relationships, spectral methods for global dynamics
3. **Memory Efficient** β€” Gradient checkpointing, INT8/INT4 quantization, runs on consumer GPUs
4. **Truly Open** β€” Apache 2.0 license, reproducible training, no hidden dependencies

---

## Features

### Core Capabilities

- **90-Day Forecasts** β€” Extended-range predictions competitive with commercial services
- **Uncertainty Quantification** β€” Know not just the prediction, but how confident it is
- **150+ Years of Data** β€” Built on the complete GHCN historical record
- **Global Coverage** β€” Forecasts for any location on Earth
- **Multiple Variables** β€” Temperature, precipitation, wind, pressure, humidity

### Technical Highlights

- **Consumer Hardware** β€” Inference on RTX 3060 (12GB), training on RTX 4090 or multi-GPU
- **Horizontally Scalable** β€” From laptop to cluster with Ray Serve
- **Modern Stack** β€” PyTorch 2.x, Flash Attention, DeepSpeed, FastAPI, Next.js 14
- **Production Ready** β€” Docker containers, Redis caching, PostgreSQL + TimescaleDB

### User Experience

- **Glassmorphic UI** β€” Beautiful, modern interface with dynamic weather backgrounds
- **Interactive Maps** β€” Mapbox GL JS with temperature layers and station markers
- **Rich Visualizations** β€” Recharts/D3 for forecasts, uncertainty bands, wind roses
- **Historical Explorer** β€” Analyze 150+ years of climate trends

---

## Quick Start

### Prerequisites

- Python 3.10+
- CUDA-capable GPU (12GB+ VRAM recommended)
- Node.js 18+ (for frontend)

### Quick Start with Pre-trained Model

If you have a trained checkpoint (e.g., `lilith_best.pt`), you can run the full stack immediately:

```bash
# 1. Clone and setup
git clone https://github.com/consigcody94/lilith.git
cd lilith
python -m venv .venv
.venv\Scripts\activate  # Windows
# source .venv/bin/activate  # Linux/Mac

# 2. Install dependencies
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
pip install -e ".[all]"

# 3. Place your checkpoint in the checkpoints folder
mkdir checkpoints
# Copy lilith_best.pt to checkpoints/

# 4. Set OpenWeatherMap API Key (Optional but recommended for live data)
export OPENWEATHER_API_KEY="your_api_key_here"  # Linux/Mac
# set OPENWEATHER_API_KEY=your_api_key_here      # Windows

# 5. Start the API server (auto-detects checkpoint)
python -m uvicorn web.api.main:app --host 127.0.0.1 --port 8000

# 6. In a new terminal, start the frontend
cd web/frontend
npm install
npm run dev

# 7. Open http://localhost:3000 in your browser
```

The API will automatically find and load `checkpoints/lilith_best.pt` or `checkpoints/lilith_final.pt`. You'll see log output like:

```
Found checkpoint at C:\...\checkpoints\lilith_best.pt
Model loaded on cuda
Config: d_model=128, layers=4
Val RMSE: 3.96Β°C
Model loaded successfully (RMSE: 3.96Β°C)
```

**Test the API directly:**

```bash
curl -X POST http://127.0.0.1:8000/v1/forecast \
  -H "Content-Type: application/json" \
  -d '{"latitude": 40.7128, "longitude": -74.006, "days": 14}'
```

### Installation

```bash
# Clone the repository
git clone https://github.com/consigcody94/lilith.git
cd lilith

# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate  # Linux/Mac
# .venv\Scripts\activate   # Windows

# Install with all dependencies
pip install -e ".[all]"
```

### Download Data

```bash
# Download GHCN-Daily station data
python scripts/download_data.py --source ghcn-daily --stations 5000 --years 50

# Process and prepare for training
python scripts/process_data.py --config configs/data/default.yaml
```

### Training

LILITH training is designed to work on consumer GPUs. Here's a complete step-by-step guide:

#### Step 1: Environment Setup

```bash
# Create and activate virtual environment
python -m venv .venv
.venv\Scripts\activate  # Windows
# source .venv/bin/activate  # Linux/Mac

# Install PyTorch with CUDA support
# For RTX 30/40 series:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121

# For RTX 50 series (Blackwell - requires nightly):
pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu128

# Install LILITH dependencies
pip install -e ".[all]"
```

#### Step 2: Download Training Data

```bash
# Download GHCN station data (start with 300 stations for quick training)
python -m data.download.ghcn_daily \
    --stations 300 \
    --min-years 30 \
    --country US

# For better models, download more stations
python -m data.download.ghcn_daily \
    --stations 5000 \
    --min-years 20 \
    --elements TMAX,TMIN,PRCP

# Download climate indices for long-range prediction
python -m data.download.climate_indices --all
```

#### Step 3: Process Data

```bash
# Process raw GHCN data into training format
python -m data.processing.ghcn_processor

# This creates:
# - data/processed/ghcn_combined.parquet (all station data)
# - data/processed/training/X.npy (input sequences)
# - data/processed/training/Y.npy (target sequences)
# - data/processed/training/meta.npy (station metadata)
# - data/processed/training/stats.npz (normalization stats)
```

#### Step 4: Train the Model

```bash
# Quick training (30 epochs, good for testing)
python -m training.train_simple \
    --epochs 30 \
    --batch-size 64 \
    --d-model 128 \
    --layers 4

# Full training (100 epochs, production quality)
python -m training.train_simple \
    --epochs 100 \
    --batch-size 128 \
    --d-model 256 \
    --layers 6 \
    --lr 1e-4

# Resume training from checkpoint
python -m training.train_simple \
    --resume checkpoints/lilith_best.pt \
    --epochs 50
```

#### Step 5: Monitor Training

During training, you'll see output like:

```
Epoch 1/30 | Train Loss: 0.8234 | Val Loss: 0.7891 | Temp RMSE: 4.21Β°C | Temp MAE: 3.15Β°C
Epoch 2/30 | Train Loss: 0.6543 | Val Loss: 0.6234 | Temp RMSE: 3.45Β°C | Temp MAE: 2.67Β°C
...
Epoch 30/30 | Train Loss: 0.2134 | Val Loss: 0.2456 | Temp RMSE: 1.89Β°C | Temp MAE: 1.42Β°C
```

Target metrics:

- **Days 1-7**: Temp RMSE < 2Β°C
- **Days 8-14**: Temp RMSE < 3Β°C

#### Step 6: Use the Trained Model

```bash
# Update the API to use your trained model
# Edit web/api/main.py and set DEMO_MODE = False

# Or run inference directly
python -m inference.forecast \
    --checkpoint checkpoints/lilith_best.pt \
    --lat 40.7128 --lon -74.006 \
    --days 90
```

#### Training on Multiple GPUs

```bash
# Using PyTorch DistributedDataParallel
torchrun --nproc_per_node=2 training/train_distributed.py \
    --config models/configs/large.yaml

# Using DeepSpeed for memory efficiency
deepspeed --num_gpus=4 training/train_deepspeed.py \
    --config models/configs/xl.yaml \
    --deepspeed configs/training/ds_config.json
```

#### Memory Requirements

| Model Size | Batch Size | VRAM Required |
|------------|------------|---------------|
| d_model=128 | 64 | ~4 GB |
| d_model=256 | 64 | ~8 GB |
| d_model=256 | 128 | ~12 GB |
| d_model=512 | 64 | ~16 GB |

#### Training Tips

1. **Start small**: Train with 300 stations first to verify everything works
2. **Monitor GPU usage**: Use `nvidia-smi` to ensure GPU is being utilized
3. **Watch for overfitting**: If val loss increases while train loss decreases, reduce epochs
4. **Save checkpoints**: The best model is automatically saved to `checkpoints/lilith_best.pt`
5. **Use mixed precision**: Enabled by default (FP16), cuts memory usage in half

---

## Pre-trained Models

### Using Pre-trained Checkpoints

Once a model is trained, you **do not need to retrain** β€” the checkpoint file contains everything needed for inference. Anyone can download and use pre-trained models.

#### Checkpoint File Contents

The `.pt` checkpoint file (~20-50MB depending on model size) contains:

```python
checkpoint = {
    'epoch': 20,                    # Training epoch when saved
    'model_state_dict': {...},      # All learned weights
    'optimizer_state_dict': {...},  # Optimizer state (for resuming training)
    'val_loss': 0.2456,             # Validation loss at checkpoint
    'val_rmse': 1.89,               # Temperature RMSE in Β°C
    'config': {                      # Model architecture config
        'input_features': 3,
        'output_features': 3,
        'd_model': 128,
        'nhead': 4,
        'num_encoder_layers': 4,
        'num_decoder_layers': 4,
        'dropout': 0.1
    },
    'normalization': {              # Data normalization stats
        'X_mean': [...],
        'X_std': [...],
        'Y_mean': [...],
        'Y_std': [...]
    }
}
```

#### Pre-trained Checkpoint Included

A pre-trained checkpoint (`lilith_best.pt`) is included in the `checkpoints/` folder. This model was trained on:

- **915,000 sequences** from 300 US GHCN stations
- **20 epochs** of training
- **Validation RMSE: 3.96Β°C**

You can use this checkpoint immediately or train your own model with different data/parameters.

#### Model Specifications

| Model | Parameters | File Size | VRAM (Inference) | Best For |
|-------|------------|-----------|------------------|----------|
| **SimpleLILITH** | 1.87M | ~23 MB | 2-4 GB | Default model, fast training |
| **lilith-base** | 150M | ~45 MB | 4 GB | Balanced accuracy/speed |
| **lilith-large** | 400M | ~120 MB | 8 GB | High accuracy |

### GPU Requirements for Inference

Unlike training, inference requires much less VRAM. Here's what you can run on different hardware:

| GPU | VRAM | Models Supported | Batch Size | Latency (90-day forecast) |
|-----|------|------------------|------------|---------------------------|
| **RTX 3050/4050** | 4 GB | Tiny, Base (INT8) | 1 | ~1.5 sec |
| **RTX 3060/4060** | 8 GB | Tiny, Base, Large (INT8) | 1-4 | ~0.8 sec |
| **RTX 3070/4070** | 8-12 GB | All models (FP16) | 4-8 | ~0.5 sec |
| **RTX 3080/4080** | 10-16 GB | All models (FP16) | 8-16 | ~0.3 sec |
| **RTX 3090/4090** | 24 GB | All models, ensembles | 32+ | ~0.2 sec |
| **RTX 5050** | 8.5 GB | Tiny, Base, Large (INT8) | 1-4 | ~0.6 sec |
| **CPU Only** | N/A | All models (slow) | 1 | ~10-30 sec |

#### Quantization for Smaller GPUs

```bash
# Convert to INT8 for 50% memory reduction
python -m inference.quantize \
    --checkpoint checkpoints/lilith_base.pt \
    --output checkpoints/lilith_base_int8.pt \
    --precision int8

# Convert to INT4 for 75% memory reduction (slight accuracy loss)
python -m inference.quantize \
    --checkpoint checkpoints/lilith_base.pt \
    --output checkpoints/lilith_base_int4.pt \
    --precision int4
```

### Loading and Using a Checkpoint

#### Python API

```python
import torch
from models.lilith import SimpleLILITH

# Load checkpoint
checkpoint = torch.load('checkpoints/lilith_best.pt', map_location='cuda')

# Recreate model from config
model = SimpleLILITH(**checkpoint['config'])
model.load_state_dict(checkpoint['model_state_dict'])
model.eval()

# Get normalization stats
X_mean = torch.tensor(checkpoint['normalization']['X_mean'])
X_std = torch.tensor(checkpoint['normalization']['X_std'])
Y_mean = torch.tensor(checkpoint['normalization']['Y_mean'])
Y_std = torch.tensor(checkpoint['normalization']['Y_std'])

# Run inference
with torch.no_grad():
    # Normalize input
    X_norm = (X - X_mean) / X_std

    # Predict
    pred = model(X_norm, meta, target_len=14)

    # Denormalize output
    pred_denorm = pred * Y_std + Y_mean
```

#### Command Line

```bash
# Single location forecast
python -m inference.forecast \
    --checkpoint checkpoints/lilith_best.pt \
    --lat 40.7128 --lon -74.006 \
    --days 90 \
    --output forecast.json

# Batch inference for multiple locations
python -m inference.forecast \
    --checkpoint checkpoints/lilith_best.pt \
    --locations-file locations.csv \
    --days 90 \
    --output forecasts/
```

#### Start API Server with Trained Model

```bash
# Set checkpoint path
export LILITH_CHECKPOINT=checkpoints/lilith_best.pt

# Start API (will use trained model instead of demo mode)
python -m web.api.main

# Or specify directly
python -m uvicorn web.api.main:app --host 0.0.0.0 --port 8000
```

### Sharing Your Trained Model

#### Upload to HuggingFace Hub

```python
from huggingface_hub import HfApi

api = HfApi()
api.upload_file(
    path_or_fileobj="checkpoints/lilith_best.pt",
    path_in_repo="lilith_base_v1.pt",
    repo_id="your-username/lilith-base",
    repo_type="model"
)
```

#### Create a GitHub Release

```bash
# Tag your release
git tag -a v1.0 -m "LILITH Base v1.0 - Trained on 915K sequences"
git push origin v1.0

# Upload checkpoint to release (via GitHub UI or gh cli)
gh release create v1.0 checkpoints/lilith_best.pt --title "LILITH v1.0"
```

### Model Training Metrics

When training completes, you'll see metrics like:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    LILITH TRAINING COMPLETE                    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Epochs: 20                                                    β”‚
β”‚  Training Samples: 915,001                                     β”‚
β”‚  Final Train Loss: 0.2134                                      β”‚
β”‚  Final Val Loss: 0.2456                                        β”‚
β”‚  Temperature RMSE: 1.89Β°C                                      β”‚
β”‚  Temperature MAE: 1.42Β°C                                       β”‚
β”‚  Checkpoint: checkpoints/lilith_best.pt (22.8 MB)              β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Model Config:                                                 β”‚
β”‚    - Parameters: 1,869,251                                     β”‚
β”‚    - d_model: 128                                              β”‚
β”‚    - Attention Heads: 4                                        β”‚
β”‚    - Encoder Layers: 4                                         β”‚
β”‚    - Decoder Layers: 4                                         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Resuming Training

```bash
# Continue training from checkpoint
python -m training.train_simple \
    --resume checkpoints/lilith_best.pt \
    --epochs 50 \
    --lr 5e-5  # Lower learning rate for fine-tuning

# The checkpoint includes optimizer state, so training continues smoothly
```

### Model Comparison

| Checkpoint | Epochs | Training Data | Val RMSE | File Size | Notes |
|------------|--------|---------------|----------|-----------|-------|
| `lilith_v0.1.pt` | 10 | 100K samples | 4.3Β°C | 22 MB | Quick test |
| `lilith_v0.5.pt` | 30 | 500K samples | 2.8Β°C | 22 MB | Development |
| `lilith_v1.0.pt` | 100 | 915K samples | 1.9Β°C | 22 MB | Production |
| `lilith_large_v1.pt` | 100 | 2M samples | 1.5Β°C | 120 MB | Best accuracy |

---

### Inference

```bash
# Generate a forecast
python scripts/run_inference.py \
    --checkpoint checkpoints/best.pt \
    --lat 40.7128 --lon -74.006 \
    --days 90

# Start the API server
python scripts/start_api.py --checkpoint checkpoints/best.pt --port 8000

# Query the API
curl -X POST http://localhost:8000/v1/forecast \
  -H "Content-Type: application/json" \
  -d '{"latitude": 40.7128, "longitude": -74.006, "days": 90}'
```

### Web Interface

```bash
cd web/frontend
npm install
npm run dev
# Open http://localhost:3000
```

### Docker Deployment

```bash
# Full stack deployment
docker-compose -f docker/docker-compose.yml up -d

# Individual services
docker build -f docker/Dockerfile.inference -t lilith-inference .
docker build -f docker/Dockerfile.web -t lilith-web .
```

---

## Architecture

### Model Overview

LILITH uses a **Station-Graph Temporal Transformer (SGTT)** architecture that processes weather observations through three stages:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                            LILITH ARCHITECTURE                              β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                                             β”‚
β”‚  INPUT: Station Observations                                                β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  β€’ 100,000+ GHCN stations worldwide                                 β”‚   β”‚
β”‚  β”‚  β€’ Temperature, precipitation, pressure, wind, humidity             β”‚   β”‚
β”‚  β”‚  β€’ Quality-controlled, gap-filled, normalized                       β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                    β”‚                                        β”‚
β”‚                                    β–Ό                                        β”‚
β”‚  ENCODER ──────────────────────────────────────────────────────────────    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”‚
β”‚  β”‚   Station    │──▢│  Graph Attention │──▢│ Temporal Transformer   β”‚      β”‚
β”‚  β”‚  Embedding   β”‚   β”‚   Network v2     β”‚   β”‚   (Flash Attention)    β”‚      β”‚
β”‚  β”‚              β”‚   β”‚                  β”‚   β”‚                        β”‚      β”‚
β”‚  β”‚  β€’ 3D pos    β”‚   β”‚  β€’ Spatial       β”‚   β”‚  β€’ Historical context  β”‚      β”‚
β”‚  β”‚  β€’ Features  β”‚   β”‚    correlations  β”‚   β”‚  β€’ Causal masking      β”‚      β”‚
β”‚  β”‚  β€’ Temporal  β”‚   β”‚  β€’ Multi-hop     β”‚   β”‚  β€’ RoPE embeddings     β”‚      β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚
β”‚                                    β”‚                                        β”‚
β”‚                                    β–Ό                                        β”‚
β”‚                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                       β”‚
β”‚                    β”‚   LATENT ATMOSPHERIC STATE    β”‚                       β”‚
β”‚                    β”‚      (64 Γ— 128 Γ— 256)         β”‚                       β”‚
β”‚                    β”‚                               β”‚                       β”‚
β”‚                    β”‚   Learned global grid that    β”‚                       β”‚
β”‚                    β”‚   captures atmospheric        β”‚                       β”‚
β”‚                    β”‚   dynamics implicitly         β”‚                       β”‚
β”‚                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                       β”‚
β”‚                                    β”‚                                        β”‚
β”‚                                    β–Ό                                        β”‚
β”‚  PROCESSOR ────────────────────────────────────────────────────────────    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚              Spherical Fourier Neural Operator (SFNO)               β”‚   β”‚
β”‚  β”‚                                                                     β”‚   β”‚
β”‚  β”‚   β€’ Operates in spectral domain on sphere                          β”‚   β”‚
β”‚  β”‚   β€’ Captures global teleconnections (ENSO, NAO, etc.)              β”‚   β”‚
β”‚  β”‚   β€’ Respects Earth's spherical geometry                            β”‚   β”‚
β”‚  β”‚   β€’ Efficient O(N log N) via spherical harmonics                   β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚              Multi-Scale Temporal Processor                         β”‚   β”‚
β”‚  β”‚                                                                     β”‚   β”‚
β”‚  β”‚   Days 1-14:   6-hour steps  (synoptic weather)                    β”‚   β”‚
β”‚  β”‚   Days 15-42:  24-hour steps (weekly patterns)                     β”‚   β”‚
β”‚  β”‚   Days 43-90:  168-hour steps (seasonal trends)                    β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚              Climate Embedding Module                               β”‚   β”‚
β”‚  β”‚                                                                     β”‚   β”‚
β”‚  β”‚   β€’ ENSO index (El NiΓ±o/La NiΓ±a state)                             β”‚   β”‚
β”‚  β”‚   β€’ MJO phase and amplitude                                        β”‚   β”‚
β”‚  β”‚   β€’ NAO, AO, PDO indices                                           β”‚   β”‚
β”‚  β”‚   β€’ Seasonal cycles, solar position                                β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                    β”‚                                        β”‚
β”‚                                    β–Ό                                        β”‚
β”‚  DECODER ──────────────────────────────────────────────────────────────    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”            β”‚
β”‚  β”‚    Grid Decoder      β”‚              β”‚   Station Decoder    β”‚            β”‚
β”‚  β”‚                      β”‚              β”‚                      β”‚            β”‚
β”‚  β”‚  β€’ Global fields     β”‚              β”‚  β€’ Point forecasts   β”‚            β”‚
β”‚  β”‚  β€’ Spatial upsamplingβ”‚              β”‚  β€’ Location-specific β”‚            β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜            β”‚
β”‚                    β”‚                              β”‚                         β”‚
β”‚                    β–Ό                              β–Ό                         β”‚
β”‚  OUTPUT ───────────────────────────────────────────────────────────────    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚                     Ensemble Head (Optional)                        β”‚   β”‚
β”‚  β”‚                                                                     β”‚   β”‚
β”‚  β”‚   β€’ Diffusion-based ensemble generation                            β”‚   β”‚
β”‚  β”‚   β€’ Gaussian, quantile, or MC dropout uncertainty                  β”‚   β”‚
β”‚  β”‚   β€’ Calibrated confidence intervals                                β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                                             β”‚
β”‚  FINAL OUTPUT:                                                              β”‚
β”‚  β€’ 90-day forecasts for temperature, precipitation, wind, pressure         β”‚
β”‚  β€’ Uncertainty bounds (5th, 25th, 50th, 75th, 95th percentiles)           β”‚
β”‚  β€’ Ensemble spread metrics                                                 β”‚
β”‚                                                                             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Model Variants

| Variant | Parameters | VRAM (FP16) | VRAM (INT8) | Best For |
|---------|------------|-------------|-------------|----------|
| **LILITH-Tiny** | 50M | 4 GB | 2 GB | Fast inference, edge deployment |
| **LILITH-Base** | 150M | 8 GB | 4 GB | Balanced accuracy/speed |
| **LILITH-Large** | 400M | 12 GB | 6 GB | High accuracy forecasts |
| **LILITH-XL** | 1B | 24 GB | 12 GB | Research, maximum accuracy |

### Key Components

| Component | Purpose | Implementation |
|-----------|---------|----------------|
| `StationEmbedding` | Encode station features + position | MLP with 3D spherical coordinates |
| `GATEncoder` | Learn spatial relationships | Graph Attention Network v2 |
| `TemporalTransformer` | Process time series | Flash Attention with RoPE |
| `SFNO` | Global atmospheric dynamics | Spherical Fourier Neural Operator |
| `ClimateEmbedding` | Encode climate indices | ENSO, MJO, NAO, seasonal |
| `EnsembleHead` | Uncertainty quantification | Diffusion / Gaussian / Quantile |

---

## Data Sources

LILITH is built entirely on **freely available public data**. The more data sources you integrate, the better your predictions will be.

### Primary: GHCN (Global Historical Climatology Network)

| Dataset | Coverage | Stations | Variables | Resolution |
|---------|----------|----------|-----------|------------|
| **GHCN-Daily** | 1763–present | 100,000+ | Temp, Precip, Snow | Daily |
| **GHCN-Hourly** | 1900s–present | 20,000+ | Wind, Pressure, Humidity | Hourly |
| **GHCN-Monthly** | 1700s–present | 26,000 | Temp, Precip | Monthly |

**Source**: [NOAA National Centers for Environmental Information](https://www.ncei.noaa.gov/products/land-based-station/global-historical-climatology-network-daily)

### Recommended Additional Data Sources

These freely available datasets can significantly improve prediction accuracy:

#### 1. ERA5 Reanalysis (Highly Recommended)

| Dataset | Coverage | Resolution | Variables |
|---------|----------|------------|-----------|
| **ERA5** | 1940–present | 0.25Β° / hourly | Full atmospheric state (temperature, wind, humidity, pressure at all levels) |

**Source**: [ECMWF Climate Data Store](https://cds.climate.copernicus.eu/)

- Provides gridded global data interpolated from observations
- Excellent for learning atmospheric dynamics
- ~2TB for 10 years of data at full resolution

#### 2. Climate Indices (Essential for Long-Range)

| Index | Description | Impact |
|-------|-------------|--------|
| **ENSO (ONI)** | El NiΓ±o/La NiΓ±a state | Major driver of global weather patterns |
| **NAO** | North Atlantic Oscillation | European/North American winter weather |
| **PDO** | Pacific Decadal Oscillation | Long-term Pacific climate cycles |
| **MJO** | Madden-Julian Oscillation | Tropical weather, 30-60 day cycles |
| **AO** | Arctic Oscillation | Northern Hemisphere cold outbreaks |

**Source**: [NOAA Climate Prediction Center](https://www.cpc.ncep.noaa.gov/)

```bash
# Download climate indices
python -m data.download.climate_indices --indices enso,nao,pdo,mjo,ao
```

#### 3. Sea Surface Temperature (SST)

| Dataset | Coverage | Resolution |
|---------|----------|------------|
| **NOAA OISST** | 1981–present | 0.25Β° / daily |
| **HadISST** | 1870–present | 1Β° / monthly |

**Source**: [NOAA OISST](https://www.ncei.noaa.gov/products/optimum-interpolation-sst)

- Ocean temperatures strongly influence atmospheric patterns
- Critical for predicting precipitation and temperature anomalies

#### 4. NOAA GFS Model Data

| Dataset | Forecast Range | Resolution |
|---------|----------------|------------|
| **GFS Analysis** | Historical | 0.25Β° / 6-hourly |
| **GFS Forecasts** | 16 days | 0.25Β° / hourly |

**Source**: [NOAA NOMADS](https://nomads.ncep.noaa.gov/)

- Use as additional training signal or for ensemble weighting
- Can blend ML predictions with physics-based forecasts

#### 5. Satellite Data

| Dataset | Variables | Coverage |
|---------|-----------|----------|
| **GOES-16/17/18** | Cloud cover, precipitation | Americas |
| **NASA GPM** | Global precipitation | Global |
| **MODIS** | Land surface temperature | Global |

**Sources**:

- [NOAA CLASS](https://www.class.noaa.gov/)
- [NASA Earthdata](https://earthdata.nasa.gov/)

#### 6. Additional Reanalysis Products

| Dataset | Coverage | Best For |
|---------|----------|----------|
| **NASA MERRA-2** | 1980–present | North America |
| **NCEP/NCAR Reanalysis** | 1948–present | Historical coverage |
| **JRA-55** | 1958–present | Pacific/Asia region |

### Data Download Commands

```bash
# Download all recommended data sources
python -m data.download.all \
    --ghcn-stations 5000 \
    --era5-years 20 \
    --climate-indices all \
    --sst oisst \
    --region north_america

# Download just climate indices (small, fast)
python -m data.download.climate_indices

# Download ERA5 for specific region (requires CDS account)
python -m data.download.era5 \
    --start-year 2000 \
    --end-year 2024 \
    --region "north_america" \
    --variables temperature,wind,humidity,pressure
```

### Data Integration Priority

For the best results, add data sources in this order:

1. **GHCN-Daily** (required) - Station observations
2. **Climate Indices** (highly recommended) - ENSO, NAO, MJO for long-range skill
3. **ERA5** (recommended) - Full atmospheric state for dynamics
4. **SST** (recommended) - Ocean influence on weather
5. **Satellite** (optional) - Real-time cloud/precip data

---

## Performance

### Accuracy Targets

| Forecast Range | Metric | LILITH Target | Climatology |
|----------------|--------|---------------|-------------|
| Days 1-7 | Temperature RMSE | < 2Β°C | ~5Β°C |
| Days 8-14 | Temperature RMSE | < 3Β°C | ~5Β°C |
| Days 15-42 | Skill Score | > 0.3 | 0.0 |
| Days 43-90 | Skill Score | > 0.1 | 0.0 |

### Inference Performance (RTX 3060 12GB)

| Model | Single Location | Regional Grid | Global |
|-------|-----------------|---------------|--------|
| LILITH-Tiny (INT8) | 0.3s | 2s | 15s |
| LILITH-Base (INT8) | 0.8s | 5s | 45s |
| LILITH-Large (FP16) | 1.5s | 12s | 90s |

---

## Project Structure

```
lilith/
β”œβ”€β”€ data/                       # Data pipeline
β”‚   β”œβ”€β”€ download/               # GHCN download scripts
β”‚   β”‚   β”œβ”€β”€ ghcn_daily.py       # Daily observations
β”‚   β”‚   └── ghcn_hourly.py      # Hourly observations
β”‚   β”œβ”€β”€ processing/             # Data processing
β”‚   β”‚   β”œβ”€β”€ quality_control.py  # Outlier detection, QC flags
β”‚   β”‚   β”œβ”€β”€ feature_encoder.py  # Normalization, encoding
β”‚   β”‚   └── gridding.py         # Station β†’ grid interpolation
β”‚   └── loaders/                # PyTorch datasets
β”‚       β”œβ”€β”€ station_dataset.py  # Station-based loading
β”‚       └── forecast_dataset.py # Forecast sequence loading
β”‚
β”œβ”€β”€ models/                     # Model architecture
β”‚   β”œβ”€β”€ components/             # Building blocks
β”‚   β”‚   β”œβ”€β”€ station_embed.py    # Station feature embedding
β”‚   β”‚   β”œβ”€β”€ gat_encoder.py      # Graph Attention Network
β”‚   β”‚   β”œβ”€β”€ temporal_transformer.py  # Temporal processing
β”‚   β”‚   β”œβ”€β”€ sfno.py             # Spherical Fourier Neural Operator
β”‚   β”‚   β”œβ”€β”€ climate_embed.py    # Climate indices embedding
β”‚   β”‚   └── ensemble_head.py    # Uncertainty quantification
β”‚   β”œβ”€β”€ lilith.py               # Main model class
β”‚   β”œβ”€β”€ losses.py               # Multi-task loss functions
β”‚   └── configs/                # Model configurations
β”‚       β”œβ”€β”€ tiny.yaml
β”‚       β”œβ”€β”€ base.yaml
β”‚       └── large.yaml
β”‚
β”œβ”€β”€ training/                   # Training infrastructure
β”‚   └── trainer.py              # Training loop with DeepSpeed
β”‚
β”œβ”€β”€ inference/                  # Inference and serving
β”‚   β”œβ”€β”€ forecast.py             # High-level forecast API
β”‚   └── quantize.py             # INT8/INT4 quantization
β”‚
β”œβ”€β”€ web/
β”‚   β”œβ”€β”€ api/                    # FastAPI backend
β”‚   β”‚   β”œβ”€β”€ main.py             # Application entry point
β”‚   β”‚   └── schemas.py          # Pydantic models
β”‚   └── frontend/               # Next.js 14 frontend
β”‚       └── src/
β”‚           β”œβ”€β”€ app/            # App Router pages
β”‚           β”œβ”€β”€ components/     # React components
β”‚           └── stores/         # Zustand state
β”‚
β”œβ”€β”€ scripts/                    # CLI utilities
β”‚   β”œβ”€β”€ download_data.py
β”‚   β”œβ”€β”€ process_data.py
β”‚   β”œβ”€β”€ train_model.py
β”‚   β”œβ”€β”€ run_inference.py
β”‚   └── start_api.py
β”‚
β”œβ”€β”€ tests/                      # Test suite
β”‚   β”œβ”€β”€ test_models.py
β”‚   β”œβ”€β”€ test_data.py
β”‚   └── test_api.py
β”‚
β”œβ”€β”€ docker/                     # Containerization
β”‚   β”œβ”€β”€ Dockerfile.inference
β”‚   β”œβ”€β”€ Dockerfile.web
β”‚   └── docker-compose.yml
β”‚
└── docs/                       # Documentation
    └── architecture.md
```

---

## API Reference

### Endpoints

#### `POST /v1/forecast`

Generate a weather forecast for a location.

```json
{
  "latitude": 40.7128,
  "longitude": -74.006,
  "days": 90,
  "ensemble_members": 10,
  "variables": ["temperature", "precipitation", "wind"]
}
```

**Response:**

```json
{
  "location": {"latitude": 40.7128, "longitude": -74.006, "name": "New York, NY"},
  "generated_at": "2025-01-15T12:00:00Z",
  "model_version": "lilith-base-v1.0",
  "forecasts": [
    {
      "date": "2025-01-16",
      "temperature": {"mean": 2.5, "min": -1.2, "max": 6.8},
      "precipitation": {"probability": 0.35, "amount_mm": 2.1},
      "wind": {"speed_ms": 5.2, "direction_deg": 270},
      "uncertainty": {"temperature_std": 1.2, "confidence": 0.85}
    }
  ]
}
```

#### `GET /v1/historical/{station_id}`

Retrieve historical observations for a station.

#### `GET /health`

Health check endpoint.

---

## Contributing

We welcome contributions from the community. LILITH is built on the principle that weather forecasting should be accessible to everyone, and that means building in the open with help from anyone who shares that vision.

### Ways to Contribute

- **Code**: Model improvements, new features, bug fixes
- **Data**: Additional data sources, quality control improvements
- **Documentation**: Tutorials, guides, API documentation
- **Testing**: Unit tests, integration tests, benchmarking
- **Design**: UI/UX improvements, visualizations

### Development Setup

```bash
# Fork and clone (replace with your username if you fork)
git clone https://github.com/consigcody94/lilith.git
cd lilith

# Install development dependencies
pip install -e ".[dev]"

# Install pre-commit hooks
pre-commit install

# Run tests
pytest tests/ -v

# Run linting
ruff check .
mypy .
```

### Pull Request Process

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Run tests and linting
5. Commit with clear messages
6. Push and open a Pull Request

---

## Acknowledgments

### U.S. Government AI Initiatives

We thank **President Donald Trump** and his administration for the **Stargate AI Initiative** and commitment to advancing American AI research and infrastructure. The recognition that AI developmentβ€”including open-source projects like LILITHβ€”represents a critical frontier for innovation, economic growth, and global competitiveness has helped create an environment where ambitious projects like this can flourish. The initiative's focus on building domestic AI capabilities and infrastructure supports the democratization of advanced technologies for all Americans.

### Data Providers

- **NOAA NCEI** β€” For maintaining the invaluable GHCN dataset as a public resource funded by U.S. taxpayers
- **ECMWF** β€” For ERA5 reanalysis data

### Research Community

- **GraphCast** (Google DeepMind) β€” Pioneering ML weather prediction
- **Pangu-Weather** (Huawei) β€” Advancing transformer architectures for weather
- **FourCastNet** (NVIDIA) β€” Demonstrating Fourier neural operators for atmospheric modeling
- **FuXi** (Fudan University) β€” Pushing boundaries in subseasonal forecasting

### Open Source

- PyTorch team for the deep learning framework
- Hugging Face for model hosting infrastructure
- The countless contributors to the Python scientific computing ecosystem

---

## Configuration

### Environment Variables

Copy `.env.example` to `.env` and configure:

```bash
cp .env.example .env
```

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `OPENWEATHER_API_KEY` | Yes (for live data) | `YOUR_OPENWEATHER_API_KEY_HERE` | Free API key from [OpenWeatherMap](https://openweathermap.org/api) |
| `LILITH_CHECKPOINT` | No | Auto-detected | Path to trained model checkpoint |

### Getting an OpenWeatherMap API Key

1. Sign up at [OpenWeatherMap](https://openweathermap.org/users/sign_up) (free)
2. Go to [API Keys](https://home.openweathermap.org/api_keys)
3. Copy your API key
4. Set the environment variable:

```bash
# Linux/Mac
export OPENWEATHER_API_KEY="your_key_here"

# Windows PowerShell
$env:OPENWEATHER_API_KEY="your_key_here"

# Windows CMD
set OPENWEATHER_API_KEY=your_key_here
```

### Using the Pre-trained Model

A pre-trained model is available in the releases. This model was trained on:

- **505 US GHCN stations** with 9.6 million weather records
- **1.15 million training sequences**
- **10 epochs** of training (~5 hours on CPU, ~1 hour on GPU)
- **Final RMSE: 3.88Β°C** (temperature prediction accuracy)

Download and use:

```bash
# Download from releases
curl -L -o checkpoints/lilith_best.pt https://github.com/consigcody94/lilith/releases/download/v1.0/lilith_best.pt

# Start with the model
LILITH_CHECKPOINT=checkpoints/lilith_best.pt python -m uvicorn web.api.main:app --port 8000
```

### Live Data & Caching

LILITH fetches live data from external APIs. To avoid hitting rate limits:

#### OpenWeatherMap (Forecast Adjustments)

- **Source**: api.openweathermap.org
- **Cache**: 15 minutes per location
- **Rate Limit**: 1,000 calls/day on free tier
- Used for fallback forecasts when ML model is unavailable

To disable live data fetching entirely and use only the ML model:

```python
# In web/api/main.py, set _weather_service to None
_weather_service = None  # Disables OpenWeatherMap calls
```

### Running Without API Keys

If you don't want to set up API keys, the app will still work but with limited features:

| Feature | With API Key | Without API Key |
|---------|--------------|-----------------|
| ML Forecasts | βœ… Full functionality | βœ… Full functionality |
| Fallback Forecasts | βœ… OWM-based | ❌ Error if model not loaded |

### Data Directory Structure

```
data/
β”œβ”€β”€ raw/
β”‚   └── ghcn_daily/           # Downloaded GHCN station files
β”‚       β”œβ”€β”€ stations/         # .dly files (gitignored)
β”‚       β”œβ”€β”€ ghcnd-stations.txt
β”‚       └── ghcnd-inventory.txt
β”œβ”€β”€ processed/
β”‚   └── training/             # Processed training data (gitignored)
β”‚       β”œβ”€β”€ X.npy             # Input sequences
β”‚       β”œβ”€β”€ Y.npy             # Target sequences
β”‚       └── stats.npz         # Normalization stats
└── training_stations.json    # Station coordinates (500+ stations)

checkpoints/
β”œβ”€β”€ lilith_best.pt            # Best model checkpoint
└── lilith_*.pt               # Other checkpoints (gitignored)
```

### Avoiding Data Re-downloads

Training data is cached locally. To avoid re-downloading on every build:

```bash
# Check if data exists before downloading
if [ ! -d "data/raw/ghcn_daily/stations" ]; then
    python scripts/download_data.py --max-stations 500
fi

# Or use the --skip-existing flag
python scripts/download_data.py --max-stations 500 --skip-existing
```

---

## License

```
Copyright 2025 LILITH Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

---

## Citation

If you use LILITH in your research, please cite:

```bibtex
@software{lilith2025,
  author = {LILITH Contributors},
  title = {LILITH: Long-range Intelligent Learning for Integrated Trend Hindcasting},
  year = {2025},
  url = {https://github.com/consigcody94/lilith}
}
```

---

<p align="center">
  <br>
  <em>"The storm goddess sees all horizons."</em>
  <br><br>
  <strong>Weather prediction should be free. The data is public. The science is open. Now the tools are too.</strong>
</p>