s42chen commited on
Commit
4c73eec
·
verified ·
1 Parent(s): 6eaa2dc

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/EXPERIMENTS.md +219 -0
  2. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/infer.sh +4 -0
  3. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/model.py +142 -0
  4. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/model_manifest.json +129 -0
  5. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/provenance/data.py +71 -0
  6. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/provenance/train.py +59 -0
  7. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/ts_io.py +433 -0
  8. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/validation_report.json +0 -0
  9. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/EXPERIMENTS.md +424 -0
  10. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/README.md +5 -0
  11. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/config.json +9 -0
  12. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/infer.sh +4 -0
  13. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/model.py +142 -0
  14. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/model_manifest.json +137 -0
  15. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/continuation/data.py +71 -0
  16. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/continuation/train.py +70 -0
  17. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/data.py +71 -0
  18. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/pack.py +56 -0
  19. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/train.py +59 -0
  20. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/requirements.txt +12 -0
  21. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/seasonal.py +38 -0
  22. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/ts_io.py +433 -0
  23. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/validation_report.json +0 -0
  24. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/direct_large/model.py +142 -0
  25. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/large_corpus/data.py +73 -0
  26. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/large_corpus/model.py +171 -0
  27. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/large_corpus/train.py +73 -0
  28. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/partial_targets/model.py +180 -0
  29. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S028/provenance/member0/training/large_sign/model.py +154 -0
  30. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S028/provenance/member1/training/patch16/pack.py +56 -0
  31. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/direct_large/pack.py +56 -0
  32. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/large_sign/pack.py +56 -0
  33. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/long_memory_synth/model.py +180 -0
  34. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/partial_targets/train.py +73 -0
  35. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/patch16/data.py +72 -0
  36. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/README.md +21 -0
  37. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/infer.sh +4 -0
  38. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/confidence_query/data.py +72 -0
  39. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/confidence_query/model.py +190 -0
  40. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/confidence_query/train.py +54 -0
  41. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/direct_large/data.py +71 -0
  42. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/direct_large/model.py +142 -0
  43. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/direct_large/pack.py +56 -0
  44. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/direct_large/train.py +67 -0
  45. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/full_paired/data.py +94 -0
  46. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/full_paired/model.py +204 -0
  47. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/horizon_jitter/data.py +86 -0
  48. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/horizon_jitter/model.py +180 -0
  49. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/horizon_jitter/train.py +74 -0
  50. tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/large_corpus/data.py +73 -0
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/EXPERIMENTS.md ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experiments
2
+
3
+ All learned weights are initialized here from scratch. Validation windows are used only for selection and diagnostics. Screen evaluations span all 97 configurations, sampling at most 192 instances per configuration with seed 2026 and recomputing Seasonal Naive on exactly that subset. Full validation uses the supplied reference. Neither scale is the held-out reward scale.
4
+
5
+ ## E0: contract bootstrap
6
+ - Hypothesis: maintain a runnable package while training the first candidate.
7
+ - Changed factor: none; provided Seasonal Naive formula, with no learned parameters.
8
+ - Seed: deterministic. Measured compute: no training.
9
+ - Checkpoint hash: not applicable.
10
+ - Outcome: provisional package published with atomic directory exchange.
11
+
12
+ ## E1: direct long-horizon quantile forecasting
13
+ - Hypothesis: a direct horizon objective and explicit seasonal context features reduce long-horizon median drift and the underestimation of uncertainty from short-patch autoregression.
14
+ - Changed factors relative to the supplied baseline: 6,758,720-parameter encoder/decoder (4 encoder and 3 decoder layers, width 256), 32-point patches, variable 512–4096-point context, direct 32/128/512/1024-step objectives, monotone nine-quantile head. Context features contain recent levels, fixed damped slope and four-cycle primary/secondary seasonal averages; all weights are globally fixed at inference.
15
+ - Corpus: all 95 mounted allow-listed directories, deterministic source-capped sample totaling 958,745,103 points / 3.835 GB and 357,789 series. Shortest retained series: 16 points. At most eight shuffled shards per source, up to approximately 24M points/source. Series exceeding 131,072 points are cropped at a random position. Packing took under two minutes on six workers.
16
+ - Mixture: directory weight proportional to capped points^0.25, climate multiplier 0.35, low-frequency competition-source multiplier 3. Synthetic proportion 20%. Exact logic is in provenance/data.py.
17
+ - Synthetic generator: newly generated damped trends, Fourier seasonality, AR noise, intermittent demand and changepoints. No downloaded synthetic assets.
18
+ - Training seed: 17. AdamW 3e-4, batch 128, 400-step warmup, cosine decay, bf16, one H100. Run planned for 12,000 steps with snapshots every 1,000 steps.
19
+ - Control: randomly initialized model with zero output projection (fixed seasonal mixture and fixed initial interval widths) saved at step 0 to distinguish learning from the forecasting prior.
20
+ - Completed 12,000 steps in 349.9 seconds on one H100. Measured group skills, checkpoint hashes and outcomes are recorded below.
21
+
22
+ ## Known limits and next decisions
23
+ - This first run jointly changes the architecture and objective; it does not isolate their individual causal contributions.
24
+ - The initial corpus pack samples shuffled shards but takes early Arrow record batches within each selected shard. Later runs should test a wider source sample if validation plateaus.
25
+ - 10-second daily seasonality exceeds the 4,096-point encoder window. Longer fixed context summaries are a planned ablation after initial diagnostics.
26
+
27
+ ## E1 control, step 0, screening
28
+ - Checkpoint SHA-256: `81be0f24c44a558e29dffcabb4ac15ae3c944e1afe2860851683d155f920ec2f`.
29
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.037512302398682 seconds.
30
+ - Overall skill 0.000921; relative MASE 1.194471; relative WQL 0.835649.
31
+ - term skill: long=0.0466, medium=0.0284, short=-0.0280.
32
+ - domain skill: Econ/Fin=-1.0735, Energy=-0.1019, Healthcare=-0.0966, Nature=0.2991, Sales=0.3167, Transport=0.2140, Web/CloudOps=-0.1294.
33
+ - frequency skill: A=-0.6469, D=0.1541, H=0.1205, M=-0.3393, Q=-0.5490, S=-2.2691, T=0.1079, W=-0.0412.
34
+ - variates skill: multivariate=0.0528, univariate=-0.0424.
35
+ - Outcome: Untrained seasonal-mixture prior barely exceeds Seasonal Naive overall and fails badly on 10-second and low-frequency configurations.
36
+
37
+ ## E1 step 1000, seed 17, screening
38
+ - Checkpoint SHA-256: `ebdd9eaa223c2bb6e38b8faec6f465a227fcd735b654a26f3b617a757addb0d3`.
39
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.581991195678711 seconds.
40
+ - Overall skill 0.210443; relative MASE 0.932765; relative WQL 0.668336.
41
+ - term skill: long=0.2339, medium=0.2517, short=0.1848.
42
+ - domain skill: Econ/Fin=-0.1600, Energy=0.0730, Healthcare=-0.0312, Nature=0.3679, Sales=0.2919, Transport=0.3892, Web/CloudOps=0.2547.
43
+ - frequency skill: A=0.3078, D=0.2651, H=0.3157, M=-0.3962, Q=0.0682, S=-0.6697, T=0.2839, W=0.0983.
44
+ - variates skill: multivariate=0.2140, univariate=0.2076.
45
+ - Outcome: Improves the control by 0.2095 screening skill after about 34 seconds on one H100. Selected for first neural publication and full validation.
46
+
47
+ ## E1 step 1000, full validation
48
+ - Checkpoint SHA-256: `see model_manifest.json`.
49
+ - Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds.
50
+ - Overall skill 0.206132; relative MASE 0.931220; relative WQL 0.676774.
51
+ - term skill: long=0.2265, medium=0.2444, short=0.1829.
52
+ - domain skill: Econ/Fin=-0.1543, Energy=0.0590, Healthcare=-0.0112, Nature=0.3688, Sales=0.3043, Transport=0.3878, Web/CloudOps=0.2461.
53
+ - frequency skill: A=0.2746, D=0.2676, H=0.3116, M=-0.3493, Q=0.0397, S=-0.6697, T=0.2712, W=0.1025.
54
+ - variates skill: multivariate=0.2097, univariate=0.2033.
55
+ - Outcome: Full 151,170-instance validation skill 0.2061, with no failed configurations. Package inference took 29.5 seconds while training shared the sole GPU. First neural publication verified.
56
+
57
+ ## E1 step 2000, screening
58
+ - Checkpoint SHA-256: `a513ac4f03aceb93a860d5e5eca70010c0101fdea794df4a9a8ae472647fb9c9`.
59
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.98806357383728 seconds.
60
+ - Overall skill 0.249671; relative MASE 0.890745; relative WQL 0.632048.
61
+ - term skill: long=0.2727, medium=0.2872, short=0.2257.
62
+ - domain skill: Econ/Fin=-0.0533, Energy=0.1151, Healthcare=0.1665, Nature=0.4084, Sales=0.2984, Transport=0.3867, Web/CloudOps=0.2855.
63
+ - frequency skill: A=0.3280, D=0.2894, H=0.3291, M=-0.1483, Q=0.1703, S=-0.4627, T=0.3239, W=0.1185.
64
+ - variates skill: multivariate=0.2588, univariate=0.2423.
65
+ - Outcome: Improves screening skill to 0.2497 after 66.8 seconds of training; candidate for replacement.
66
+
67
+ ## E1 step 3000, screening
68
+ - Checkpoint SHA-256: `74da538d2365426496a12c965c0c0cdc1d3962a798bd2e2c5fed950c1f663f30`.
69
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.051600933074951 seconds.
70
+ - Overall skill 0.246085; relative MASE 0.894210; relative WQL 0.635631.
71
+ - term skill: long=0.2835, medium=0.2774, short=0.2187.
72
+ - domain skill: Econ/Fin=-0.1111, Energy=0.1198, Healthcare=-0.0532, Nature=0.3956, Sales=0.3188, Transport=0.4123, Web/CloudOps=0.3004.
73
+ - frequency skill: A=0.3478, D=0.2585, H=0.3298, M=-0.3174, Q=0.1517, S=-0.6889, T=0.3620, W=0.1126.
74
+ - variates skill: multivariate=0.2552, univariate=0.2388.
75
+ - Outcome: Slight regression to 0.2461 relative to step 2000. Negative checkpoint-selection result; not selected.
76
+
77
+ ## E2 fixed longer-history feature ablation, step 2000 seed 17
78
+ - Checkpoint SHA-256: `25ac85db67c041c92870e2ea2e8b198bb768f5c5ed64f42b78d6ec207ffe3a18`.
79
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.066685438156128 seconds.
80
+ - Overall skill 0.249089; relative MASE 0.890661; relative WQL 0.633088.
81
+ - term skill: long=0.2741, medium=0.2855, short=0.2248.
82
+ - domain skill: Econ/Fin=-0.0532, Energy=0.1146, Healthcare=0.1651, Nature=0.4048, Sales=0.2986, Transport=0.3880, Web/CloudOps=0.2859.
83
+ - frequency skill: A=0.3273, D=0.2892, H=0.3291, M=-0.1495, Q=0.1705, S=-0.4627, T=0.3228, W=0.1166.
84
+ - variates skill: multivariate=0.2572, univariate=0.2426.
85
+ - Outcome: No training. Changed only history available to seasonal summaries from 4,096 to 16,384 points, with the encoder unchanged. Skill decreased 0.24967 to 0.24909. Rejected. Validation 10-second histories are shorter than one daily cycle, so additional history cannot supply that feature.
86
+
87
+ ## E1 step 4000, screening
88
+ - Checkpoint SHA-256: `f1b4e5f798688a56a693daf799fa21e69ec21c9c1710cae8dafbdb833c9ee069`.
89
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.961170196533203 seconds.
90
+ - Overall skill 0.266471; relative MASE 0.874789; relative WQL 0.615080.
91
+ - term skill: long=0.2537, medium=0.2846, short=0.2643.
92
+ - domain skill: Econ/Fin=-0.0360, Energy=0.1306, Healthcare=0.1810, Nature=0.3894, Sales=0.3301, Transport=0.4253, Web/CloudOps=0.3121.
93
+ - frequency skill: A=0.3647, D=0.2978, H=0.3375, M=-0.0981, Q=0.1458, S=-0.2890, T=0.3375, W=0.1196.
94
+ - variates skill: multivariate=0.2648, univariate=0.2678.
95
+ - Outcome: Best ungated checkpoint so far; improved short-horizon performance, with some long-horizon regression.
96
+
97
+ ## E1 step 6000, screening
98
+ - Checkpoint SHA-256: `f38cdb1b49938007c20bdfdfa7c4fc7d7aba6516192f388f37088891411eab7f`.
99
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.802650451660156 seconds.
100
+ - Overall skill 0.258313; relative MASE 0.878300; relative WQL 0.626324.
101
+ - term skill: long=0.2951, medium=0.3035, short=0.2254.
102
+ - domain skill: Econ/Fin=-0.0599, Energy=0.1417, Healthcare=0.2750, Nature=0.3683, Sales=0.3181, Transport=0.4116, Web/CloudOps=0.2761.
103
+ - frequency skill: A=0.3490, D=0.2962, H=0.3475, M=-0.0679, Q=0.1442, S=-0.6390, T=0.3416, W=0.0785.
104
+ - variates skill: multivariate=0.2482, univariate=0.2662.
105
+ - Outcome: Overall regression relative to step 4000 despite improvement on medium and long horizons. Not selected by overall skill.
106
+
107
+ ## E3 seasonal confidence gate, step 4000 seed 17
108
+ - Checkpoint SHA-256: `f1b4e5f798688a56a693daf799fa21e69ec21c9c1710cae8dafbdb833c9ee069`.
109
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.475942373275757 seconds.
110
+ - Overall skill 0.301779; relative MASE 0.827721; relative WQL 0.588981.
111
+ - term skill: long=0.3338, medium=0.3656, short=0.2627.
112
+ - domain skill: Econ/Fin=-0.0087, Energy=0.1326, Healthcare=0.1954, Nature=0.3891, Sales=0.3285, Transport=0.4242, Web/CloudOps=0.4509.
113
+ - frequency skill: A=0.3647, D=0.2945, H=0.3455, M=-0.0632, Q=0.1395, S=0.3700, T=0.3389, W=0.1159.
114
+ - variates skill: multivariate=0.3379, univariate=0.2716.
115
+ - Outcome: No additional training. Fixed gate: weight=clip(1 - mean squared seasonal difference / (0.25 * context variance), 0, 0.98). Blend neural quantiles with a last-four-cycle seasonal mean and Gaussian intervals based on seasonal differences. Each instance uses only its own context; no optimized or adapted parameters. Skill increases 0.26647 to 0.30178; selected for full validation.
116
+
117
+ ## E3 step 4000 gate, full validation
118
+ - Checkpoint SHA-256: `see model_manifest.json`.
119
+ - Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds.
120
+ - Overall skill 0.296168; relative MASE 0.830141; relative WQL 0.596742.
121
+ - term skill: long=0.3262, medium=0.3621, short=0.2569.
122
+ - domain skill: Econ/Fin=-0.0444, Energy=0.1210, Healthcare=0.2106, Nature=0.3890, Sales=0.3389, Transport=0.4244, Web/CloudOps=0.4426.
123
+ - frequency skill: A=0.2806, D=0.2946, H=0.3404, M=-0.0364, Q=0.1048, S=0.3700, T=0.3291, W=0.1093.
124
+ - variates skill: multivariate=0.3332, univariate=0.2652.
125
+ - Outcome: Selected and published. Full validation skill 0.296168 versus 0.206132 for the initial neural package; no failures. Full inference took 39.8 seconds while sharing one GPU with training. This is validation skill, not a held-out reward claim.
126
+
127
+ ## E1 step 8000, seed 17, ungated screening
128
+ - Checkpoint SHA-256: `ebbae91cb50acf1b1436fcbcdce1637195dd6e5006580d3d8e94a4e102aed0ad`.
129
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.500704050064087 seconds.
130
+ - Overall skill 0.276275; relative MASE 0.864160; relative WQL 0.606113.
131
+ - term skill: long=0.2954, medium=0.3094, short=0.2557.
132
+ - domain skill: Econ/Fin=-0.0085, Energy=0.1522, Healthcare=0.1826, Nature=0.3866, Sales=0.3192, Transport=0.4212, Web/CloudOps=0.3315.
133
+ - frequency skill: A=0.3679, D=0.3262, H=0.3533, M=-0.2016, Q=0.1316, S=-0.4192, T=0.3605, W=0.1103.
134
+ - variates skill: multivariate=0.2735, univariate=0.2785.
135
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
136
+
137
+ ## E1 step 8000, seed 17, gated screening
138
+ - Checkpoint SHA-256: `ebbae91cb50acf1b1436fcbcdce1637195dd6e5006580d3d8e94a4e102aed0ad`.
139
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.228765964508057 seconds.
140
+ - Overall skill 0.312772; relative MASE 0.813977; relative WQL 0.580216.
141
+ - term skill: long=0.3671, medium=0.3752, short=0.2645.
142
+ - domain skill: Econ/Fin=-0.0003, Energy=0.1512, Healthcare=0.1999, Nature=0.3863, Sales=0.3176, Transport=0.4184, Web/CloudOps=0.4791.
143
+ - frequency skill: A=0.3679, D=0.3227, H=0.3559, M=-0.1576, Q=0.1357, S=0.3651, T=0.3604, W=0.1062.
144
+ - variates skill: multivariate=0.3530, univariate=0.2790.
145
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
146
+
147
+ ## E1 step 10000, seed 17, ungated screening
148
+ - Checkpoint SHA-256: `3845afb6035396030b9a5182037287db092814d68caa4c96a7c415eb1d3b3a0a`.
149
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.094600439071655 seconds.
150
+ - Overall skill 0.285838; relative MASE 0.855761; relative WQL 0.595993.
151
+ - term skill: long=0.2974, medium=0.3249, short=0.2658.
152
+ - domain skill: Econ/Fin=0.0083, Energy=0.1537, Healthcare=0.1904, Nature=0.3858, Sales=0.3164, Transport=0.4217, Web/CloudOps=0.3674.
153
+ - frequency skill: A=0.3494, D=0.3058, H=0.3594, M=-0.1439, Q=0.1128, S=-0.2516, T=0.3685, W=0.1234.
154
+ - variates skill: multivariate=0.2917, univariate=0.2812.
155
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
156
+
157
+ ## E1 step 10000, seed 17, gated screening
158
+ - Checkpoint SHA-256: `3845afb6035396030b9a5182037287db092814d68caa4c96a7c415eb1d3b3a0a`.
159
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.704133749008179 seconds.
160
+ - Overall skill 0.317743; relative MASE 0.805746; relative WQL 0.577695.
161
+ - term skill: long=0.3656, medium=0.3815, short=0.2718.
162
+ - domain skill: Econ/Fin=0.0087, Energy=0.1540, Healthcare=0.2110, Nature=0.3855, Sales=0.3148, Transport=0.4194, Web/CloudOps=0.4916.
163
+ - frequency skill: A=0.3494, D=0.3033, H=0.3612, M=-0.1027, Q=0.1231, S=0.3756, T=0.3699, W=0.1199.
164
+ - variates skill: multivariate=0.3600, univariate=0.2821.
165
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
166
+
167
+ ## E1 step 12000, seed 17, ungated screening
168
+ - Checkpoint SHA-256: `629130a69f89561219b286c1e805d89b8b4662fce0e4b75e731e8764d9066e98`.
169
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.807793855667114 seconds.
170
+ - Overall skill 0.284471; relative MASE 0.856118; relative WQL 0.598027.
171
+ - term skill: long=0.2877, medium=0.3155, short=0.2710.
172
+ - domain skill: Econ/Fin=0.0294, Energy=0.1544, Healthcare=0.2252, Nature=0.3903, Sales=0.3151, Transport=0.4273, Web/CloudOps=0.3413.
173
+ - frequency skill: A=0.3430, D=0.3172, H=0.3585, M=-0.1807, Q=0.1231, S=-0.2708, T=0.3565, W=0.1685.
174
+ - variates skill: multivariate=0.2854, univariate=0.2837.
175
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
176
+
177
+ ## E1 step 12000, seed 17, gated screening
178
+ - Checkpoint SHA-256: `629130a69f89561219b286c1e805d89b8b4662fce0e4b75e731e8764d9066e98`.
179
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.750269889831543 seconds.
180
+ - Overall skill 0.315453; relative MASE 0.812477; relative WQL 0.576760.
181
+ - term skill: long=0.3585, medium=0.3794, short=0.2715.
182
+ - domain skill: Econ/Fin=0.0081, Energy=0.1534, Healthcare=0.2414, Nature=0.3899, Sales=0.3136, Transport=0.4251, Web/CloudOps=0.4722.
183
+ - frequency skill: A=0.3430, D=0.3141, H=0.3577, M=-0.1400, Q=0.1249, S=0.3722, T=0.3572, W=0.1641.
184
+ - variates skill: multivariate=0.3552, univariate=0.2820.
185
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
186
+
187
+ ## E4 stochastic weight average, seed 17, gated screening
188
+ - Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`.
189
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.737564325332642 seconds.
190
+ - Overall skill 0.320612; relative MASE 0.803931; relative WQL 0.574139.
191
+ - term skill: long=0.3654, medium=0.3823, short=0.2769.
192
+ - domain skill: Econ/Fin=0.0210, Energy=0.1663, Healthcare=0.2341, Nature=0.3839, Sales=0.3192, Transport=0.4246, Web/CloudOps=0.4812.
193
+ - frequency skill: A=0.3645, D=0.3114, H=0.3584, M=-0.0937, Q=0.1411, S=0.3729, T=0.3725, W=0.1398.
194
+ - variates skill: multivariate=0.3557, univariate=0.2913.
195
+ - Outcome: Arithmetic weight average of steps 8000, 9000, 10000, 11000 and 12000. Total underlying training 349.9 seconds on one H100 for 12,000 steps / 1,536,000 windows. Averaging uses no validation labels or training updates. Screening skill 0.320612 exceeds the best individual checkpoint 0.317743; selected for full validation.
196
+
197
+ ## E3 confidence and quantile-width sweep
198
+ - Fixed global settings, selected only on validation; no model updates. Seed and checkpoint: E1 step 8000, seed 17.
199
+ - Measured CPU time: 10.7 seconds. The original threshold 0.25 and width multiplier 1.0 won; no tuned change was adopted.
200
+ - (variance threshold, width multiplier) (0.25, 1.0): skill 0.312772; term skills {'short': 0.2645319168347662, 'medium': 0.37524061562171485, 'long': 0.36711552655262625}.
201
+ - (variance threshold, width multiplier) (0.5, 1.0): skill 0.311338; term skills {'short': 0.26128183571880415, 'medium': 0.3766834137570718, 'long': 0.36686872500364487}.
202
+ - (variance threshold, width multiplier) (0.25, 0.75): skill 0.310114; term skills {'short': 0.26357949467631236, 'medium': 0.3710044838302994, 'long': 0.36223509497654094}.
203
+ - (variance threshold, width multiplier) (0.1, 1.0): skill 0.309380; term skills {'short': 0.2645827018541862, 'medium': 0.3687788042390393, 'long': 0.3590704635989247}.
204
+ - (variance threshold, width multiplier) (0.25, 1.25): skill 0.308716; term skills {'short': 0.25806263726485956, 'medium': 0.3732424245969126, 'long': 0.3664492202082874}.
205
+ - (variance threshold, width multiplier) (0.5, 0.75): skill 0.308480; term skills {'short': 0.2599791649373039, 'medium': 0.3724274186615034, 'long': 0.36196930941343286}.
206
+ - (variance threshold, width multiplier) (0.5, 1.25): skill 0.307830; term skills {'short': 0.25575126666422066, 'medium': 0.3747816871597687, 'long': 0.3663051398261168}.
207
+ - (variance threshold, width multiplier) (0.1, 0.75): skill 0.306923; term skills {'short': 0.26386190560263856, 'medium': 0.3650190620286501, 'long': 0.35398875275507513}.
208
+ - (variance threshold, width multiplier) (0.1, 1.25): skill 0.305043; term skills {'short': 0.2579337472130613, 'medium': 0.36611831669487493, 'long': 0.3583403545682865}.
209
+ - (variance threshold, width multiplier) (1.0, 1.0): skill 0.300332; term skills {'short': 0.24300377373135085, 'medium': 0.37515035650362993, 'long': 0.3625716315021771}.
210
+ - (variance threshold, width multiplier) (1.0, 0.75): skill 0.297470; term skills {'short': 0.24163138399697548, 'medium': 0.37101264403024414, 'long': 0.3577626408389879}.
211
+ - (variance threshold, width multiplier) (1.0, 1.25): skill 0.296900; term skills {'short': 0.23759298244372884, 'medium': 0.3732464838258517, 'long': 0.3619922948184182}.
212
+ - (variance threshold, width multiplier) (0.0, 1.0): skill 0.276275; term skills {'short': 0.25565045294773825, 'medium': 0.30935443355536374, 'long': 0.29541709470756516}.
213
+ - (variance threshold, width multiplier) (0.0, 0.75): skill 0.274035; term skills {'short': 0.2552205537396286, 'medium': 0.30589300644316675, 'long': 0.289930620063797}.
214
+ - (variance threshold, width multiplier) (0.0, 1.25): skill 0.271354; term skills {'short': 0.2486798921582145, 'medium': 0.30569315727356094, 'long': 0.29429049771287774}.
215
+
216
+ ## E5 capacity and exponential averaging
217
+ - Hypothesis: increased capacity reduces residual errors after direct-horizon training; exponential weight averaging reduces checkpoint noise.
218
+ - Changed factors: width 512, six encoder and four decoder layers, 37,002,816 parameters; 24,000-step schedule at 2e-4; seed 23. Same source sample, mixture, synthetic generator, batch 128 and horizon distribution as E1. Training-only EMA decay min(0.999, 1-1/(step+1)).
219
+ - Single H100; run in progress. Both raw and EMA snapshots will be evaluated across all 97 configurations. No causal claim isolates size from seed/schedule changes.
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/infer.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export OMP_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=4
4
+ exec python3 "$(dirname "$(readlink -f "$0")")/predict.py" "$1" "$2"
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/model.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon)
51
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
52
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
53
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
54
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
55
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
56
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
57
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
58
+ with torch.no_grad():
59
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
60
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
61
+
62
+ @staticmethod
63
+ def standardize(ctx):
64
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
65
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
66
+ mu=x.sum(-1,keepdim=True)/count
67
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
68
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
69
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
70
+ return z,valid,mu,scale
71
+
72
+ @staticmethod
73
+ def features(z,valid,periods,h):
74
+ b,c=z.shape;dev=z.device
75
+ def avg(k):
76
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
77
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
78
+ last=z.gather(1,last_idx[:,None])[:,0]
79
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
80
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
81
+ t=torch.arange(h,device=dev)[None,:]
82
+ for j in range(2):
83
+ p=periods[:,j:j+1].clamp(min=1)
84
+ anchor=c-p+t%p
85
+ vals=[];masks=[]
86
+ for cycle in range(4):
87
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
88
+ ok=(idx>=0)&valid.gather(1,safe)
89
+ vals.append(z.gather(1,safe));masks.append(ok)
90
+ vals=torch.stack(vals);masks=torch.stack(masks)
91
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
92
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
93
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
94
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
95
+ k=min(128,max(4,c//4));recent=avg(k)
96
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
97
+ slope=((recent-older)/k).clamp(-.03,.03)
98
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
99
+ bases.append(trend)
100
+ return torch.stack(bases,-1)
101
+
102
+ def forward(self,ctx,periods,horizon):
103
+ p=self.patch;h=math.ceil(horizon/p)*p
104
+ ctx=ctx[:,-self.max_context:]
105
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
106
+ z,valid,mu,scale=self.standardize(ctx)
107
+ b,c=z.shape;nt=c//p
108
+ base=self.features(z,valid,periods,h)
109
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
110
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
111
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,torch.full((b,1),math.log1p(h)/8,device=z.device)),-1)
112
+ emb=self.metadata(meta)[:,None]
113
+ x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb
114
+ for layer in self.encoder:x=layer(x,pmask)
115
+ q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb
116
+ for layer in self.decoder:q=layer(q,pmask,x)
117
+ out=self.head(self.norm(q)).view(b,h,18).float()
118
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
119
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
120
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
121
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
122
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
123
+ return quant,mu,scale
124
+
125
+ @torch.no_grad()
126
+ def predict(self,ctx,periods,horizon):
127
+ q,mu,scale=self(ctx,periods,horizon)
128
+ q=q*scale[:,:,None]+mu[:,:,None]
129
+ # Positivity is a fixed context rule, as in released foundation forecasters.
130
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
131
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
132
+ return q.transpose(1,2)
133
+
134
+ def loss_fn(model,ctx,target,periods):
135
+ q,mu,scale=model(ctx,periods,target.shape[-1])
136
+ valid=torch.isfinite(target)
137
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
138
+ err=y[:,:,None]-q
139
+ levels=torch.arange(1,10,device=q.device)/10
140
+ pin=torch.maximum(levels*err,(levels-1)*err).mean(-1)
141
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
142
+ return per.mean()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/model_manifest.json ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "direct-seasonal-quantile-v1-gated",
3
+ "contract": "timeseries-forecast/v1",
4
+ "parameters": 6758720,
5
+ "pretrained_assets": [],
6
+ "sources_used": [
7
+ "gifteval_pretrain/BEIJING_SUBWAY_30MIN",
8
+ "gifteval_pretrain/HZMETRO",
9
+ "gifteval_pretrain/LOS_LOOP",
10
+ "gifteval_pretrain/PEMS03",
11
+ "gifteval_pretrain/PEMS04",
12
+ "gifteval_pretrain/PEMS07",
13
+ "gifteval_pretrain/PEMS08",
14
+ "gifteval_pretrain/PEMS_BAY",
15
+ "gifteval_pretrain/Q-TRAFFIC",
16
+ "gifteval_pretrain/SHMETRO",
17
+ "gifteval_pretrain/alibaba_cluster_trace_2018",
18
+ "gifteval_pretrain/australian_electricity_demand",
19
+ "gifteval_pretrain/azure_vm_traces_2017",
20
+ "gifteval_pretrain/bdg-2_bear",
21
+ "gifteval_pretrain/bdg-2_fox",
22
+ "gifteval_pretrain/bdg-2_panther",
23
+ "gifteval_pretrain/bdg-2_rat",
24
+ "gifteval_pretrain/bitcoin_with_missing",
25
+ "gifteval_pretrain/borealis",
26
+ "gifteval_pretrain/borg_cluster_data_2011",
27
+ "gifteval_pretrain/buildings_900k",
28
+ "gifteval_pretrain/bull",
29
+ "gifteval_pretrain/cdc_fluview_ilinet",
30
+ "gifteval_pretrain/cdc_fluview_who_nrevss",
31
+ "gifteval_pretrain/china_air_quality",
32
+ "gifteval_pretrain/cif_2016_12",
33
+ "gifteval_pretrain/cif_2016_6",
34
+ "gifteval_pretrain/cmip6_2000",
35
+ "gifteval_pretrain/cmip6_2005",
36
+ "gifteval_pretrain/cmip6_2010",
37
+ "gifteval_pretrain/cockatoo",
38
+ "gifteval_pretrain/covid19_energy",
39
+ "gifteval_pretrain/covid_mobility",
40
+ "gifteval_pretrain/elecdemand",
41
+ "gifteval_pretrain/elf",
42
+ "gifteval_pretrain/era5_2010",
43
+ "gifteval_pretrain/era5_2011",
44
+ "gifteval_pretrain/era5_2012",
45
+ "gifteval_pretrain/era5_2013",
46
+ "gifteval_pretrain/era5_2014",
47
+ "gifteval_pretrain/era5_2015",
48
+ "gifteval_pretrain/era5_2016",
49
+ "gifteval_pretrain/era5_2017",
50
+ "gifteval_pretrain/era5_2018",
51
+ "gifteval_pretrain/extended_web_traffic_with_missing",
52
+ "gifteval_pretrain/favorita_sales",
53
+ "gifteval_pretrain/favorita_transactions",
54
+ "gifteval_pretrain/gfc12_load",
55
+ "gifteval_pretrain/gfc14_load",
56
+ "gifteval_pretrain/gfc17_load",
57
+ "gifteval_pretrain/godaddy",
58
+ "gifteval_pretrain/hog",
59
+ "gifteval_pretrain/ideal",
60
+ "gifteval_pretrain/kaggle_web_traffic_weekly",
61
+ "gifteval_pretrain/kdd2022",
62
+ "gifteval_pretrain/largest_2017",
63
+ "gifteval_pretrain/largest_2018",
64
+ "gifteval_pretrain/largest_2019",
65
+ "gifteval_pretrain/largest_2020",
66
+ "gifteval_pretrain/largest_2021",
67
+ "gifteval_pretrain/lcl",
68
+ "gifteval_pretrain/london_smart_meters_with_missing",
69
+ "gifteval_pretrain/m1_monthly",
70
+ "gifteval_pretrain/m1_quarterly",
71
+ "gifteval_pretrain/m1_yearly",
72
+ "gifteval_pretrain/m5",
73
+ "gifteval_pretrain/monash_m3_monthly",
74
+ "gifteval_pretrain/monash_m3_other",
75
+ "gifteval_pretrain/monash_m3_quarterly",
76
+ "gifteval_pretrain/nn5_daily_with_missing",
77
+ "gifteval_pretrain/nn5_weekly",
78
+ "gifteval_pretrain/oikolab_weather",
79
+ "gifteval_pretrain/pdb",
80
+ "gifteval_pretrain/project_tycho",
81
+ "gifteval_pretrain/residential_load_power",
82
+ "gifteval_pretrain/residential_pv_power",
83
+ "gifteval_pretrain/rideshare_with_missing",
84
+ "gifteval_pretrain/sceaux",
85
+ "gifteval_pretrain/smart",
86
+ "gifteval_pretrain/solar_power",
87
+ "gifteval_pretrain/spain",
88
+ "gifteval_pretrain/subseasonal",
89
+ "gifteval_pretrain/subseasonal_precip",
90
+ "gifteval_pretrain/sunspot_with_missing",
91
+ "gifteval_pretrain/taxi_30min",
92
+ "gifteval_pretrain/tourism_quarterly",
93
+ "gifteval_pretrain/tourism_yearly",
94
+ "gifteval_pretrain/traffic_hourly",
95
+ "gifteval_pretrain/traffic_weekly",
96
+ "gifteval_pretrain/uber_tlc_daily",
97
+ "gifteval_pretrain/uber_tlc_hourly",
98
+ "gifteval_pretrain/vehicle_trips_with_missing",
99
+ "gifteval_pretrain/wiki-rolling_nips",
100
+ "gifteval_pretrain/wind_farms_with_missing",
101
+ "gifteval_pretrain/wind_power",
102
+ "synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17"
103
+ ],
104
+ "weights_sha256": "a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db",
105
+ "training_step": 12000,
106
+ "config": {
107
+ "d": 256,
108
+ "heads": 8,
109
+ "enc_layers": 4,
110
+ "dec_layers": 3,
111
+ "patch": 32,
112
+ "max_context": 4096,
113
+ "max_horizon": 1024
114
+ },
115
+ "notes": "Random initialization, direct encoder-decoder quantile forecasts with fixed per-instance seasonal context summaries. No fitting or parameter adaptation at inference. All 95 allow-listed directories sampled. Validation only used for selection. Fixed context confidence gate blends highly repeatable seasonal histories with a four-cycle seasonal average and residual-based intervals; no parameters are fit at inference.",
116
+ "averaged_training_steps": [
117
+ 8000,
118
+ 9000,
119
+ 10000,
120
+ 11000,
121
+ 12000
122
+ ],
123
+ "postprocessing": {
124
+ "seasonal_difference_variance_threshold": 0.25,
125
+ "maximum_blend": 0.98,
126
+ "cycles_averaged": 4,
127
+ "inference_fitting": false
128
+ }
129
+ }
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/provenance/data.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class Sampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ w=min(len(values),20_000_000)**.25
19
+ if name.startswith(('era5_','cmip6_')):w*=.35
20
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
21
+ weights.append(w)
22
+ self.probs=np.array(weights)/sum(weights)
23
+
24
+ def synthetic(self,n,p):
25
+ r=self.rng;t=np.arange(n,dtype=np.float32)
26
+ # New generator: damped trends, random Fourier seasonality, AR noise,
27
+ # intermittent demand, changepoints, and randomly scaled observation noise.
28
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
29
+ x=np.full(n,level,np.float32)
30
+ if r.random()<.8:
31
+ for period in p:
32
+ if period<2:continue
33
+ for k in range(1,int(r.integers(2,5))):
34
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
35
+ if r.random()<.6:
36
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
37
+ x+=slope*tau*(1-np.exp(-t/tau))
38
+ noise=r.normal(0,sigma,n).astype(np.float32)
39
+ if r.random()<.5:
40
+ from scipy.signal import lfilter
41
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
42
+ x+=noise
43
+ if r.random()<.2:
44
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
45
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
46
+ if r.random()<.1:x=np.maximum(0,x)
47
+ return x.astype(np.float32)
48
+
49
+ def sample(self,batch,context=2048,horizon=1024):
50
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
51
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
52
+ for b,d in enumerate(ds):
53
+ if r.random()<self.synthetic_fraction:
54
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
55
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
56
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
57
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
58
+ # Random cutoffs retain short sources, with unavailable future steps masked.
59
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
60
+ nc=min(context,cut)
61
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
62
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
63
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
64
+ if r.random()<.12 and l>=4*(context+horizon):
65
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
66
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
67
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
68
+ else:periods[b]=self.periods[d][i]
69
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
70
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
71
+ return ctx,tgt,periods
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/provenance/train.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json,math,time,os,sys,shutil,hashlib
2
+ from pathlib import Path
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import numpy as np
5
+ import torch
6
+ from model import DirectForecaster,loss_fn
7
+ from data import Sampler
8
+
9
+ def save(model,path,step,args,opt=None):
10
+ ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)}
11
+ if opt is not None:ck['opt']=opt.state_dict()
12
+ tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path)
13
+
14
+ def main():
15
+ ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True)
16
+ ap.add_argument('--steps',type=int,default=12000);ap.add_argument('--batch',type=int,default=128);ap.add_argument('--context',type=int,default=4096)
17
+ ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3)
18
+ ap.add_argument('--lr',type=float,default=3e-4);ap.add_argument('--seed',type=int,default=17);ap.add_argument('--save-every',type=int,default=1000)
19
+ ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args()
20
+ torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed)
21
+ torch.backends.cuda.matmul.allow_tf32=True
22
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
23
+ model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda()
24
+ opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True)
25
+ startstep=0
26
+ if a.resume:
27
+ ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step']
28
+ if 'opt' in ck:opt.load_state_dict(ck['opt'])
29
+ sampler=Sampler(a.packed,seed=a.seed+startstep)
30
+ params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2))
31
+ print('parameters',params,flush=True)
32
+ rng=np.random.default_rng(a.seed+startstep)
33
+ def nextbatch():
34
+ c=int(rng.choice([512,1024,2048,a.context],p=[.1,.15,.35,.4]));h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5]))
35
+ return sampler.sample(a.batch,c,h)
36
+ pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[]
37
+ for step in range(startstep+1,a.steps+1):
38
+ arrays=future.result();future=pool.submit(nextbatch)
39
+ x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays]
40
+ lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps))))
41
+ for g in opt.param_groups:g['lr']=lr
42
+ opt.zero_grad(set_to_none=True)
43
+ with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p)
44
+ loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
45
+ if torch.isfinite(gn):opt.step()
46
+ losses.append(float(loss.detach()))
47
+ if step%50==0:
48
+ rec={'step':step,'loss':float(np.mean(losses)),'seconds':round(time.time()-t0,1),'lr':lr,'grad_norm':float(gn),'context':x.shape[-1],'horizon':y.shape[-1]}
49
+ print(json.dumps(rec),flush=True)
50
+ with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n')
51
+ losses=[]
52
+ stop=a.stop_file and Path(a.stop_file).exists()
53
+ if step%a.save_every==0 or step==a.steps or stop:
54
+ save(model,out/f'step{step:06d}.pt',step,a)
55
+ save(model,out/'last.pt',step,a,opt)
56
+ if stop:break
57
+ pool.shutdown()
58
+
59
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/ts_io.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1).
2
+
3
+ Three things live here because the case builder, the grader, the starter and
4
+ the reference packages must agree on them exactly:
5
+
6
+ 1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality
7
+ tables, transcribed from gift-eval `src/gift_eval/data.py` at commit
8
+ db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables,
9
+ not runtime derivations, so a pandas alias rename cannot silently change a
10
+ horizon or a seasonality.
11
+ 2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval
12
+ (`<dataset>/[<freq>/]data-00000-of-00001.arrow`), implemented with pyarrow
13
+ only, and the rolling-window instance generator that reproduces
14
+ `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval.
15
+ 3. The case-file format: one HDF5 file per (dataset, frequency, term) config
16
+ holding every forecast instance's context, and one HDF5 prediction file per
17
+ config holding the mean and the nine decile forecasts.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import functools
22
+ import hashlib
23
+ import json
24
+ import math
25
+ import os
26
+ import re
27
+ import stat
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+
32
+ CONTRACT = "timeseries-forecast/v1"
33
+ QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
34
+ CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md)
35
+ TEST_SPLIT = 0.1
36
+ MAX_WINDOW = 20
37
+ TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15}
38
+ PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60}
39
+ M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48}
40
+ # gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1
41
+ BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1}
42
+ _UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"}
43
+ _FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$")
44
+
45
+
46
+ def parse_freq(freq: str) -> tuple[int, str]:
47
+ """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H')."""
48
+ m = _FREQ_RE.match(freq.strip())
49
+ if not m:
50
+ raise ValueError(f"unrecognised frequency {freq!r}")
51
+ n = int(m.group(1) or 1)
52
+ unit = _UNIT_ALIASES.get(m.group(2), m.group(2))
53
+ if unit not in BASE_SEASONALITY:
54
+ raise ValueError(f"unrecognised frequency unit in {freq!r}")
55
+ return n, unit
56
+
57
+
58
+ def prediction_length(dataset: str, freq: str, term: str) -> int:
59
+ _, unit = parse_freq(freq)
60
+ table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP
61
+ return TERM_MULTIPLIER[term] * table[unit]
62
+
63
+
64
+ def seasonality(freq: str) -> int:
65
+ n, unit = parse_freq(freq)
66
+ base = BASE_SEASONALITY[unit]
67
+ q, r = divmod(base, n)
68
+ return q if r == 0 else 1
69
+
70
+
71
+ def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int:
72
+ if "m4" in dataset:
73
+ return 1
74
+ w = math.ceil(TEST_SPLIT * min_series_length / pred_len)
75
+ return min(max(1, w), MAX_WINDOW)
76
+
77
+
78
+ def config_id(dataset: str, freq_unit: str, term: str) -> str:
79
+ """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique)."""
80
+ return f"{dataset.split('/')[0]}__{freq_unit}__{term}"
81
+
82
+
83
+ # gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names
84
+ LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H",
85
+ "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M",
86
+ "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"}
87
+ LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain",
88
+ "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"}
89
+
90
+
91
+ def leaderboard_key(dataset: str, term: str) -> str:
92
+ """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased)."""
93
+ base, _, sub = dataset.partition("/")
94
+ freq = sub if sub else LEADERBOARD_FREQ[base]
95
+ base = base.lower()
96
+ return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}"
97
+
98
+
99
+ VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it
100
+
101
+
102
+ # ----------------------------------------------------------------------------- Arrow readers
103
+
104
+
105
+ def arrow_path(root: Path, dataset: str) -> Path:
106
+ return Path(root) / dataset / "data-00000-of-00001.arrow"
107
+
108
+
109
+ def read_arrow_dataset(root: Path, dataset: str):
110
+ """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset.
111
+
112
+ `series` is a list of float32 arrays of shape (D, T); univariate datasets
113
+ give D = 1. Missing values are NaN as stored.
114
+ """
115
+ import pyarrow as pa
116
+
117
+ with open(arrow_path(root, dataset), "rb") as f:
118
+ table = pa.ipc.open_stream(f).read_all()
119
+ item_ids = table.column("item_id").to_pylist()
120
+ starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]")
121
+ freq = table.column("freq")[0].as_py()
122
+ target = table.column("target").combine_chunks()
123
+ series = []
124
+ if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type):
125
+ # multivariate: fixed_size_list<list<float>> (or list<list<float>>) -> (D, T) per item
126
+ if pa.types.is_fixed_size_list(target.type):
127
+ k = target.type.list_size
128
+ outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k
129
+ else:
130
+ outer_off = target.offsets.to_numpy()
131
+ inner = target.values
132
+ inner_off = inner.offsets.to_numpy()
133
+ flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32)
134
+ for i in range(len(target)):
135
+ d0, d1 = outer_off[i], outer_off[i + 1]
136
+ rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)]
137
+ if len({len(r) for r in rows}) != 1:
138
+ raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length")
139
+ series.append(np.stack(rows))
140
+ else:
141
+ off = target.offsets.to_numpy()
142
+ flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32)
143
+ for i in range(len(target)):
144
+ series.append(flat[off[i]:off[i + 1]][None, :])
145
+ return item_ids, starts, freq, series
146
+
147
+
148
+ def read_arrow_index(root: Path, dataset: str):
149
+ """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints).
150
+
151
+ The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can
152
+ hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does.
153
+ """
154
+ import pyarrow as pa
155
+
156
+ with open(arrow_path(root, dataset), "rb") as f:
157
+ table = pa.ipc.open_stream(f).read_all()
158
+ item_ids = table.column("item_id").to_pylist()
159
+ starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]")
160
+ freq = table.column("freq")[0].as_py()
161
+ target = table.column("target").combine_chunks()
162
+ if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type):
163
+ inner = target.values
164
+ off = inner.offsets.to_numpy()
165
+ flat = inner.values.to_numpy(zero_copy_only=False)
166
+ width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None
167
+ if width is None:
168
+ outer = target.offsets.to_numpy()
169
+ first = outer[:-1]
170
+ else:
171
+ first = (np.arange(len(target)) + target.offset) * width
172
+ else:
173
+ off = target.offsets.to_numpy()
174
+ flat = target.values.to_numpy(zero_copy_only=False)
175
+ first = np.arange(len(target))
176
+ lengths = (off[first + 1] - off[first]).astype(np.int64)
177
+ fingerprints = []
178
+ for i, start in enumerate(first):
179
+ a, b = off[start], off[start + 1]
180
+ head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b]
181
+ fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16]))
182
+ return item_ids, starts, freq, lengths, fingerprints
183
+
184
+
185
+ def config_table(root: Path, dataset: str, term: str) -> dict:
186
+ """Protocol quantities of one (dataset, term) config, read from the Arrow file."""
187
+ item_ids, starts, freq, series = read_arrow_dataset(root, dataset)
188
+ n, unit = parse_freq(freq)
189
+ lengths = np.array([s.shape[1] for s in series])
190
+ pred_len = prediction_length(dataset, freq, term)
191
+ windows = n_windows(dataset, int(lengths.min()), pred_len)
192
+ return {
193
+ "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term,
194
+ "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term),
195
+ "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows,
196
+ "n_series": len(series), "n_variates": int(series[0].shape[0]),
197
+ "min_length": int(lengths.min()), "max_length": int(lengths.max()),
198
+ "n_test_instances": len(series) * windows, "n_valid_instances": len(series),
199
+ }
200
+
201
+
202
+ def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]:
203
+ """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L."""
204
+ return [length - pred_len * windows + k * pred_len for k in range(windows)]
205
+
206
+
207
+ def valid_cutoff(length: int, pred_len: int, windows: int) -> int:
208
+ """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which
209
+ `training_dataset` (offset -L*(W+1)) excludes.
210
+
211
+ A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test
212
+ regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation
213
+ data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the
214
+ per-config upper bound.
215
+ """
216
+ return length - pred_len * (windows + 1)
217
+
218
+
219
+ def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int:
220
+ """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid)."""
221
+ import pandas as pd
222
+
223
+ multiple, _ = parse_freq(freq)
224
+ f = _pandas_freq(freq)
225
+ # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps
226
+ delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n
227
+ return int(delta) // multiple
228
+
229
+
230
+ @functools.lru_cache(maxsize=4096)
231
+ def _base_period(start: str, freq: str):
232
+ import pandas as pd
233
+
234
+ return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq))
235
+
236
+
237
+ def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str:
238
+ """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`."""
239
+ return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat()
240
+
241
+
242
+ def _pandas_freq(freq: str) -> str:
243
+ n, unit = parse_freq(freq)
244
+ anchor = freq.split("-")[1] if "-" in freq else ""
245
+ new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit]
246
+ return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}"
247
+
248
+
249
+ # ----------------------------------------------------------------------------- case files
250
+
251
+
252
+ def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None):
253
+ """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance;
254
+ cohorts: verifier invocation group per instance (see make_cases.py), optional."""
255
+ import h5py
256
+
257
+ d = int(meta["n_variates"])
258
+ lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64)
259
+ offsets = np.zeros(len(contexts) + 1, dtype=np.int64)
260
+ offsets[1:] = np.cumsum(lengths * d)
261
+ values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32)
262
+ path.parent.mkdir(parents=True, exist_ok=True)
263
+ with h5py.File(path, "w") as f:
264
+ f.create_dataset("values", data=values)
265
+ f.create_dataset("offsets", data=offsets)
266
+ f.create_dataset("context_length", data=lengths)
267
+ f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64))
268
+ f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype()))
269
+ f.create_dataset("window", data=np.asarray(windows, dtype=np.int64))
270
+ f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype()))
271
+ if cohorts is not None:
272
+ f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64))
273
+ for k, v in meta.items():
274
+ f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v
275
+ f.attrs["contract"] = CONTRACT
276
+ f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS)
277
+
278
+
279
+ def write_case_subset(src: "CaseFile", indices, dst: Path):
280
+ """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied)."""
281
+ import h5py
282
+
283
+ indices = np.asarray(indices, dtype=np.int64)
284
+ contexts = [src.context(int(i)) for i in indices]
285
+ meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")}
286
+ write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices],
287
+ [src.forecast_start[i] for i in indices], src.history_length[indices])
288
+ with h5py.File(dst, "r+") as f:
289
+ f.create_dataset("cohort", data=src.cohort[indices])
290
+ f.create_dataset("source_index", data=indices)
291
+
292
+
293
+ class CaseFile:
294
+ """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32."""
295
+
296
+ def __init__(self, path: Path):
297
+ import h5py
298
+
299
+ self.path = Path(path)
300
+ self._f = h5py.File(self.path, "r")
301
+ self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()}
302
+ self.n_variates = int(self.meta["n_variates"])
303
+ self.prediction_length = int(self.meta["prediction_length"])
304
+ self.offsets = self._f["offsets"][()]
305
+ self.n = len(self.offsets) - 1
306
+ self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]]
307
+ self.window = self._f["window"][()]
308
+ self.context_length = self._f["context_length"][()]
309
+ self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]]
310
+ self.history_length = self._f["history_length"][()]
311
+ self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64)
312
+ self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n)
313
+
314
+ def context(self, i: int) -> np.ndarray:
315
+ v = self._f["values"][self.offsets[i]:self.offsets[i + 1]]
316
+ return v.reshape(self.n_variates, -1)
317
+
318
+ def contexts(self):
319
+ values = self._f["values"][()]
320
+ for i in range(self.n):
321
+ yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1)
322
+
323
+ def close(self):
324
+ self._f.close()
325
+
326
+
327
+ def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None):
328
+ """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS."""
329
+ import h5py
330
+
331
+ mean = np.asarray(mean, dtype=np.float32)
332
+ quantiles = np.asarray(quantiles, dtype=np.float32)
333
+ if mean.ndim != 3 or quantiles.ndim != 4 or quantiles.shape[:2] != mean.shape[:2] or quantiles.shape[3] != mean.shape[2] or quantiles.shape[2] != len(QUANTILE_LEVELS):
334
+ raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}")
335
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
336
+ with h5py.File(path, "w") as f:
337
+ f.create_dataset("mean", data=mean)
338
+ f.create_dataset("quantiles", data=quantiles)
339
+ f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS)
340
+ f.attrs["contract"] = CONTRACT
341
+ for k, v in (meta or {}).items():
342
+ f.attrs[k] = v
343
+
344
+
345
+ PREDICTION_DATASETS = ("mean", "quantiles")
346
+
347
+
348
+ def open_package_h5(path, names=PREDICTION_DATASETS):
349
+ """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets.
350
+
351
+ The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow
352
+ anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can
353
+ point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block."""
354
+ import h5py
355
+
356
+ st = os.lstat(path)
357
+ if not stat.S_ISREG(st.st_mode):
358
+ raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)")
359
+ f = h5py.File(path, "r")
360
+ try:
361
+ for name in names:
362
+ link = f.get(name, getlink=True)
363
+ if link is None:
364
+ raise KeyError(f"no {name!r} dataset")
365
+ if not isinstance(link, h5py.HardLink):
366
+ raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read")
367
+ d = f[name]
368
+ if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external:
369
+ raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)")
370
+ except Exception:
371
+ f.close()
372
+ raise
373
+ return f
374
+
375
+
376
+ def prediction_shapes(path: Path):
377
+ """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory."""
378
+ with open_package_h5(path) as f:
379
+ attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()}
380
+ return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs
381
+
382
+
383
+ def read_prediction_file(path: Path, expect: tuple | None = None):
384
+ """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read."""
385
+ with open_package_h5(path) as f:
386
+ got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape)
387
+ want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2])
388
+ if expect is not None and (got_m != tuple(expect) or got_q != want_q):
389
+ raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}")
390
+ return f["mean"][()], f["quantiles"][()]
391
+
392
+
393
+ def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict):
394
+ """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64."""
395
+ import h5py
396
+
397
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
398
+ with h5py.File(path, "w") as f:
399
+ f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32))
400
+ f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64))
401
+ for k, v in meta.items():
402
+ f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v
403
+
404
+
405
+ def read_truth_file(path: Path):
406
+ import h5py
407
+
408
+ with h5py.File(path, "r") as f:
409
+ meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()}
410
+ return f["labels"][()], f["seasonal_error"][()], meta
411
+
412
+
413
+ def seasonal_error(history: np.ndarray, m: int) -> np.ndarray:
414
+ """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate.
415
+
416
+ Reproduces `gluonts.model.evaluation._get_data_batch` with
417
+ `mask_invalid_label=True`: the history is a masked array, so the mean of
418
+ |x[t] - x[t-m]| runs over the pairs where both observations are finite.
419
+ If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with
420
+ no valid pair gets NaN.
421
+ """
422
+ t = history.shape[-1]
423
+ lag = m if m <= t else 1
424
+ if t <= lag:
425
+ return np.full(history.shape[0], np.nan)
426
+ x = history.astype(np.float64)
427
+ diff = np.abs(x[:, lag:] - x[:, :-lag])
428
+ valid = np.isfinite(diff)
429
+ count = valid.sum(axis=-1)
430
+ with np.errstate(invalid="ignore", divide="ignore"):
431
+ out = np.where(valid, diff, 0.0).sum(axis=-1) / count
432
+ out[count == 0] = np.nan
433
+ return out
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S004/validation_report.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/EXPERIMENTS.md ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experiments
2
+
3
+ All learned weights are initialized here from scratch. Validation windows are used only for selection and diagnostics. Screen evaluations span all 97 configurations, sampling at most 192 instances per configuration with seed 2026 and recomputing Seasonal Naive on exactly that subset. Full validation uses the supplied reference. Neither scale is the held-out reward scale.
4
+
5
+ ## E0: contract bootstrap
6
+ - Hypothesis: maintain a runnable package while training the first candidate.
7
+ - Changed factor: none; provided Seasonal Naive formula, with no learned parameters.
8
+ - Seed: deterministic. Measured compute: no training.
9
+ - Checkpoint hash: not applicable.
10
+ - Outcome: provisional package published with atomic directory exchange.
11
+
12
+ ## E1: direct long-horizon quantile forecasting
13
+ - Hypothesis: a direct horizon objective and explicit seasonal context features reduce long-horizon median drift and the underestimation of uncertainty from short-patch autoregression.
14
+ - Changed factors relative to the supplied baseline: 6,758,720-parameter encoder/decoder (4 encoder and 3 decoder layers, width 256), 32-point patches, variable 512–4096-point context, direct 32/128/512/1024-step objectives, monotone nine-quantile head. Context features contain recent levels, fixed damped slope and four-cycle primary/secondary seasonal averages; all weights are globally fixed at inference.
15
+ - Corpus: all 95 mounted allow-listed directories, deterministic source-capped sample totaling 958,745,103 points / 3.835 GB and 357,789 series. Shortest retained series: 16 points. At most eight shuffled shards per source, up to approximately 24M points/source. Series exceeding 131,072 points are cropped at a random position. Packing took under two minutes on six workers.
16
+ - Mixture: directory weight proportional to capped points^0.25, climate multiplier 0.35, low-frequency competition-source multiplier 3. Synthetic proportion 20%. Exact logic is in provenance/data.py.
17
+ - Synthetic generator: newly generated damped trends, Fourier seasonality, AR noise, intermittent demand and changepoints. No downloaded synthetic assets.
18
+ - Training seed: 17. AdamW 3e-4, batch 128, 400-step warmup, cosine decay, bf16, one H100. Run planned for 12,000 steps with snapshots every 1,000 steps.
19
+ - Control: randomly initialized model with zero output projection (fixed seasonal mixture and fixed initial interval widths) saved at step 0 to distinguish learning from the forecasting prior.
20
+ - Completed 12,000 steps in 349.9 seconds on one H100. Measured group skills, checkpoint hashes and outcomes are recorded below.
21
+
22
+ ## Known limits and next decisions
23
+ - This first run jointly changes the architecture and objective; it does not isolate their individual causal contributions.
24
+ - The initial corpus pack samples shuffled shards but takes early Arrow record batches within each selected shard. Later runs should test a wider source sample if validation plateaus.
25
+ - 10-second daily seasonality exceeds the 4,096-point encoder window. Longer fixed context summaries are a planned ablation after initial diagnostics.
26
+
27
+ ## E1 control, step 0, screening
28
+ - Checkpoint SHA-256: `81be0f24c44a558e29dffcabb4ac15ae3c944e1afe2860851683d155f920ec2f`.
29
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.037512302398682 seconds.
30
+ - Overall skill 0.000921; relative MASE 1.194471; relative WQL 0.835649.
31
+ - term skill: long=0.0466, medium=0.0284, short=-0.0280.
32
+ - domain skill: Econ/Fin=-1.0735, Energy=-0.1019, Healthcare=-0.0966, Nature=0.2991, Sales=0.3167, Transport=0.2140, Web/CloudOps=-0.1294.
33
+ - frequency skill: A=-0.6469, D=0.1541, H=0.1205, M=-0.3393, Q=-0.5490, S=-2.2691, T=0.1079, W=-0.0412.
34
+ - variates skill: multivariate=0.0528, univariate=-0.0424.
35
+ - Outcome: Untrained seasonal-mixture prior barely exceeds Seasonal Naive overall and fails badly on 10-second and low-frequency configurations.
36
+
37
+ ## E1 step 1000, seed 17, screening
38
+ - Checkpoint SHA-256: `ebdd9eaa223c2bb6e38b8faec6f465a227fcd735b654a26f3b617a757addb0d3`.
39
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.581991195678711 seconds.
40
+ - Overall skill 0.210443; relative MASE 0.932765; relative WQL 0.668336.
41
+ - term skill: long=0.2339, medium=0.2517, short=0.1848.
42
+ - domain skill: Econ/Fin=-0.1600, Energy=0.0730, Healthcare=-0.0312, Nature=0.3679, Sales=0.2919, Transport=0.3892, Web/CloudOps=0.2547.
43
+ - frequency skill: A=0.3078, D=0.2651, H=0.3157, M=-0.3962, Q=0.0682, S=-0.6697, T=0.2839, W=0.0983.
44
+ - variates skill: multivariate=0.2140, univariate=0.2076.
45
+ - Outcome: Improves the control by 0.2095 screening skill after about 34 seconds on one H100. Selected for first neural publication and full validation.
46
+
47
+ ## E1 step 1000, full validation
48
+ - Checkpoint SHA-256: `see model_manifest.json`.
49
+ - Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds.
50
+ - Overall skill 0.206132; relative MASE 0.931220; relative WQL 0.676774.
51
+ - term skill: long=0.2265, medium=0.2444, short=0.1829.
52
+ - domain skill: Econ/Fin=-0.1543, Energy=0.0590, Healthcare=-0.0112, Nature=0.3688, Sales=0.3043, Transport=0.3878, Web/CloudOps=0.2461.
53
+ - frequency skill: A=0.2746, D=0.2676, H=0.3116, M=-0.3493, Q=0.0397, S=-0.6697, T=0.2712, W=0.1025.
54
+ - variates skill: multivariate=0.2097, univariate=0.2033.
55
+ - Outcome: Full 151,170-instance validation skill 0.2061, with no failed configurations. Package inference took 29.5 seconds while training shared the sole GPU. First neural publication verified.
56
+
57
+ ## E1 step 2000, screening
58
+ - Checkpoint SHA-256: `a513ac4f03aceb93a860d5e5eca70010c0101fdea794df4a9a8ae472647fb9c9`.
59
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.98806357383728 seconds.
60
+ - Overall skill 0.249671; relative MASE 0.890745; relative WQL 0.632048.
61
+ - term skill: long=0.2727, medium=0.2872, short=0.2257.
62
+ - domain skill: Econ/Fin=-0.0533, Energy=0.1151, Healthcare=0.1665, Nature=0.4084, Sales=0.2984, Transport=0.3867, Web/CloudOps=0.2855.
63
+ - frequency skill: A=0.3280, D=0.2894, H=0.3291, M=-0.1483, Q=0.1703, S=-0.4627, T=0.3239, W=0.1185.
64
+ - variates skill: multivariate=0.2588, univariate=0.2423.
65
+ - Outcome: Improves screening skill to 0.2497 after 66.8 seconds of training; candidate for replacement.
66
+
67
+ ## E1 step 3000, screening
68
+ - Checkpoint SHA-256: `74da538d2365426496a12c965c0c0cdc1d3962a798bd2e2c5fed950c1f663f30`.
69
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.051600933074951 seconds.
70
+ - Overall skill 0.246085; relative MASE 0.894210; relative WQL 0.635631.
71
+ - term skill: long=0.2835, medium=0.2774, short=0.2187.
72
+ - domain skill: Econ/Fin=-0.1111, Energy=0.1198, Healthcare=-0.0532, Nature=0.3956, Sales=0.3188, Transport=0.4123, Web/CloudOps=0.3004.
73
+ - frequency skill: A=0.3478, D=0.2585, H=0.3298, M=-0.3174, Q=0.1517, S=-0.6889, T=0.3620, W=0.1126.
74
+ - variates skill: multivariate=0.2552, univariate=0.2388.
75
+ - Outcome: Slight regression to 0.2461 relative to step 2000. Negative checkpoint-selection result; not selected.
76
+
77
+ ## E2 fixed longer-history feature ablation, step 2000 seed 17
78
+ - Checkpoint SHA-256: `25ac85db67c041c92870e2ea2e8b198bb768f5c5ed64f42b78d6ec207ffe3a18`.
79
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.066685438156128 seconds.
80
+ - Overall skill 0.249089; relative MASE 0.890661; relative WQL 0.633088.
81
+ - term skill: long=0.2741, medium=0.2855, short=0.2248.
82
+ - domain skill: Econ/Fin=-0.0532, Energy=0.1146, Healthcare=0.1651, Nature=0.4048, Sales=0.2986, Transport=0.3880, Web/CloudOps=0.2859.
83
+ - frequency skill: A=0.3273, D=0.2892, H=0.3291, M=-0.1495, Q=0.1705, S=-0.4627, T=0.3228, W=0.1166.
84
+ - variates skill: multivariate=0.2572, univariate=0.2426.
85
+ - Outcome: No training. Changed only history available to seasonal summaries from 4,096 to 16,384 points, with the encoder unchanged. Skill decreased 0.24967 to 0.24909. Rejected. Validation 10-second histories are shorter than one daily cycle, so additional history cannot supply that feature.
86
+
87
+ ## E1 step 4000, screening
88
+ - Checkpoint SHA-256: `f1b4e5f798688a56a693daf799fa21e69ec21c9c1710cae8dafbdb833c9ee069`.
89
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.961170196533203 seconds.
90
+ - Overall skill 0.266471; relative MASE 0.874789; relative WQL 0.615080.
91
+ - term skill: long=0.2537, medium=0.2846, short=0.2643.
92
+ - domain skill: Econ/Fin=-0.0360, Energy=0.1306, Healthcare=0.1810, Nature=0.3894, Sales=0.3301, Transport=0.4253, Web/CloudOps=0.3121.
93
+ - frequency skill: A=0.3647, D=0.2978, H=0.3375, M=-0.0981, Q=0.1458, S=-0.2890, T=0.3375, W=0.1196.
94
+ - variates skill: multivariate=0.2648, univariate=0.2678.
95
+ - Outcome: Best ungated checkpoint so far; improved short-horizon performance, with some long-horizon regression.
96
+
97
+ ## E1 step 6000, screening
98
+ - Checkpoint SHA-256: `f38cdb1b49938007c20bdfdfa7c4fc7d7aba6516192f388f37088891411eab7f`.
99
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.802650451660156 seconds.
100
+ - Overall skill 0.258313; relative MASE 0.878300; relative WQL 0.626324.
101
+ - term skill: long=0.2951, medium=0.3035, short=0.2254.
102
+ - domain skill: Econ/Fin=-0.0599, Energy=0.1417, Healthcare=0.2750, Nature=0.3683, Sales=0.3181, Transport=0.4116, Web/CloudOps=0.2761.
103
+ - frequency skill: A=0.3490, D=0.2962, H=0.3475, M=-0.0679, Q=0.1442, S=-0.6390, T=0.3416, W=0.0785.
104
+ - variates skill: multivariate=0.2482, univariate=0.2662.
105
+ - Outcome: Overall regression relative to step 4000 despite improvement on medium and long horizons. Not selected by overall skill.
106
+
107
+ ## E3 seasonal confidence gate, step 4000 seed 17
108
+ - Checkpoint SHA-256: `f1b4e5f798688a56a693daf799fa21e69ec21c9c1710cae8dafbdb833c9ee069`.
109
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.475942373275757 seconds.
110
+ - Overall skill 0.301779; relative MASE 0.827721; relative WQL 0.588981.
111
+ - term skill: long=0.3338, medium=0.3656, short=0.2627.
112
+ - domain skill: Econ/Fin=-0.0087, Energy=0.1326, Healthcare=0.1954, Nature=0.3891, Sales=0.3285, Transport=0.4242, Web/CloudOps=0.4509.
113
+ - frequency skill: A=0.3647, D=0.2945, H=0.3455, M=-0.0632, Q=0.1395, S=0.3700, T=0.3389, W=0.1159.
114
+ - variates skill: multivariate=0.3379, univariate=0.2716.
115
+ - Outcome: No additional training. Fixed gate: weight=clip(1 - mean squared seasonal difference / (0.25 * context variance), 0, 0.98). Blend neural quantiles with a last-four-cycle seasonal mean and Gaussian intervals based on seasonal differences. Each instance uses only its own context; no optimized or adapted parameters. Skill increases 0.26647 to 0.30178; selected for full validation.
116
+
117
+ ## E3 step 4000 gate, full validation
118
+ - Checkpoint SHA-256: `see model_manifest.json`.
119
+ - Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds.
120
+ - Overall skill 0.296168; relative MASE 0.830141; relative WQL 0.596742.
121
+ - term skill: long=0.3262, medium=0.3621, short=0.2569.
122
+ - domain skill: Econ/Fin=-0.0444, Energy=0.1210, Healthcare=0.2106, Nature=0.3890, Sales=0.3389, Transport=0.4244, Web/CloudOps=0.4426.
123
+ - frequency skill: A=0.2806, D=0.2946, H=0.3404, M=-0.0364, Q=0.1048, S=0.3700, T=0.3291, W=0.1093.
124
+ - variates skill: multivariate=0.3332, univariate=0.2652.
125
+ - Outcome: Selected and published. Full validation skill 0.296168 versus 0.206132 for the initial neural package; no failures. Full inference took 39.8 seconds while sharing one GPU with training. This is validation skill, not a held-out reward claim.
126
+
127
+ ## E1 step 8000, seed 17, ungated screening
128
+ - Checkpoint SHA-256: `ebbae91cb50acf1b1436fcbcdce1637195dd6e5006580d3d8e94a4e102aed0ad`.
129
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.500704050064087 seconds.
130
+ - Overall skill 0.276275; relative MASE 0.864160; relative WQL 0.606113.
131
+ - term skill: long=0.2954, medium=0.3094, short=0.2557.
132
+ - domain skill: Econ/Fin=-0.0085, Energy=0.1522, Healthcare=0.1826, Nature=0.3866, Sales=0.3192, Transport=0.4212, Web/CloudOps=0.3315.
133
+ - frequency skill: A=0.3679, D=0.3262, H=0.3533, M=-0.2016, Q=0.1316, S=-0.4192, T=0.3605, W=0.1103.
134
+ - variates skill: multivariate=0.2735, univariate=0.2785.
135
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
136
+
137
+ ## E1 step 8000, seed 17, gated screening
138
+ - Checkpoint SHA-256: `ebbae91cb50acf1b1436fcbcdce1637195dd6e5006580d3d8e94a4e102aed0ad`.
139
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.228765964508057 seconds.
140
+ - Overall skill 0.312772; relative MASE 0.813977; relative WQL 0.580216.
141
+ - term skill: long=0.3671, medium=0.3752, short=0.2645.
142
+ - domain skill: Econ/Fin=-0.0003, Energy=0.1512, Healthcare=0.1999, Nature=0.3863, Sales=0.3176, Transport=0.4184, Web/CloudOps=0.4791.
143
+ - frequency skill: A=0.3679, D=0.3227, H=0.3559, M=-0.1576, Q=0.1357, S=0.3651, T=0.3604, W=0.1062.
144
+ - variates skill: multivariate=0.3530, univariate=0.2790.
145
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
146
+
147
+ ## E1 step 10000, seed 17, ungated screening
148
+ - Checkpoint SHA-256: `3845afb6035396030b9a5182037287db092814d68caa4c96a7c415eb1d3b3a0a`.
149
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.094600439071655 seconds.
150
+ - Overall skill 0.285838; relative MASE 0.855761; relative WQL 0.595993.
151
+ - term skill: long=0.2974, medium=0.3249, short=0.2658.
152
+ - domain skill: Econ/Fin=0.0083, Energy=0.1537, Healthcare=0.1904, Nature=0.3858, Sales=0.3164, Transport=0.4217, Web/CloudOps=0.3674.
153
+ - frequency skill: A=0.3494, D=0.3058, H=0.3594, M=-0.1439, Q=0.1128, S=-0.2516, T=0.3685, W=0.1234.
154
+ - variates skill: multivariate=0.2917, univariate=0.2812.
155
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
156
+
157
+ ## E1 step 10000, seed 17, gated screening
158
+ - Checkpoint SHA-256: `3845afb6035396030b9a5182037287db092814d68caa4c96a7c415eb1d3b3a0a`.
159
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.704133749008179 seconds.
160
+ - Overall skill 0.317743; relative MASE 0.805746; relative WQL 0.577695.
161
+ - term skill: long=0.3656, medium=0.3815, short=0.2718.
162
+ - domain skill: Econ/Fin=0.0087, Energy=0.1540, Healthcare=0.2110, Nature=0.3855, Sales=0.3148, Transport=0.4194, Web/CloudOps=0.4916.
163
+ - frequency skill: A=0.3494, D=0.3033, H=0.3612, M=-0.1027, Q=0.1231, S=0.3756, T=0.3699, W=0.1199.
164
+ - variates skill: multivariate=0.3600, univariate=0.2821.
165
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
166
+
167
+ ## E1 step 12000, seed 17, ungated screening
168
+ - Checkpoint SHA-256: `629130a69f89561219b286c1e805d89b8b4662fce0e4b75e731e8764d9066e98`.
169
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.807793855667114 seconds.
170
+ - Overall skill 0.284471; relative MASE 0.856118; relative WQL 0.598027.
171
+ - term skill: long=0.2877, medium=0.3155, short=0.2710.
172
+ - domain skill: Econ/Fin=0.0294, Energy=0.1544, Healthcare=0.2252, Nature=0.3903, Sales=0.3151, Transport=0.4273, Web/CloudOps=0.3413.
173
+ - frequency skill: A=0.3430, D=0.3172, H=0.3585, M=-0.1807, Q=0.1231, S=-0.2708, T=0.3565, W=0.1685.
174
+ - variates skill: multivariate=0.2854, univariate=0.2837.
175
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
176
+
177
+ ## E1 step 12000, seed 17, gated screening
178
+ - Checkpoint SHA-256: `629130a69f89561219b286c1e805d89b8b4662fce0e4b75e731e8764d9066e98`.
179
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.750269889831543 seconds.
180
+ - Overall skill 0.315453; relative MASE 0.812477; relative WQL 0.576760.
181
+ - term skill: long=0.3585, medium=0.3794, short=0.2715.
182
+ - domain skill: Econ/Fin=0.0081, Energy=0.1534, Healthcare=0.2414, Nature=0.3899, Sales=0.3136, Transport=0.4251, Web/CloudOps=0.4722.
183
+ - frequency skill: A=0.3430, D=0.3141, H=0.3577, M=-0.1400, Q=0.1249, S=0.3722, T=0.3572, W=0.1641.
184
+ - variates skill: multivariate=0.3552, univariate=0.2820.
185
+ - Outcome: Included in final checkpoint selection; compare to weight-averaged result below.
186
+
187
+ ## E4 stochastic weight average, seed 17, gated screening
188
+ - Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`.
189
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.737564325332642 seconds.
190
+ - Overall skill 0.320612; relative MASE 0.803931; relative WQL 0.574139.
191
+ - term skill: long=0.3654, medium=0.3823, short=0.2769.
192
+ - domain skill: Econ/Fin=0.0210, Energy=0.1663, Healthcare=0.2341, Nature=0.3839, Sales=0.3192, Transport=0.4246, Web/CloudOps=0.4812.
193
+ - frequency skill: A=0.3645, D=0.3114, H=0.3584, M=-0.0937, Q=0.1411, S=0.3729, T=0.3725, W=0.1398.
194
+ - variates skill: multivariate=0.3557, univariate=0.2913.
195
+ - Outcome: Arithmetic weight average of steps 8000, 9000, 10000, 11000 and 12000. Total underlying training 349.9 seconds on one H100 for 12,000 steps / 1,536,000 windows. Averaging uses no validation labels or training updates. Screening skill 0.320612 exceeds the best individual checkpoint 0.317743; selected for full validation.
196
+
197
+ ## E3 confidence and quantile-width sweep
198
+ - Fixed global settings, selected only on validation; no model updates. Seed and checkpoint: E1 step 8000, seed 17.
199
+ - Measured CPU time: 10.7 seconds. The original threshold 0.25 and width multiplier 1.0 won; no tuned change was adopted.
200
+ - (variance threshold, width multiplier) (0.25, 1.0): skill 0.312772; term skills {'short': 0.2645319168347662, 'medium': 0.37524061562171485, 'long': 0.36711552655262625}.
201
+ - (variance threshold, width multiplier) (0.5, 1.0): skill 0.311338; term skills {'short': 0.26128183571880415, 'medium': 0.3766834137570718, 'long': 0.36686872500364487}.
202
+ - (variance threshold, width multiplier) (0.25, 0.75): skill 0.310114; term skills {'short': 0.26357949467631236, 'medium': 0.3710044838302994, 'long': 0.36223509497654094}.
203
+ - (variance threshold, width multiplier) (0.1, 1.0): skill 0.309380; term skills {'short': 0.2645827018541862, 'medium': 0.3687788042390393, 'long': 0.3590704635989247}.
204
+ - (variance threshold, width multiplier) (0.25, 1.25): skill 0.308716; term skills {'short': 0.25806263726485956, 'medium': 0.3732424245969126, 'long': 0.3664492202082874}.
205
+ - (variance threshold, width multiplier) (0.5, 0.75): skill 0.308480; term skills {'short': 0.2599791649373039, 'medium': 0.3724274186615034, 'long': 0.36196930941343286}.
206
+ - (variance threshold, width multiplier) (0.5, 1.25): skill 0.307830; term skills {'short': 0.25575126666422066, 'medium': 0.3747816871597687, 'long': 0.3663051398261168}.
207
+ - (variance threshold, width multiplier) (0.1, 0.75): skill 0.306923; term skills {'short': 0.26386190560263856, 'medium': 0.3650190620286501, 'long': 0.35398875275507513}.
208
+ - (variance threshold, width multiplier) (0.1, 1.25): skill 0.305043; term skills {'short': 0.2579337472130613, 'medium': 0.36611831669487493, 'long': 0.3583403545682865}.
209
+ - (variance threshold, width multiplier) (1.0, 1.0): skill 0.300332; term skills {'short': 0.24300377373135085, 'medium': 0.37515035650362993, 'long': 0.3625716315021771}.
210
+ - (variance threshold, width multiplier) (1.0, 0.75): skill 0.297470; term skills {'short': 0.24163138399697548, 'medium': 0.37101264403024414, 'long': 0.3577626408389879}.
211
+ - (variance threshold, width multiplier) (1.0, 1.25): skill 0.296900; term skills {'short': 0.23759298244372884, 'medium': 0.3732464838258517, 'long': 0.3619922948184182}.
212
+ - (variance threshold, width multiplier) (0.0, 1.0): skill 0.276275; term skills {'short': 0.25565045294773825, 'medium': 0.30935443355536374, 'long': 0.29541709470756516}.
213
+ - (variance threshold, width multiplier) (0.0, 0.75): skill 0.274035; term skills {'short': 0.2552205537396286, 'medium': 0.30589300644316675, 'long': 0.289930620063797}.
214
+ - (variance threshold, width multiplier) (0.0, 1.25): skill 0.271354; term skills {'short': 0.2486798921582145, 'medium': 0.30569315727356094, 'long': 0.29429049771287774}.
215
+
216
+ ## E5 capacity and exponential averaging
217
+ - Hypothesis: increased capacity reduces residual errors after direct-horizon training; exponential weight averaging reduces checkpoint noise.
218
+ - Changed factors: width 512, six encoder and four decoder layers, 37,002,816 parameters; 24,000-step schedule at 2e-4; seed 23. Same source sample, mixture, synthetic generator, batch 128 and horizon distribution as E1. Training-only EMA decay min(0.999, 1-1/(step+1)).
219
+ - Single H100; run in progress. Both raw and EMA snapshots will be evaluated across all 97 configurations. No causal claim isolates size from seed/schedule changes.
220
+
221
+ ## E4 averaged small model, full validation
222
+ - Checkpoint SHA-256: `see model_manifest.json`.
223
+ - Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds.
224
+ - Overall skill 0.315325; relative MASE 0.806359; relative WQL 0.581354.
225
+ - term skill: long=0.3584, medium=0.3790, short=0.2715.
226
+ - domain skill: Econ/Fin=-0.0034, Energy=0.1557, Healthcare=0.2457, Nature=0.3833, Sales=0.3308, Transport=0.4241, Web/CloudOps=0.4729.
227
+ - frequency skill: A=0.2978, D=0.3142, H=0.3526, M=-0.0698, Q=0.1192, S=0.3729, T=0.3632, W=0.1318.
228
+ - variates skill: multivariate=0.3509, univariate=0.2856.
229
+ - Outcome: Full validation skill 0.315325, relative MASE 0.806359 and relative WQL 0.581354, all 97 configurations valid. Inference took 37.2 seconds while sharing one H100 with training. Selected over the step-4000 gated package.
230
+
231
+ ## E6 sign symmetry, averaged small model, seed 17
232
+ - Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`.
233
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.13059401512146 seconds.
234
+ - Overall skill 0.328463; relative MASE 0.794174; relative WQL 0.567837.
235
+ - term skill: long=0.3740, medium=0.3863, short=0.2861.
236
+ - domain skill: Econ/Fin=0.0049, Energy=0.1627, Healthcare=0.2543, Nature=0.3978, Sales=0.3314, Transport=0.4439, Web/CloudOps=0.4889.
237
+ - frequency skill: A=0.2986, D=0.3191, H=0.3677, M=-0.0077, Q=0.1661, S=0.3711, T=0.3792, W=0.1244.
238
+ - variates skill: multivariate=0.3628, univariate=0.2998.
239
+ - Outcome: No additional training. Average the forecasts from x and negated x with quantile order reversed, then apply positivity and the same fixed seasonal gate. Screening skill rises 0.320612 to 0.328463. Hypothesis: sign symmetry reduces finite-sample neural bias. Selected for full validation.
240
+
241
+ ## E6 sign symmetry, averaged small model, full validation
242
+ - Checkpoint SHA-256: `see model_manifest.json`.
243
+ - Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds.
244
+ - Overall skill 0.323978; relative MASE 0.795773; relative WQL 0.574292.
245
+ - term skill: long=0.3666, medium=0.3832, short=0.2823.
246
+ - domain skill: Econ/Fin=-0.0072, Energy=0.1517, Healthcare=0.2646, Nature=0.3974, Sales=0.3433, Transport=0.4439, Web/CloudOps=0.4816.
247
+ - frequency skill: A=0.2459, D=0.3222, H=0.3623, M=0.0177, Q=0.1587, S=0.3711, T=0.3705, W=0.1158.
248
+ - variates skill: multivariate=0.3586, univariate=0.2951.
249
+ - Outcome: Full validation skill 0.323978 versus 0.315325 without sign symmetry. Relative MASE 0.795773, relative WQL 0.574292, zero failed configurations, 42.3 seconds of inference. Selected for atomic publication.
250
+
251
+ ## E7 coarse temporal resolution at inference, small averaged model
252
+ - Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`.
253
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.896855354309082 seconds.
254
+ - Overall skill 0.320862; relative MASE 0.803289; relative WQL 0.574174.
255
+ - term skill: long=0.3616, medium=0.3660, short=0.2861.
256
+ - domain skill: Econ/Fin=0.0049, Energy=0.1601, Healthcare=0.2543, Nature=0.4043, Sales=0.3314, Transport=0.4281, Web/CloudOps=0.4698.
257
+ - frequency skill: A=0.2986, D=0.3191, H=0.3444, M=-0.0077, Q=0.1661, S=0.3686, T=0.3804, W=0.1244.
258
+ - variates skill: multivariate=0.3567, univariate=0.2909.
259
+ - Outcome: Negative result: for horizons >=400, average the sign-symmetric prediction with a four-step-aggregated prediction from the same weights, then apply the unchanged seasonal gate. Screening skill falls from 0.328463 to 0.320862, so this is rejected. No training or fitted context parameters.
260
+
261
+ ## E8 median and predictable-series loss weighting
262
+ - Hypothesis: optimizing median error explicitly and weighting by context seasonal error aligns pretraining with MASE and quantile loss.
263
+ - Initial weights: E4 averaged small model, trained here from random initialization; no external pretrained assets.
264
+ - Changed factor: loss = mean over valid steps of 0.5 times mean pinball loss plus 0.25 times absolute median error, weighted per instance by clip(1/(0.25 + normalized context seasonal absolute difference), 0.25, 4). Weights are normalized across the batch. Training-only calculation; inference model unchanged.
265
+ - Seed 31, batch 256, 6,000 steps, AdamW 1e-4 with 400-step warmup and cosine decay, same source sample and synthetic generator. EMA as E5.
266
+ - Compute: 272.9 seconds elapsed on the sole H100, shared concurrently with E5. Underlying initial pretraining used 349.9 seconds.
267
+
268
+ ## E8 step 1000, seed 31, symmetric screening
269
+ - Checkpoint SHA-256: `e7cb5c4b4f04ba1ca873bc725f5e4345874520a96cbd3f079e4f631fd3c46d50`.
270
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.978966474533081 seconds.
271
+ - Overall skill 0.331642; relative MASE 0.791898; relative WQL 0.564091.
272
+ - term skill: long=0.3735, medium=0.3891, short=0.2910.
273
+ - domain skill: Econ/Fin=-0.0197, Energy=0.1668, Healthcare=0.2894, Nature=0.4040, Sales=0.3301, Transport=0.4439, Web/CloudOps=0.4906.
274
+ - frequency skill: A=0.2646, D=0.3158, H=0.3714, M=0.0669, Q=0.1387, S=0.3726, T=0.3764, W=0.1424.
275
+ - variates skill: multivariate=0.3652, univariate=0.3036.
276
+ - Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance.
277
+
278
+ ## E8 ema 1000, seed 31, symmetric screening
279
+ - Checkpoint SHA-256: `dab309aff5a3a28936391b84b3ebd9d5dfc208e53c1e1602e4f5c599e3004c33`.
280
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.16230034828186 seconds.
281
+ - Overall skill 0.332263; relative MASE 0.790121; relative WQL 0.564310.
282
+ - term skill: long=0.3745, medium=0.3873, short=0.2925.
283
+ - domain skill: Econ/Fin=0.0051, Energy=0.1638, Healthcare=0.2952, Nature=0.4011, Sales=0.3311, Transport=0.4450, Web/CloudOps=0.4919.
284
+ - frequency skill: A=0.3239, D=0.3220, H=0.3698, M=0.0488, Q=0.1636, S=0.3751, T=0.3783, W=0.1317.
285
+ - variates skill: multivariate=0.3653, univariate=0.3047.
286
+ - Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance.
287
+
288
+ ## E8 step 2000, seed 31, symmetric screening
289
+ - Checkpoint SHA-256: `111cf52c0662c60aebb44355135a65675a09d898995deeb4dd2f8f2b66339a0f`.
290
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.85259199142456 seconds.
291
+ - Overall skill 0.326318; relative MASE 0.796087; relative WQL 0.570097.
292
+ - term skill: long=0.3658, medium=0.3826, short=0.2873.
293
+ - domain skill: Econ/Fin=-0.0159, Energy=0.1477, Healthcare=0.3155, Nature=0.4038, Sales=0.3247, Transport=0.4419, Web/CloudOps=0.4862.
294
+ - frequency skill: A=0.2949, D=0.3163, H=0.3678, M=0.0654, Q=0.1519, S=0.3722, T=0.3655, W=0.1286.
295
+ - variates skill: multivariate=0.3573, univariate=0.3006.
296
+ - Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance.
297
+
298
+ ## E8 ema 2000, seed 31, symmetric screening
299
+ - Checkpoint SHA-256: `5fa525d923b4af5949f2415cf0ad0b325dae7623f07aae06b3131bdbda08c209`.
300
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.634822130203247 seconds.
301
+ - Overall skill 0.332843; relative MASE 0.789360; relative WQL 0.563874.
302
+ - term skill: long=0.3745, medium=0.3875, short=0.2936.
303
+ - domain skill: Econ/Fin=0.0007, Energy=0.1627, Healthcare=0.3135, Nature=0.4026, Sales=0.3309, Transport=0.4452, Web/CloudOps=0.4913.
304
+ - frequency skill: A=0.3152, D=0.3249, H=0.3696, M=0.0640, Q=0.1700, S=0.3757, T=0.3784, W=0.1261.
305
+ - variates skill: multivariate=0.3645, univariate=0.3065.
306
+ - Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance.
307
+
308
+ ## E8 step 4000, seed 31, symmetric screening
309
+ - Checkpoint SHA-256: `8ce9867a6005c28005b32d163254c088279f2a46febeadc433b403aeffc29066`.
310
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 20.403828620910645 seconds.
311
+ - Overall skill 0.333292; relative MASE 0.789778; relative WQL 0.562816.
312
+ - term skill: long=0.3723, medium=0.3857, short=0.2961.
313
+ - domain skill: Econ/Fin=-0.0157, Energy=0.1603, Healthcare=0.3279, Nature=0.4080, Sales=0.3286, Transport=0.4450, Web/CloudOps=0.4921.
314
+ - frequency skill: A=0.2821, D=0.3254, H=0.3697, M=0.0826, Q=0.1490, S=0.3718, T=0.3810, W=0.1182.
315
+ - variates skill: multivariate=0.3645, univariate=0.3073.
316
+ - Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance.
317
+
318
+ ## E8 ema 4000, seed 31, symmetric screening
319
+ - Checkpoint SHA-256: `e61535b34efac923328f1dd464f5ab8ab05913438f86125d8b933f1b166281d9`.
320
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.288180112838745 seconds.
321
+ - Overall skill 0.334221; relative MASE 0.787768; relative WQL 0.562681.
322
+ - term skill: long=0.3735, medium=0.3879, short=0.2964.
323
+ - domain skill: Econ/Fin=-0.0016, Energy=0.1638, Healthcare=0.3235, Nature=0.4037, Sales=0.3295, Transport=0.4477, Web/CloudOps=0.4916.
324
+ - frequency skill: A=0.3041, D=0.3326, H=0.3704, M=0.0629, Q=0.1674, S=0.3746, T=0.3813, W=0.1128.
325
+ - variates skill: multivariate=0.3653, univariate=0.3084.
326
+ - Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance.
327
+
328
+ ## E8 step 6000, seed 31, symmetric screening
329
+ - Checkpoint SHA-256: `15833e7668d9cd11ed55a4820b4700d71c6f734415d11490c7e8beb654abfa12`.
330
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 21.2668559551239 seconds.
331
+ - Overall skill 0.334430; relative MASE 0.788174; relative WQL 0.562038.
332
+ - term skill: long=0.3762, medium=0.3886, short=0.2953.
333
+ - domain skill: Econ/Fin=-0.0108, Energy=0.1611, Healthcare=0.3518, Nature=0.4037, Sales=0.3298, Transport=0.4457, Web/CloudOps=0.4924.
334
+ - frequency skill: A=0.2760, D=0.3360, H=0.3690, M=0.0736, Q=0.1605, S=0.3759, T=0.3813, W=0.1132.
335
+ - variates skill: multivariate=0.3660, univariate=0.3081.
336
+ - Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance.
337
+
338
+ ## E8 ema 6000, seed 31, symmetric screening
339
+ - Checkpoint SHA-256: `70a3768d667df75f0d6565e831cdca8cf7c179c8546252e5902f7b7ec68ab7aa`.
340
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 11.340764284133911 seconds.
341
+ - Overall skill 0.335038; relative MASE 0.787307; relative WQL 0.561630.
342
+ - term skill: long=0.3762, medium=0.3878, short=0.2968.
343
+ - domain skill: Econ/Fin=-0.0053, Energy=0.1637, Healthcare=0.3401, Nature=0.4031, Sales=0.3292, Transport=0.4464, Web/CloudOps=0.4934.
344
+ - frequency skill: A=0.2894, D=0.3329, H=0.3693, M=0.0767, Q=0.1622, S=0.3763, T=0.3828, W=0.1162.
345
+ - variates skill: multivariate=0.3659, univariate=0.3094.
346
+ - Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance.
347
+
348
+ ## E9 neural context 512 for horizons <=128, seed 17
349
+ - Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`.
350
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.416622161865234 seconds.
351
+ - Overall skill 0.320871; relative MASE 0.803968; relative WQL 0.573675.
352
+ - term skill: long=0.3740, medium=0.3863, short=0.2718.
353
+ - domain skill: Econ/Fin=0.0457, Energy=0.1466, Healthcare=0.2113, Nature=0.3887, Sales=0.3285, Transport=0.4330, Web/CloudOps=0.4911.
354
+ - frequency skill: A=0.2986, D=0.2904, H=0.3587, M=-0.0099, Q=0.1658, S=0.3756, T=0.3687, W=0.1716.
355
+ - variates skill: multivariate=0.3665, univariate=0.2822.
356
+ - Outcome: Only the neural input is shortened; the seasonal confidence gate retains 4096 points. 512 loses skill; 1024/2048 improve by less than 0.001 over the control. Not adopted pending a larger effect.
357
+
358
+ ## E9 neural context 1024 for horizons <=128, seed 17
359
+ - Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`.
360
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 19.072535276412964 seconds.
361
+ - Overall skill 0.329251; relative MASE 0.796444; relative WQL 0.564891.
362
+ - term skill: long=0.3740, medium=0.3863, short=0.2876.
363
+ - domain skill: Econ/Fin=0.0323, Energy=0.1629, Healthcare=0.1832, Nature=0.3978, Sales=0.3361, Transport=0.4415, Web/CloudOps=0.4998.
364
+ - frequency skill: A=0.2986, D=0.3031, H=0.3649, M=-0.0077, Q=0.1661, S=0.3761, T=0.3907, W=0.1240.
365
+ - variates skill: multivariate=0.3738, univariate=0.2915.
366
+ - Outcome: Only the neural input is shortened; the seasonal confidence gate retains 4096 points. 512 loses skill; 1024/2048 improve by less than 0.001 over the control. Not adopted pending a larger effect.
367
+
368
+ ## E9 neural context 2048 for horizons <=128, seed 17
369
+ - Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`.
370
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.426023244857788 seconds.
371
+ - Overall skill 0.329063; relative MASE 0.794285; relative WQL 0.566744.
372
+ - term skill: long=0.3740, medium=0.3863, short=0.2872.
373
+ - domain skill: Econ/Fin=0.0227, Energy=0.1628, Healthcare=0.2235, Nature=0.3975, Sales=0.3314, Transport=0.4448, Web/CloudOps=0.4931.
374
+ - frequency skill: A=0.2986, D=0.3154, H=0.3656, M=-0.0077, Q=0.1661, S=0.3738, T=0.3847, W=0.1224.
375
+ - variates skill: multivariate=0.3651, univariate=0.2989.
376
+ - Outcome: Only the neural input is shortened; the seasonal confidence gate retains 4096 points. 512 loses skill; 1024/2048 improve by less than 0.001 over the control. Not adopted pending a larger effect.
377
+
378
+ ## E10 fixed 50/50 ensemble diagnostic
379
+ - Checkpoint SHA-256: `see model_manifest.json`.
380
+ - Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 4.082070589065552 seconds.
381
+ - Overall skill 0.332712; relative MASE 0.791350; relative WQL 0.562676.
382
+ - term skill: long=0.3746, medium=0.3901, short=0.2921.
383
+ - domain skill: Econ/Fin=-0.0029, Energy=0.1641, Healthcare=0.3036, Nature=0.4055, Sales=0.3288, Transport=0.4500, Web/CloudOps=0.4870.
384
+ - frequency skill: A=0.2971, D=0.3243, H=0.3712, M=0.0353, Q=0.1843, S=0.3742, T=0.3778, W=0.1385.
385
+ - variates skill: multivariate=0.3658, univariate=0.3052.
386
+ - Outcome: Average of E8 EMA4000 and E5 EMA12000, both with sign symmetry and the same fixed seasonal gate. Skill 0.332712 is below E8 alone (0.334221). Rejected for now; both members would forecast every instance.
387
+
388
+ ## E8 EMA6000, full validation
389
+ - Checkpoint SHA-256: `see model_manifest.json`.
390
+ - Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds.
391
+ - Overall skill 0.330109; relative MASE 0.789610; relative WQL 0.568323.
392
+ - term skill: long=0.3687, medium=0.3851, short=0.2920.
393
+ - domain skill: Econ/Fin=-0.0223, Energy=0.1525, Healthcare=0.3475, Nature=0.4024, Sales=0.3415, Transport=0.4461, Web/CloudOps=0.4860.
394
+ - frequency skill: A=0.2370, D=0.3358, H=0.3639, M=0.0960, Q=0.1447, S=0.3763, T=0.3738, W=0.1061.
395
+ - variates skill: multivariate=0.3616, univariate=0.3039.
396
+ - Outcome: Full validation skill 0.330109, relative MASE 0.789610, relative WQL 0.568323, zero failed configurations. Inference took 48.1 seconds while sharing the one H100. Improves the previous published 0.323978 and is selected for atomic publication.
397
+
398
+ ## E11 matched corpus-coverage experiment
399
+ - Hypothesis: broader source coverage improves generalization after the initial model has plateaued.
400
+ - Expanded sample: 95 directories, 1,032,415 series, 5,653,290,832 points (22.613 GB), versus 357,789 series and 958,745,103 points (3.835 GB). Per-source cap rises from 24M to 192M points, Arrow record batches are shuffled within each selected shard, and the per-series crop cap rises from 131,072 to 1,048,576. The same deterministic directory-hash seeds and at most eight sampled shards per directory are used.
401
+ - Two matched continuations start from E8 EMA6000: original sample control and expanded sample. Both use seed 41, batch 256, the E8 loss, 6,000 steps, AdamW 1e-4 and the same schedule/EMA. Training uses only corpus/synthetic data.
402
+ - Runs share the single H100 with E5; CPU threads are limited to three per new trainer. Results and measured elapsed compute are pending.
403
+
404
+ ## E12 fixed continuity correction
405
+ - Hypothesis: a direct-horizon head can miss the immediate level of a smooth history, and a small decaying correction should reduce short-horizon error. No training or context fitting. E8 EMA6000 weights, seed 31.
406
+ - Fixed formula: ratio=mean(square(first differences))/variance over the last 512 points; w=clip(1-ratio/0.5,0,0.95); bias=w*(last value + median of the last eight differences - first forecast median). Add bias*exp(-step/tau) to each quantile, then retain the existing positivity rule. Skip sparse missing-value differences.
407
+ - Initial diagnostic needed a missing-value guard; invalid intermediate scores were discarded. A positivity-lookback mismatch in the probe was also corrected so tau=0 exactly reproduces the control.
408
+ - CPU sweep took 6.0 seconds; final verified control and all candidate scores follow. Tau 24 selected for package/full validation.
409
+ - tau=0: skill 0.335038, relative MASE 0.787307, relative WQL 0.561630, group skills {'term': {'short': 0.2967927346774093, 'medium': 0.38776799350809343, 'long': 0.37616349665047677}, 'domain': {'Econ/Fin': -0.005273788909573085, 'Energy': 0.16374587322817125, 'Healthcare': 0.34007707190705616, 'Nature': 0.4030815329292825, 'Sales': 0.32924485226314826, 'Transport': 0.4464324047455728, 'Web/CloudOps': 0.4934311796492926}, 'freq': {'A-DEC': 0.2893784388532201, 'Q-DEC': 0.16218093798601307, 'M': 0.07665328507242941, 'W-SUN': -0.31450314757766273, 'D': 0.332876404786148, 'H': 0.3693479345200832, '15T': 0.14228566862247327, 'W-FRI': 0.032405497411887585, '10T': 0.4887742379514316, 'W-TUE': 0.309664207244038, 'W-THU': 0.14794979612329628, 'W-WED': 0.29198895648742507, '5T': 0.5120305409377247, '10S': 0.3762720731817548}}.
410
+ - tau=2: skill 0.337508, relative MASE 0.783332, relative WQL 0.560293, group skills {'term': {'short': 0.30112159439110886, 'medium': 0.3882128168958763, 'long': 0.3763449044348186}, 'domain': {'Econ/Fin': 0.012010642573481944, 'Energy': 0.1687336419481582, 'Healthcare': 0.33847751009406857, 'Nature': 0.4038059435050727, 'Sales': 0.32920024652725177, 'Transport': 0.4463400575252827, 'Web/CloudOps': 0.4950030531002031}, 'freq': {'A-DEC': 0.2973561434987757, 'Q-DEC': 0.17698071591831765, 'M': 0.07233297868059718, 'W-SUN': -0.2582996069171355, 'D': 0.3346112879714367, 'H': 0.36855118351366944, '15T': 0.14569114456054433, 'W-FRI': 0.021432593572035197, '10T': 0.5064176027092252, 'W-TUE': 0.3132256284193611, 'W-THU': 0.1516542652623164, 'W-WED': 0.29198895648742507, '5T': 0.5121886153783087, '10S': 0.38181456512243606}}.
411
+ - tau=8: skill 0.339730, relative MASE 0.781190, relative WQL 0.558067, group skills {'term': {'short': 0.30468677533784194, 'medium': 0.3890128603479147, 'long': 0.3768542253336602}, 'domain': {'Econ/Fin': 0.04357586882889164, 'Energy': 0.17060177779549268, 'Healthcare': 0.3292576172809155, 'Nature': 0.4040895491577191, 'Sales': 0.32915095007230155, 'Transport': 0.4455718893158739, 'Web/CloudOps': 0.498582535356759}, 'freq': {'A-DEC': 0.30427943534005153, 'Q-DEC': 0.18739632573970566, 'M': 0.05811644843967234, 'W-SUN': -0.14993519310493708, 'D': 0.33691177813304396, 'H': 0.36800946318922256, '15T': 0.15562275067857723, 'W-FRI': 0.015293948848938421, '10T': 0.5022238811405833, 'W-TUE': 0.308852394109824, 'W-THU': 0.16531962754891327, 'W-WED': 0.29198895648742507, '5T': 0.5124270255950129, '10S': 0.3959332124123227}}.
412
+ - tau=24: skill 0.341604, relative MASE 0.780976, relative WQL 0.555056, group skills {'term': {'short': 0.30735425505077896, 'medium': 0.38984232067302926, 'long': 0.37791322023985785}, 'domain': {'Econ/Fin': 0.07789629542475163, 'Energy': 0.16814859423491146, 'Healthcare': 0.32219860777640197, 'Nature': 0.4027938268275436, 'Sales': 0.32911299366848257, 'Transport': 0.4440214473788372, 'Web/CloudOps': 0.505502554697025}, 'freq': {'A-DEC': 0.30701454754159097, 'Q-DEC': 0.18894276751813088, 'M': 0.04173508991923269, 'W-SUN': -0.06710914169849702, 'D': 0.33891978173454174, 'H': 0.36806701600948255, '15T': 0.16691265843751302, 'W-FRI': 0.011149977535114819, '10T': 0.48062823437029445, 'W-TUE': 0.3054618645258299, 'W-THU': 0.17135723270801106, 'W-WED': 0.29198895648742507, '5T': 0.5128629288387704, '10S': 0.42606586812368186}}.
413
+ - tau=64: skill 0.340824, relative MASE 0.783313, relative WQL 0.554713, group skills {'term': {'short': 0.3064164746371565, 'medium': 0.38779908004530583, 'long': 0.3787937309532532}, 'domain': {'Econ/Fin': 0.09969949435020342, 'Energy': 0.15974598777640392, 'Healthcare': 0.3189527251466179, 'Nature': 0.4009254556920715, 'Sales': 0.32909545704191134, 'Transport': 0.44166143132149305, 'Web/CloudOps': 0.5103628293774518}, 'freq': {'A-DEC': 0.3079352359976604, 'Q-DEC': 0.18879190434187287, 'M': 0.03049481695615497, 'W-SUN': -0.03231570437562303, 'D': 0.33992332397958547, 'H': 0.36593420410508737, '15T': 0.1654947222236236, 'W-FRI': 0.009213828856730832, '10T': 0.46016772262416383, 'W-TUE': 0.3040006089982843, 'W-THU': 0.17343046632698478, 'W-WED': 0.29198895648742507, '5T': 0.5128850832828526, '10S': 0.4486615108502494}}.
414
+ - tau=128: skill 0.338292, relative MASE 0.786639, relative WQL 0.556618, group skills {'term': {'short': 0.3043668884529205, 'medium': 0.38176748757743373, 'long': 0.37868472074438897}, 'domain': {'Econ/Fin': 0.10637792737302931, 'Energy': 0.1531270206619928, 'Healthcare': 0.31816668045459984, 'Nature': 0.39985518410953147, 'Sales': 0.3290895550941987, 'Transport': 0.4399018505526925, 'Web/CloudOps': 0.5082609219137205}, 'freq': {'A-DEC': 0.3082114553822066, 'Q-DEC': 0.1886335736447592, 'M': 0.026327746733658897, 'W-SUN': -0.021307580325764297, 'D': 0.34025742210101806, 'H': 0.3625439077766571, '15T': 0.1628300810039216, 'W-FRI': 0.00856370190545519, '10T': 0.4513327819863723, 'W-TUE': 0.30351149262807786, 'W-THU': 0.1740816133131421, 'W-WED': 0.29198895648742507, '5T': 0.512369368619311, '10S': 0.44352723463256316}}.
415
+
416
+ ## E12 continuity prior, full validation
417
+ - Checkpoint SHA-256: `see model_manifest.json`.
418
+ - Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds.
419
+ - Overall skill 0.336914; relative MASE 0.783869; relative WQL 0.560914.
420
+ - term skill: long=0.3705, medium=0.3876, short=0.3028.
421
+ - domain skill: Econ/Fin=0.0580, Energy=0.1590, Healthcare=0.3286, Nature=0.4018, Sales=0.3415, Transport=0.4438, Web/CloudOps=0.4980.
422
+ - frequency skill: A=0.2499, D=0.3408, H=0.3619, M=0.0606, Q=0.1682, S=0.4261, T=0.3809, W=0.1368.
423
+ - variates skill: multivariate=0.3731, univariate=0.3066.
424
+ - Outcome: Full validation skill 0.336914 versus 0.330109 without the correction, relative MASE 0.783869 and relative WQL 0.560914; zero failures. Package inference took 69.8 seconds while three trainers shared the sole H100. Selected for atomic publication.
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Direct seasonal quantile foundation forecaster
2
+
3
+ Run `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6,758,720-parameter encoder/decoder was trained from random initialization on source-balanced samples of the 95 allow-listed GiftEvalPretrain directories and newly generated synthetic data. It predicts nine quantiles directly, with no autoregressive rollout and no inference-time fitting. Fixed context summaries include recent levels, damped slopes and seasonal means. A fixed confidence rule blends forecasts with a four-cycle seasonal average where seasonal differences are small relative to context variance; all thresholds are in model_manifest.json and seasonal.py. Forecasts average predictions of the history and its sign reversal. A fixed continuity correction for smooth histories then decays over 24 steps; continuity.py contains its complete formula.
4
+
5
+ The runtime is pinned in requirements.txt. Per-instance normalization is computed by the model; no external statistics are needed. The output quantiles are monotone by construction. See EXPERIMENTS.md and validation_report.json for measured results, limitations and checkpoint identity. Validation skill is not on the held-out reward scale.
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "d": 256,
3
+ "heads": 8,
4
+ "enc_layers": 4,
5
+ "dec_layers": 3,
6
+ "patch": 32,
7
+ "max_context": 4096,
8
+ "max_horizon": 1024
9
+ }
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/infer.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export OMP_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=4
4
+ exec python3 "$(dirname "$(readlink -f "$0")")/predict.py" "$1" "$2"
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/model.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon)
51
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
52
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
53
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
54
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
55
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
56
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
57
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
58
+ with torch.no_grad():
59
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
60
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
61
+
62
+ @staticmethod
63
+ def standardize(ctx):
64
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
65
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
66
+ mu=x.sum(-1,keepdim=True)/count
67
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
68
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
69
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
70
+ return z,valid,mu,scale
71
+
72
+ @staticmethod
73
+ def features(z,valid,periods,h):
74
+ b,c=z.shape;dev=z.device
75
+ def avg(k):
76
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
77
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
78
+ last=z.gather(1,last_idx[:,None])[:,0]
79
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
80
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
81
+ t=torch.arange(h,device=dev)[None,:]
82
+ for j in range(2):
83
+ p=periods[:,j:j+1].clamp(min=1)
84
+ anchor=c-p+t%p
85
+ vals=[];masks=[]
86
+ for cycle in range(4):
87
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
88
+ ok=(idx>=0)&valid.gather(1,safe)
89
+ vals.append(z.gather(1,safe));masks.append(ok)
90
+ vals=torch.stack(vals);masks=torch.stack(masks)
91
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
92
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
93
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
94
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
95
+ k=min(128,max(4,c//4));recent=avg(k)
96
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
97
+ slope=((recent-older)/k).clamp(-.03,.03)
98
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
99
+ bases.append(trend)
100
+ return torch.stack(bases,-1)
101
+
102
+ def forward(self,ctx,periods,horizon):
103
+ p=self.patch;h=math.ceil(horizon/p)*p
104
+ ctx=ctx[:,-self.max_context:]
105
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
106
+ z,valid,mu,scale=self.standardize(ctx)
107
+ b,c=z.shape;nt=c//p
108
+ base=self.features(z,valid,periods,h)
109
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
110
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
111
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,torch.full((b,1),math.log1p(h)/8,device=z.device)),-1)
112
+ emb=self.metadata(meta)[:,None]
113
+ x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb
114
+ for layer in self.encoder:x=layer(x,pmask)
115
+ q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb
116
+ for layer in self.decoder:q=layer(q,pmask,x)
117
+ out=self.head(self.norm(q)).view(b,h,18).float()
118
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
119
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
120
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
121
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
122
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
123
+ return quant,mu,scale
124
+
125
+ @torch.no_grad()
126
+ def predict(self,ctx,periods,horizon):
127
+ q,mu,scale=self(ctx,periods,horizon)
128
+ q=q*scale[:,:,None]+mu[:,:,None]
129
+ # Positivity is a fixed context rule, as in released foundation forecasters.
130
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
131
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
132
+ return q.transpose(1,2)
133
+
134
+ def loss_fn(model,ctx,target,periods):
135
+ q,mu,scale=model(ctx,periods,target.shape[-1])
136
+ valid=torch.isfinite(target)
137
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
138
+ err=y[:,:,None]-q
139
+ levels=torch.arange(1,10,device=q.device)/10
140
+ pin=torch.maximum(levels*err,(levels-1)*err).mean(-1)
141
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
142
+ return per.mean()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/model_manifest.json ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "direct-seasonal-quantile-continuity",
3
+ "contract": "timeseries-forecast/v1",
4
+ "parameters": 6758720,
5
+ "pretrained_assets": [],
6
+ "sources_used": [
7
+ "gifteval_pretrain/BEIJING_SUBWAY_30MIN",
8
+ "gifteval_pretrain/HZMETRO",
9
+ "gifteval_pretrain/LOS_LOOP",
10
+ "gifteval_pretrain/PEMS03",
11
+ "gifteval_pretrain/PEMS04",
12
+ "gifteval_pretrain/PEMS07",
13
+ "gifteval_pretrain/PEMS08",
14
+ "gifteval_pretrain/PEMS_BAY",
15
+ "gifteval_pretrain/Q-TRAFFIC",
16
+ "gifteval_pretrain/SHMETRO",
17
+ "gifteval_pretrain/alibaba_cluster_trace_2018",
18
+ "gifteval_pretrain/australian_electricity_demand",
19
+ "gifteval_pretrain/azure_vm_traces_2017",
20
+ "gifteval_pretrain/bdg-2_bear",
21
+ "gifteval_pretrain/bdg-2_fox",
22
+ "gifteval_pretrain/bdg-2_panther",
23
+ "gifteval_pretrain/bdg-2_rat",
24
+ "gifteval_pretrain/bitcoin_with_missing",
25
+ "gifteval_pretrain/borealis",
26
+ "gifteval_pretrain/borg_cluster_data_2011",
27
+ "gifteval_pretrain/buildings_900k",
28
+ "gifteval_pretrain/bull",
29
+ "gifteval_pretrain/cdc_fluview_ilinet",
30
+ "gifteval_pretrain/cdc_fluview_who_nrevss",
31
+ "gifteval_pretrain/china_air_quality",
32
+ "gifteval_pretrain/cif_2016_12",
33
+ "gifteval_pretrain/cif_2016_6",
34
+ "gifteval_pretrain/cmip6_2000",
35
+ "gifteval_pretrain/cmip6_2005",
36
+ "gifteval_pretrain/cmip6_2010",
37
+ "gifteval_pretrain/cockatoo",
38
+ "gifteval_pretrain/covid19_energy",
39
+ "gifteval_pretrain/covid_mobility",
40
+ "gifteval_pretrain/elecdemand",
41
+ "gifteval_pretrain/elf",
42
+ "gifteval_pretrain/era5_2010",
43
+ "gifteval_pretrain/era5_2011",
44
+ "gifteval_pretrain/era5_2012",
45
+ "gifteval_pretrain/era5_2013",
46
+ "gifteval_pretrain/era5_2014",
47
+ "gifteval_pretrain/era5_2015",
48
+ "gifteval_pretrain/era5_2016",
49
+ "gifteval_pretrain/era5_2017",
50
+ "gifteval_pretrain/era5_2018",
51
+ "gifteval_pretrain/extended_web_traffic_with_missing",
52
+ "gifteval_pretrain/favorita_sales",
53
+ "gifteval_pretrain/favorita_transactions",
54
+ "gifteval_pretrain/gfc12_load",
55
+ "gifteval_pretrain/gfc14_load",
56
+ "gifteval_pretrain/gfc17_load",
57
+ "gifteval_pretrain/godaddy",
58
+ "gifteval_pretrain/hog",
59
+ "gifteval_pretrain/ideal",
60
+ "gifteval_pretrain/kaggle_web_traffic_weekly",
61
+ "gifteval_pretrain/kdd2022",
62
+ "gifteval_pretrain/largest_2017",
63
+ "gifteval_pretrain/largest_2018",
64
+ "gifteval_pretrain/largest_2019",
65
+ "gifteval_pretrain/largest_2020",
66
+ "gifteval_pretrain/largest_2021",
67
+ "gifteval_pretrain/lcl",
68
+ "gifteval_pretrain/london_smart_meters_with_missing",
69
+ "gifteval_pretrain/m1_monthly",
70
+ "gifteval_pretrain/m1_quarterly",
71
+ "gifteval_pretrain/m1_yearly",
72
+ "gifteval_pretrain/m5",
73
+ "gifteval_pretrain/monash_m3_monthly",
74
+ "gifteval_pretrain/monash_m3_other",
75
+ "gifteval_pretrain/monash_m3_quarterly",
76
+ "gifteval_pretrain/nn5_daily_with_missing",
77
+ "gifteval_pretrain/nn5_weekly",
78
+ "gifteval_pretrain/oikolab_weather",
79
+ "gifteval_pretrain/pdb",
80
+ "gifteval_pretrain/project_tycho",
81
+ "gifteval_pretrain/residential_load_power",
82
+ "gifteval_pretrain/residential_pv_power",
83
+ "gifteval_pretrain/rideshare_with_missing",
84
+ "gifteval_pretrain/sceaux",
85
+ "gifteval_pretrain/smart",
86
+ "gifteval_pretrain/solar_power",
87
+ "gifteval_pretrain/spain",
88
+ "gifteval_pretrain/subseasonal",
89
+ "gifteval_pretrain/subseasonal_precip",
90
+ "gifteval_pretrain/sunspot_with_missing",
91
+ "gifteval_pretrain/taxi_30min",
92
+ "gifteval_pretrain/tourism_quarterly",
93
+ "gifteval_pretrain/tourism_yearly",
94
+ "gifteval_pretrain/traffic_hourly",
95
+ "gifteval_pretrain/traffic_weekly",
96
+ "gifteval_pretrain/uber_tlc_daily",
97
+ "gifteval_pretrain/uber_tlc_hourly",
98
+ "gifteval_pretrain/vehicle_trips_with_missing",
99
+ "gifteval_pretrain/wiki-rolling_nips",
100
+ "gifteval_pretrain/wind_farms_with_missing",
101
+ "gifteval_pretrain/wind_power",
102
+ "synthetic:own direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; seeds 17 and 31"
103
+ ],
104
+ "weights_sha256": "70a3768d667df75f0d6565e831cdca8cf7c179c8546252e5902f7b7ec68ab7aa",
105
+ "training_step": 6000,
106
+ "config": {
107
+ "d": 256,
108
+ "heads": 8,
109
+ "enc_layers": 4,
110
+ "dec_layers": 3,
111
+ "patch": 32,
112
+ "max_context": 4096,
113
+ "max_horizon": 1024
114
+ },
115
+ "notes": "Random initialization, direct encoder-decoder quantile forecasts with fixed per-instance seasonal context summaries. No fitting or parameter adaptation at inference. All 95 allow-listed directories sampled. Validation only used for selection. Fixed smooth-history continuity correction uses only the current context and model forecast, with a 24-step exponential decay. Continued pretraining on the same allowed corpus with median/quantile loss weighted by context seasonal error; no validation training. Fixed context confidence gate blends highly repeatable seasonal histories with a four-cycle seasonal average and residual-based intervals; no parameters are fit at inference.",
116
+ "symmetric_averaging": true,
117
+ "continuity": {
118
+ "decay_steps": 24,
119
+ "variance_ratio_threshold": 0.5,
120
+ "maximum_weight": 0.95,
121
+ "lookback": 512,
122
+ "slope_median_differences": 8
123
+ },
124
+ "training_seed": 31,
125
+ "training_continuation_from": {
126
+ "checkpoint": "swa008000-012000.pt",
127
+ "sha256": "a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db",
128
+ "origin": "random initialization in this research run"
129
+ },
130
+ "exponential_weight_average": true,
131
+ "postprocessing": {
132
+ "seasonal_difference_variance_threshold": 0.25,
133
+ "maximum_blend": 0.98,
134
+ "cycles_averaged": 4,
135
+ "inference_fitting": false
136
+ }
137
+ }
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/continuation/data.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class Sampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ w=min(len(values),20_000_000)**.25
19
+ if name.startswith(('era5_','cmip6_')):w*=.35
20
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
21
+ weights.append(w)
22
+ self.probs=np.array(weights)/sum(weights)
23
+
24
+ def synthetic(self,n,p):
25
+ r=self.rng;t=np.arange(n,dtype=np.float32)
26
+ # New generator: damped trends, random Fourier seasonality, AR noise,
27
+ # intermittent demand, changepoints, and randomly scaled observation noise.
28
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
29
+ x=np.full(n,level,np.float32)
30
+ if r.random()<.8:
31
+ for period in p:
32
+ if period<2:continue
33
+ for k in range(1,int(r.integers(2,5))):
34
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
35
+ if r.random()<.6:
36
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
37
+ x+=slope*tau*(1-np.exp(-t/tau))
38
+ noise=r.normal(0,sigma,n).astype(np.float32)
39
+ if r.random()<.5:
40
+ from scipy.signal import lfilter
41
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
42
+ x+=noise
43
+ if r.random()<.2:
44
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
45
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
46
+ if r.random()<.1:x=np.maximum(0,x)
47
+ return x.astype(np.float32)
48
+
49
+ def sample(self,batch,context=2048,horizon=1024):
50
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
51
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
52
+ for b,d in enumerate(ds):
53
+ if r.random()<self.synthetic_fraction:
54
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
55
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
56
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
57
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
58
+ # Random cutoffs retain short sources, with unavailable future steps masked.
59
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
60
+ nc=min(context,cut)
61
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
62
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
63
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
64
+ if r.random()<.12 and l>=4*(context+horizon):
65
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
66
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
67
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
68
+ else:periods[b]=self.periods[d][i]
69
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
70
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
71
+ return ctx,tgt,periods
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/continuation/train.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json,math,time,os,sys,shutil,hashlib
2
+ from pathlib import Path
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import numpy as np
5
+ import torch
6
+ from model import DirectForecaster,loss_fn
7
+ from data import Sampler
8
+
9
+ def save(model,path,step,args,opt=None):
10
+ ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)}
11
+ if opt is not None:ck['opt']=opt.state_dict()
12
+ tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path)
13
+
14
+ def main():
15
+ ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True)
16
+ ap.add_argument('--steps',type=int,default=12000);ap.add_argument('--batch',type=int,default=128);ap.add_argument('--context',type=int,default=4096)
17
+ ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3)
18
+ ap.add_argument('--lr',type=float,default=3e-4);ap.add_argument('--seed',type=int,default=17);ap.add_argument('--save-every',type=int,default=1000)
19
+ ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args()
20
+ torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed)
21
+ torch.backends.cuda.matmul.allow_tf32=True
22
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
23
+ model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda()
24
+ opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True)
25
+ # Exponential averaging is a training-only stabilization; inference remains fixed.
26
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()}
27
+ startstep=0
28
+ if a.resume:
29
+ ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step']
30
+ if 'opt' in ck:opt.load_state_dict(ck['opt'])
31
+ if a.initialize_from:
32
+ ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model'])
33
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()}
34
+ sampler=Sampler(a.packed,seed=a.seed+startstep)
35
+ params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2))
36
+ print('parameters',params,flush=True)
37
+ rng=np.random.default_rng(a.seed+startstep)
38
+ def nextbatch():
39
+ c=int(rng.choice([512,1024,2048,a.context],p=[.1,.15,.35,.4]));h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5]))
40
+ return sampler.sample(a.batch,c,h)
41
+ pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[]
42
+ for step in range(startstep+1,a.steps+1):
43
+ arrays=future.result();future=pool.submit(nextbatch)
44
+ x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays]
45
+ lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps))))
46
+ for g in opt.param_groups:g['lr']=lr
47
+ opt.zero_grad(set_to_none=True)
48
+ with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p)
49
+ loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
50
+ if torch.isfinite(gn):
51
+ opt.step()
52
+ with torch.no_grad():
53
+ decay=min(.999,1-1/(step+1))
54
+ for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay)
55
+ losses.append(float(loss.detach()))
56
+ if step%50==0:
57
+ rec={'step':step,'loss':float(np.mean(losses)),'seconds':round(time.time()-t0,1),'lr':lr,'grad_norm':float(gn),'context':x.shape[-1],'horizon':y.shape[-1]}
58
+ print(json.dumps(rec),flush=True)
59
+ with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n')
60
+ losses=[]
61
+ stop=a.stop_file and Path(a.stop_file).exists()
62
+ if step%a.save_every==0 or step==a.steps or stop:
63
+ save(model,out/f'step{step:06d}.pt',step,a)
64
+ save(model,out/'last.pt',step,a,opt)
65
+ ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True}
66
+ path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path)
67
+ if stop:break
68
+ pool.shutdown()
69
+
70
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/data.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class Sampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ w=min(len(values),20_000_000)**.25
19
+ if name.startswith(('era5_','cmip6_')):w*=.35
20
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
21
+ weights.append(w)
22
+ self.probs=np.array(weights)/sum(weights)
23
+
24
+ def synthetic(self,n,p):
25
+ r=self.rng;t=np.arange(n,dtype=np.float32)
26
+ # New generator: damped trends, random Fourier seasonality, AR noise,
27
+ # intermittent demand, changepoints, and randomly scaled observation noise.
28
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
29
+ x=np.full(n,level,np.float32)
30
+ if r.random()<.8:
31
+ for period in p:
32
+ if period<2:continue
33
+ for k in range(1,int(r.integers(2,5))):
34
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
35
+ if r.random()<.6:
36
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
37
+ x+=slope*tau*(1-np.exp(-t/tau))
38
+ noise=r.normal(0,sigma,n).astype(np.float32)
39
+ if r.random()<.5:
40
+ from scipy.signal import lfilter
41
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
42
+ x+=noise
43
+ if r.random()<.2:
44
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
45
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
46
+ if r.random()<.1:x=np.maximum(0,x)
47
+ return x.astype(np.float32)
48
+
49
+ def sample(self,batch,context=2048,horizon=1024):
50
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
51
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
52
+ for b,d in enumerate(ds):
53
+ if r.random()<self.synthetic_fraction:
54
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
55
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
56
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
57
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
58
+ # Random cutoffs retain short sources, with unavailable future steps masked.
59
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
60
+ nc=min(context,cut)
61
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
62
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
63
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
64
+ if r.random()<.12 and l>=4*(context+horizon):
65
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
66
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
67
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
68
+ else:periods[b]=self.periods[d][i]
69
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
70
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
71
+ return ctx,tgt,periods
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/pack.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data."""
2
+ import json,time,hashlib,concurrent.futures,argparse
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pyarrow as pa
6
+
7
+ ROOT=Path('/workspace/data/gifteval_pretrain')
8
+
9
+ def pack_dir(job):
10
+ name,out,cap=job
11
+ rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little'))
12
+ files=sorted((ROOT/name).glob('data-*.arrow'))
13
+ rng.shuffle(files)
14
+ # Spread large-source samples across eight shards rather than taking one contiguous slice.
15
+ files=files[:min(8,len(files))]
16
+ meta=[]; total=0; offsets=[0]; t0=time.time()
17
+ with open(out/f'{name}.bin','wb') as dest:
18
+ for file in files:
19
+ quota=max(1,cap//len(files)); kept=0
20
+ with pa.memory_map(str(file),'r') as f:
21
+ table=pa.ipc.open_stream(f).read_all()
22
+ freq=table.column('freq')[0].as_py() if table.num_rows else ''
23
+ for target in table.column('target').chunks:
24
+ if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type):
25
+ target=target.values
26
+ off=target.offsets.to_numpy()
27
+ flat=target.values.to_numpy(zero_copy_only=False)
28
+ ids=np.arange(len(target));rng.shuffle(ids)
29
+ for i in ids:
30
+ x=flat[off[i]:off[i+1]]
31
+ if len(x)<16 or not np.isfinite(x).any():continue
32
+ # Cap very long series at a random contiguous year-sized segment.
33
+ if len(x)>131072:
34
+ start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072]
35
+ x=np.asarray(x,dtype=np.float32)
36
+ x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total)
37
+ meta.append({'dataset':name,'freq':freq,'length':len(x)})
38
+ if kept>=quota:break
39
+ if kept>=quota:break
40
+ np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64))
41
+ (out/f'{name}.json').write_text(json.dumps(meta))
42
+ return name,total,len(meta),round(time.time()-t0,1)
43
+
44
+ def main():
45
+ ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--cap',type=int,default=16000000);ap.add_argument('--workers',type=int,default=6);a=ap.parse_args()
46
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
47
+ names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.'))
48
+ lock=json.loads(Path('/workspace/data/sources.lock.json').read_text())
49
+ allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories']
50
+ assert set(names)<=set(allowed)
51
+ with concurrent.futures.ThreadPoolExecutor(a.workers) as pool:
52
+ for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True)
53
+ counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names}
54
+ (out/'meta.json').write_text(json.dumps({'dirs':[n for n in names if counts[n]],'counts':counts,'per_directory_point_cap':a.cap,'seed':'sha256(directory) little-endian first 4 bytes','min_length':16},indent=2))
55
+
56
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/provenance/train.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json,math,time,os,sys,shutil,hashlib
2
+ from pathlib import Path
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import numpy as np
5
+ import torch
6
+ from model import DirectForecaster,loss_fn
7
+ from data import Sampler
8
+
9
+ def save(model,path,step,args,opt=None):
10
+ ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)}
11
+ if opt is not None:ck['opt']=opt.state_dict()
12
+ tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path)
13
+
14
+ def main():
15
+ ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True)
16
+ ap.add_argument('--steps',type=int,default=12000);ap.add_argument('--batch',type=int,default=128);ap.add_argument('--context',type=int,default=4096)
17
+ ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3)
18
+ ap.add_argument('--lr',type=float,default=3e-4);ap.add_argument('--seed',type=int,default=17);ap.add_argument('--save-every',type=int,default=1000)
19
+ ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args()
20
+ torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed)
21
+ torch.backends.cuda.matmul.allow_tf32=True
22
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
23
+ model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda()
24
+ opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True)
25
+ startstep=0
26
+ if a.resume:
27
+ ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step']
28
+ if 'opt' in ck:opt.load_state_dict(ck['opt'])
29
+ sampler=Sampler(a.packed,seed=a.seed+startstep)
30
+ params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2))
31
+ print('parameters',params,flush=True)
32
+ rng=np.random.default_rng(a.seed+startstep)
33
+ def nextbatch():
34
+ c=int(rng.choice([512,1024,2048,a.context],p=[.1,.15,.35,.4]));h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5]))
35
+ return sampler.sample(a.batch,c,h)
36
+ pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[]
37
+ for step in range(startstep+1,a.steps+1):
38
+ arrays=future.result();future=pool.submit(nextbatch)
39
+ x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays]
40
+ lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps))))
41
+ for g in opt.param_groups:g['lr']=lr
42
+ opt.zero_grad(set_to_none=True)
43
+ with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p)
44
+ loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
45
+ if torch.isfinite(gn):opt.step()
46
+ losses.append(float(loss.detach()))
47
+ if step%50==0:
48
+ rec={'step':step,'loss':float(np.mean(losses)),'seconds':round(time.time()-t0,1),'lr':lr,'grad_norm':float(gn),'context':x.shape[-1],'horizon':y.shape[-1]}
49
+ print(json.dumps(rec),flush=True)
50
+ with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n')
51
+ losses=[]
52
+ stop=a.stop_file and Path(a.stop_file).exists()
53
+ if step%a.save_every==0 or step==a.steps or stop:
54
+ save(model,out/f'step{step:06d}.pt',step,a)
55
+ save(model,out/'last.pt',step,a,opt)
56
+ if stop:break
57
+ pool.shutdown()
58
+
59
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Runtime pins recorded from the contributor's working environment on 2026-09-17 (Python 3.11).
2
+ # torch comes from the pytorch/pytorch:2.14.0-cuda12.6-cudnn9-runtime base image (cu130 needs driver >= 580).
3
+ torch==2.14.0
4
+ numpy==2.4.6
5
+ h5py==3.16.0
6
+ pandas==2.3.3
7
+ scipy==1.17.1
8
+ pyarrow==25.0.1
9
+ huggingface-hub==0.36.2
10
+ einops==0.8.2
11
+ safetensors==0.8.0
12
+ pytest==9.1.1
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/seasonal.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A fixed confidence gate for highly repeatable history; no fitted parameters."""
2
+ import numpy as np
3
+
4
+ def apply_gate(ctx,periods,quant,threshold=.25,strength=1.):
5
+ # Each row uses only its own context. Quantile blending preserves ordering.
6
+ b,_,h=quant.shape
7
+ out=quant.copy()
8
+ for i in range(b):
9
+ x=ctx[i];valid=np.isfinite(x)
10
+ if not valid.any():continue
11
+ x=x[np.flatnonzero(valid)[0]:]
12
+ best=None
13
+ for p in periods[i]:
14
+ p=int(p)
15
+ if p<2 or len(x)<3*p:continue
16
+ k=min(len(x)//p,8);history=x[-k*p:]
17
+ pairs=np.isfinite(history[p:])&np.isfinite(history[:-p])
18
+ if pairs.sum()<p:continue
19
+ err=history[p:][pairs]-history[:-p][pairs]
20
+ var=float(np.nanvar(history))
21
+ ratio=float(np.mean(err.astype(np.float64)**2))/(var+1e-12)
22
+ weight=float(np.clip(1-ratio/threshold,0,.98))*strength
23
+ if weight<=0 or (best is not None and weight<=best[0]):continue
24
+ seasons=history.reshape(k,p)
25
+ # Last four cycles reduce observation noise while retaining phase.
26
+ available=np.isfinite(seasons[-4:]).sum(0)
27
+ mu=np.divide(np.nansum(seasons[-4:],axis=0),available,
28
+ out=np.full(p,np.nan,np.float32),where=available>0)
29
+ # Error of a season relative to the previous one, corrected for averaging.
30
+ sigma=float(np.sqrt(np.mean(err.astype(np.float64)**2)/2*(1+1/min(k,4))))
31
+ idx=np.arange(h)%p;median=mu[idx]
32
+ z=np.array([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0,.2533471031,.5244005127,.8416212336,1.2815515655])
33
+ sq=median[None]+z[:,None]*sigma
34
+ sq=np.where(np.isfinite(sq),sq,quant[i])
35
+ if np.nanmin(x)>=0:sq=np.maximum(0,sq)
36
+ best=(weight,sq)
37
+ if best is not None:out[i]=(1-best[0])*quant[i]+best[0]*best[1]
38
+ return out
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/ts_io.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1).
2
+
3
+ Three things live here because the case builder, the grader, the starter and
4
+ the reference packages must agree on them exactly:
5
+
6
+ 1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality
7
+ tables, transcribed from gift-eval `src/gift_eval/data.py` at commit
8
+ db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables,
9
+ not runtime derivations, so a pandas alias rename cannot silently change a
10
+ horizon or a seasonality.
11
+ 2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval
12
+ (`<dataset>/[<freq>/]data-00000-of-00001.arrow`), implemented with pyarrow
13
+ only, and the rolling-window instance generator that reproduces
14
+ `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval.
15
+ 3. The case-file format: one HDF5 file per (dataset, frequency, term) config
16
+ holding every forecast instance's context, and one HDF5 prediction file per
17
+ config holding the mean and the nine decile forecasts.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import functools
22
+ import hashlib
23
+ import json
24
+ import math
25
+ import os
26
+ import re
27
+ import stat
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+
32
+ CONTRACT = "timeseries-forecast/v1"
33
+ QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
34
+ CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md)
35
+ TEST_SPLIT = 0.1
36
+ MAX_WINDOW = 20
37
+ TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15}
38
+ PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60}
39
+ M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48}
40
+ # gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1
41
+ BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1}
42
+ _UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"}
43
+ _FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$")
44
+
45
+
46
+ def parse_freq(freq: str) -> tuple[int, str]:
47
+ """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H')."""
48
+ m = _FREQ_RE.match(freq.strip())
49
+ if not m:
50
+ raise ValueError(f"unrecognised frequency {freq!r}")
51
+ n = int(m.group(1) or 1)
52
+ unit = _UNIT_ALIASES.get(m.group(2), m.group(2))
53
+ if unit not in BASE_SEASONALITY:
54
+ raise ValueError(f"unrecognised frequency unit in {freq!r}")
55
+ return n, unit
56
+
57
+
58
+ def prediction_length(dataset: str, freq: str, term: str) -> int:
59
+ _, unit = parse_freq(freq)
60
+ table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP
61
+ return TERM_MULTIPLIER[term] * table[unit]
62
+
63
+
64
+ def seasonality(freq: str) -> int:
65
+ n, unit = parse_freq(freq)
66
+ base = BASE_SEASONALITY[unit]
67
+ q, r = divmod(base, n)
68
+ return q if r == 0 else 1
69
+
70
+
71
+ def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int:
72
+ if "m4" in dataset:
73
+ return 1
74
+ w = math.ceil(TEST_SPLIT * min_series_length / pred_len)
75
+ return min(max(1, w), MAX_WINDOW)
76
+
77
+
78
+ def config_id(dataset: str, freq_unit: str, term: str) -> str:
79
+ """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique)."""
80
+ return f"{dataset.split('/')[0]}__{freq_unit}__{term}"
81
+
82
+
83
+ # gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names
84
+ LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H",
85
+ "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M",
86
+ "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"}
87
+ LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain",
88
+ "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"}
89
+
90
+
91
+ def leaderboard_key(dataset: str, term: str) -> str:
92
+ """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased)."""
93
+ base, _, sub = dataset.partition("/")
94
+ freq = sub if sub else LEADERBOARD_FREQ[base]
95
+ base = base.lower()
96
+ return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}"
97
+
98
+
99
+ VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it
100
+
101
+
102
+ # ----------------------------------------------------------------------------- Arrow readers
103
+
104
+
105
+ def arrow_path(root: Path, dataset: str) -> Path:
106
+ return Path(root) / dataset / "data-00000-of-00001.arrow"
107
+
108
+
109
+ def read_arrow_dataset(root: Path, dataset: str):
110
+ """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset.
111
+
112
+ `series` is a list of float32 arrays of shape (D, T); univariate datasets
113
+ give D = 1. Missing values are NaN as stored.
114
+ """
115
+ import pyarrow as pa
116
+
117
+ with open(arrow_path(root, dataset), "rb") as f:
118
+ table = pa.ipc.open_stream(f).read_all()
119
+ item_ids = table.column("item_id").to_pylist()
120
+ starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]")
121
+ freq = table.column("freq")[0].as_py()
122
+ target = table.column("target").combine_chunks()
123
+ series = []
124
+ if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type):
125
+ # multivariate: fixed_size_list<list<float>> (or list<list<float>>) -> (D, T) per item
126
+ if pa.types.is_fixed_size_list(target.type):
127
+ k = target.type.list_size
128
+ outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k
129
+ else:
130
+ outer_off = target.offsets.to_numpy()
131
+ inner = target.values
132
+ inner_off = inner.offsets.to_numpy()
133
+ flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32)
134
+ for i in range(len(target)):
135
+ d0, d1 = outer_off[i], outer_off[i + 1]
136
+ rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)]
137
+ if len({len(r) for r in rows}) != 1:
138
+ raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length")
139
+ series.append(np.stack(rows))
140
+ else:
141
+ off = target.offsets.to_numpy()
142
+ flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32)
143
+ for i in range(len(target)):
144
+ series.append(flat[off[i]:off[i + 1]][None, :])
145
+ return item_ids, starts, freq, series
146
+
147
+
148
+ def read_arrow_index(root: Path, dataset: str):
149
+ """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints).
150
+
151
+ The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can
152
+ hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does.
153
+ """
154
+ import pyarrow as pa
155
+
156
+ with open(arrow_path(root, dataset), "rb") as f:
157
+ table = pa.ipc.open_stream(f).read_all()
158
+ item_ids = table.column("item_id").to_pylist()
159
+ starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]")
160
+ freq = table.column("freq")[0].as_py()
161
+ target = table.column("target").combine_chunks()
162
+ if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type):
163
+ inner = target.values
164
+ off = inner.offsets.to_numpy()
165
+ flat = inner.values.to_numpy(zero_copy_only=False)
166
+ width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None
167
+ if width is None:
168
+ outer = target.offsets.to_numpy()
169
+ first = outer[:-1]
170
+ else:
171
+ first = (np.arange(len(target)) + target.offset) * width
172
+ else:
173
+ off = target.offsets.to_numpy()
174
+ flat = target.values.to_numpy(zero_copy_only=False)
175
+ first = np.arange(len(target))
176
+ lengths = (off[first + 1] - off[first]).astype(np.int64)
177
+ fingerprints = []
178
+ for i, start in enumerate(first):
179
+ a, b = off[start], off[start + 1]
180
+ head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b]
181
+ fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16]))
182
+ return item_ids, starts, freq, lengths, fingerprints
183
+
184
+
185
+ def config_table(root: Path, dataset: str, term: str) -> dict:
186
+ """Protocol quantities of one (dataset, term) config, read from the Arrow file."""
187
+ item_ids, starts, freq, series = read_arrow_dataset(root, dataset)
188
+ n, unit = parse_freq(freq)
189
+ lengths = np.array([s.shape[1] for s in series])
190
+ pred_len = prediction_length(dataset, freq, term)
191
+ windows = n_windows(dataset, int(lengths.min()), pred_len)
192
+ return {
193
+ "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term,
194
+ "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term),
195
+ "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows,
196
+ "n_series": len(series), "n_variates": int(series[0].shape[0]),
197
+ "min_length": int(lengths.min()), "max_length": int(lengths.max()),
198
+ "n_test_instances": len(series) * windows, "n_valid_instances": len(series),
199
+ }
200
+
201
+
202
+ def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]:
203
+ """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L."""
204
+ return [length - pred_len * windows + k * pred_len for k in range(windows)]
205
+
206
+
207
+ def valid_cutoff(length: int, pred_len: int, windows: int) -> int:
208
+ """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which
209
+ `training_dataset` (offset -L*(W+1)) excludes.
210
+
211
+ A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test
212
+ regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation
213
+ data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the
214
+ per-config upper bound.
215
+ """
216
+ return length - pred_len * (windows + 1)
217
+
218
+
219
+ def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int:
220
+ """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid)."""
221
+ import pandas as pd
222
+
223
+ multiple, _ = parse_freq(freq)
224
+ f = _pandas_freq(freq)
225
+ # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps
226
+ delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n
227
+ return int(delta) // multiple
228
+
229
+
230
+ @functools.lru_cache(maxsize=4096)
231
+ def _base_period(start: str, freq: str):
232
+ import pandas as pd
233
+
234
+ return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq))
235
+
236
+
237
+ def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str:
238
+ """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`."""
239
+ return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat()
240
+
241
+
242
+ def _pandas_freq(freq: str) -> str:
243
+ n, unit = parse_freq(freq)
244
+ anchor = freq.split("-")[1] if "-" in freq else ""
245
+ new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit]
246
+ return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}"
247
+
248
+
249
+ # ----------------------------------------------------------------------------- case files
250
+
251
+
252
+ def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None):
253
+ """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance;
254
+ cohorts: verifier invocation group per instance (see make_cases.py), optional."""
255
+ import h5py
256
+
257
+ d = int(meta["n_variates"])
258
+ lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64)
259
+ offsets = np.zeros(len(contexts) + 1, dtype=np.int64)
260
+ offsets[1:] = np.cumsum(lengths * d)
261
+ values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32)
262
+ path.parent.mkdir(parents=True, exist_ok=True)
263
+ with h5py.File(path, "w") as f:
264
+ f.create_dataset("values", data=values)
265
+ f.create_dataset("offsets", data=offsets)
266
+ f.create_dataset("context_length", data=lengths)
267
+ f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64))
268
+ f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype()))
269
+ f.create_dataset("window", data=np.asarray(windows, dtype=np.int64))
270
+ f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype()))
271
+ if cohorts is not None:
272
+ f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64))
273
+ for k, v in meta.items():
274
+ f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v
275
+ f.attrs["contract"] = CONTRACT
276
+ f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS)
277
+
278
+
279
+ def write_case_subset(src: "CaseFile", indices, dst: Path):
280
+ """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied)."""
281
+ import h5py
282
+
283
+ indices = np.asarray(indices, dtype=np.int64)
284
+ contexts = [src.context(int(i)) for i in indices]
285
+ meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")}
286
+ write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices],
287
+ [src.forecast_start[i] for i in indices], src.history_length[indices])
288
+ with h5py.File(dst, "r+") as f:
289
+ f.create_dataset("cohort", data=src.cohort[indices])
290
+ f.create_dataset("source_index", data=indices)
291
+
292
+
293
+ class CaseFile:
294
+ """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32."""
295
+
296
+ def __init__(self, path: Path):
297
+ import h5py
298
+
299
+ self.path = Path(path)
300
+ self._f = h5py.File(self.path, "r")
301
+ self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()}
302
+ self.n_variates = int(self.meta["n_variates"])
303
+ self.prediction_length = int(self.meta["prediction_length"])
304
+ self.offsets = self._f["offsets"][()]
305
+ self.n = len(self.offsets) - 1
306
+ self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]]
307
+ self.window = self._f["window"][()]
308
+ self.context_length = self._f["context_length"][()]
309
+ self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]]
310
+ self.history_length = self._f["history_length"][()]
311
+ self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64)
312
+ self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n)
313
+
314
+ def context(self, i: int) -> np.ndarray:
315
+ v = self._f["values"][self.offsets[i]:self.offsets[i + 1]]
316
+ return v.reshape(self.n_variates, -1)
317
+
318
+ def contexts(self):
319
+ values = self._f["values"][()]
320
+ for i in range(self.n):
321
+ yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1)
322
+
323
+ def close(self):
324
+ self._f.close()
325
+
326
+
327
+ def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None):
328
+ """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS."""
329
+ import h5py
330
+
331
+ mean = np.asarray(mean, dtype=np.float32)
332
+ quantiles = np.asarray(quantiles, dtype=np.float32)
333
+ if mean.ndim != 3 or quantiles.ndim != 4 or quantiles.shape[:2] != mean.shape[:2] or quantiles.shape[3] != mean.shape[2] or quantiles.shape[2] != len(QUANTILE_LEVELS):
334
+ raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}")
335
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
336
+ with h5py.File(path, "w") as f:
337
+ f.create_dataset("mean", data=mean)
338
+ f.create_dataset("quantiles", data=quantiles)
339
+ f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS)
340
+ f.attrs["contract"] = CONTRACT
341
+ for k, v in (meta or {}).items():
342
+ f.attrs[k] = v
343
+
344
+
345
+ PREDICTION_DATASETS = ("mean", "quantiles")
346
+
347
+
348
+ def open_package_h5(path, names=PREDICTION_DATASETS):
349
+ """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets.
350
+
351
+ The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow
352
+ anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can
353
+ point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block."""
354
+ import h5py
355
+
356
+ st = os.lstat(path)
357
+ if not stat.S_ISREG(st.st_mode):
358
+ raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)")
359
+ f = h5py.File(path, "r")
360
+ try:
361
+ for name in names:
362
+ link = f.get(name, getlink=True)
363
+ if link is None:
364
+ raise KeyError(f"no {name!r} dataset")
365
+ if not isinstance(link, h5py.HardLink):
366
+ raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read")
367
+ d = f[name]
368
+ if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external:
369
+ raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)")
370
+ except Exception:
371
+ f.close()
372
+ raise
373
+ return f
374
+
375
+
376
+ def prediction_shapes(path: Path):
377
+ """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory."""
378
+ with open_package_h5(path) as f:
379
+ attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()}
380
+ return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs
381
+
382
+
383
+ def read_prediction_file(path: Path, expect: tuple | None = None):
384
+ """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read."""
385
+ with open_package_h5(path) as f:
386
+ got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape)
387
+ want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2])
388
+ if expect is not None and (got_m != tuple(expect) or got_q != want_q):
389
+ raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}")
390
+ return f["mean"][()], f["quantiles"][()]
391
+
392
+
393
+ def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict):
394
+ """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64."""
395
+ import h5py
396
+
397
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
398
+ with h5py.File(path, "w") as f:
399
+ f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32))
400
+ f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64))
401
+ for k, v in meta.items():
402
+ f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v
403
+
404
+
405
+ def read_truth_file(path: Path):
406
+ import h5py
407
+
408
+ with h5py.File(path, "r") as f:
409
+ meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()}
410
+ return f["labels"][()], f["seasonal_error"][()], meta
411
+
412
+
413
+ def seasonal_error(history: np.ndarray, m: int) -> np.ndarray:
414
+ """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate.
415
+
416
+ Reproduces `gluonts.model.evaluation._get_data_batch` with
417
+ `mask_invalid_label=True`: the history is a masked array, so the mean of
418
+ |x[t] - x[t-m]| runs over the pairs where both observations are finite.
419
+ If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with
420
+ no valid pair gets NaN.
421
+ """
422
+ t = history.shape[-1]
423
+ lag = m if m <= t else 1
424
+ if t <= lag:
425
+ return np.full(history.shape[0], np.nan)
426
+ x = history.astype(np.float64)
427
+ diff = np.abs(x[:, lag:] - x[:, :-lag])
428
+ valid = np.isfinite(diff)
429
+ count = valid.sum(axis=-1)
430
+ with np.errstate(invalid="ignore", divide="ignore"):
431
+ out = np.where(valid, diff, 0.0).sum(axis=-1) / count
432
+ out[count == 0] = np.nan
433
+ return out
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S007/validation_report.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/direct_large/model.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon)
51
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
52
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
53
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
54
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
55
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
56
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
57
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
58
+ with torch.no_grad():
59
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
60
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
61
+
62
+ @staticmethod
63
+ def standardize(ctx):
64
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
65
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
66
+ mu=x.sum(-1,keepdim=True)/count
67
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
68
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
69
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
70
+ return z,valid,mu,scale
71
+
72
+ @staticmethod
73
+ def features(z,valid,periods,h):
74
+ b,c=z.shape;dev=z.device
75
+ def avg(k):
76
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
77
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
78
+ last=z.gather(1,last_idx[:,None])[:,0]
79
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
80
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
81
+ t=torch.arange(h,device=dev)[None,:]
82
+ for j in range(2):
83
+ p=periods[:,j:j+1].clamp(min=1)
84
+ anchor=c-p+t%p
85
+ vals=[];masks=[]
86
+ for cycle in range(4):
87
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
88
+ ok=(idx>=0)&valid.gather(1,safe)
89
+ vals.append(z.gather(1,safe));masks.append(ok)
90
+ vals=torch.stack(vals);masks=torch.stack(masks)
91
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
92
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
93
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
94
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
95
+ k=min(128,max(4,c//4));recent=avg(k)
96
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
97
+ slope=((recent-older)/k).clamp(-.03,.03)
98
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
99
+ bases.append(trend)
100
+ return torch.stack(bases,-1)
101
+
102
+ def forward(self,ctx,periods,horizon):
103
+ p=self.patch;h=math.ceil(horizon/p)*p
104
+ ctx=ctx[:,-self.max_context:]
105
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
106
+ z,valid,mu,scale=self.standardize(ctx)
107
+ b,c=z.shape;nt=c//p
108
+ base=self.features(z,valid,periods,h)
109
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
110
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
111
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,torch.full((b,1),math.log1p(h)/8,device=z.device)),-1)
112
+ emb=self.metadata(meta)[:,None]
113
+ x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb
114
+ for layer in self.encoder:x=layer(x,pmask)
115
+ q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb
116
+ for layer in self.decoder:q=layer(q,pmask,x)
117
+ out=self.head(self.norm(q)).view(b,h,18).float()
118
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
119
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
120
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
121
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
122
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
123
+ return quant,mu,scale
124
+
125
+ @torch.no_grad()
126
+ def predict(self,ctx,periods,horizon):
127
+ q,mu,scale=self(ctx,periods,horizon)
128
+ q=q*scale[:,:,None]+mu[:,:,None]
129
+ # Positivity is a fixed context rule, as in released foundation forecasters.
130
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
131
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
132
+ return q.transpose(1,2)
133
+
134
+ def loss_fn(model,ctx,target,periods):
135
+ q,mu,scale=model(ctx,periods,target.shape[-1])
136
+ valid=torch.isfinite(target)
137
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
138
+ err=y[:,:,None]-q
139
+ levels=torch.arange(1,10,device=q.device)/10
140
+ pin=torch.maximum(levels*err,(levels-1)*err).mean(-1)
141
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
142
+ return per.mean()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/large_corpus/data.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class Sampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values)
19
+ w=min(weight_points,20_000_000)**.25
20
+ if name.startswith(('era5_','cmip6_')):w*=.35
21
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
22
+ weights.append(w)
23
+ self.probs=np.array(weights)/sum(weights)
24
+
25
+ def synthetic(self,n,p):
26
+ r=self.rng;t=np.arange(n,dtype=np.float32)
27
+ # New generator: damped trends, random Fourier seasonality, AR noise,
28
+ # intermittent demand, changepoints, and randomly scaled observation noise.
29
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
30
+ x=np.full(n,level,np.float32)
31
+ if r.random()<.8:
32
+ for period in p:
33
+ if period<2:continue
34
+ for k in range(1,int(r.integers(2,5))):
35
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
36
+ if r.random()<.6:
37
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
38
+ x+=slope*tau*(1-np.exp(-t/tau))
39
+ noise=r.normal(0,sigma,n).astype(np.float32)
40
+ if r.random()<.5:
41
+ from scipy.signal import lfilter
42
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
43
+ x+=noise
44
+ if r.random()<.2:
45
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
46
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
47
+ if r.random()<.1:x=np.maximum(0,x)
48
+ return x.astype(np.float32)
49
+
50
+ def sample(self,batch,context=2048,horizon=1024):
51
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
52
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
53
+ for b,d in enumerate(ds):
54
+ if r.random()<self.synthetic_fraction:
55
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
56
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
57
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
58
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
59
+ # Random cutoffs retain short sources, with unavailable future steps masked.
60
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
61
+ nc=min(context,cut)
62
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
63
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
64
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
65
+ if r.random()<.12 and l>=4*(context+horizon):
66
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
67
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
68
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
69
+ else:periods[b]=self.periods[d][i]
70
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
71
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
72
+ sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1))
73
+ return ctx*sign,tgt*sign,periods
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/large_corpus/model.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon,recency_features=recency_features)
51
+ self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None
52
+ if self.recency is not None:nn.init.zeros_(self.recency.weight)
53
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
54
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
55
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
56
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
57
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
58
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
59
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
60
+ with torch.no_grad():
61
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
62
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
63
+
64
+ @staticmethod
65
+ def standardize(ctx):
66
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
67
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
68
+ mu=x.sum(-1,keepdim=True)/count
69
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
70
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
71
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
72
+ return z,valid,mu,scale
73
+
74
+ @staticmethod
75
+ def features(z,valid,periods,h):
76
+ b,c=z.shape;dev=z.device
77
+ def avg(k):
78
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
79
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
80
+ last=z.gather(1,last_idx[:,None])[:,0]
81
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
82
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
83
+ t=torch.arange(h,device=dev)[None,:]
84
+ for j in range(2):
85
+ p=periods[:,j:j+1].clamp(min=1)
86
+ anchor=c-p+t%p
87
+ vals=[];masks=[]
88
+ for cycle in range(4):
89
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
90
+ ok=(idx>=0)&valid.gather(1,safe)
91
+ vals.append(z.gather(1,safe));masks.append(ok)
92
+ vals=torch.stack(vals);masks=torch.stack(masks)
93
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
94
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
95
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
96
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
97
+ k=min(128,max(4,c//4));recent=avg(k)
98
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
99
+ slope=((recent-older)/k).clamp(-.03,.03)
100
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
101
+ bases.append(trend)
102
+ return torch.stack(bases,-1)
103
+
104
+ def forward(self,ctx,periods,horizon):
105
+ p=self.patch;h=math.ceil(horizon/p)*p
106
+ ctx=ctx[:,-self.max_context:]
107
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
108
+ z,valid,mu,scale=self.standardize(ctx)
109
+ b,c=z.shape;nt=c//p
110
+ base=self.features(z,valid,periods,h)
111
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
112
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
113
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,torch.full((b,1),math.log1p(max(32,h))/8,device=z.device)),-1)
114
+ emb=self.metadata(meta)[:,None]
115
+ x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
116
+ for layer in self.encoder:x=layer(x,pmask)
117
+ q=self.query(base.reshape(b,h//p,p*9))+positional((torch.arange(h//p,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
118
+ if self.recency is not None:
119
+ pos=torch.arange(c,device=z.device)[None,:];extras=[]
120
+ for j in range(2):
121
+ period=periods[:,j:j+1]
122
+ recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period)
123
+ nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1)
124
+ mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool
125
+ sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt()
126
+ sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4)
127
+ active=(period>=2)&(npool>=3*period)
128
+ shift=torch.where(active,mr-mp,0.).expand(-1,h)
129
+ amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.)
130
+ extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude])
131
+ extra=torch.stack(extras,-1)
132
+ q=q+self.recency(extra.reshape(b,h//p,p*4))
133
+ for layer in self.decoder:q=layer(q,pmask,x)
134
+ out=self.head(self.norm(q)).view(b,h,18).float()
135
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
136
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
137
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
138
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
139
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
140
+ return quant,mu,scale
141
+
142
+ @torch.no_grad()
143
+ def predict(self,ctx,periods,horizon):
144
+ q,mu,scale=self(ctx,periods,horizon)
145
+ q=q*scale[:,:,None]+mu[:,:,None]
146
+ # Positivity is a fixed context rule, as in released foundation forecasters.
147
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
148
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
149
+ return q.transpose(1,2)
150
+
151
+ def loss_fn(model,ctx,target,periods):
152
+ q,mu,scale=model(ctx,periods,target.shape[-1])
153
+ valid=torch.isfinite(target)
154
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
155
+ err=y[:,:,None]-q
156
+ levels=torch.arange(1,10,device=q.device)/10
157
+ # The evaluation gives equal importance to median MASE and average quantile loss.
158
+ pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs()
159
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
160
+ # A context-only seasonal scale makes highly predictable windows count more.
161
+ # It is used solely in the training loss; no inference adaptation is introduced.
162
+ with torch.no_grad():
163
+ z,seen,_,_=model.standardize(ctx)
164
+ n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:]
165
+ lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0)
166
+ pairs=(idx>=0)&seen&seen.gather(1,safe)
167
+ count=pairs.sum(-1)
168
+ errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1)
169
+ errscale=torch.where(count>=8,errscale,1.)
170
+ weight=(.25+errscale).reciprocal().clamp(.25,4.)
171
+ return (per*weight).sum()/weight.sum()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/large_corpus/train.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json,math,time,os,sys,shutil,hashlib
2
+ from pathlib import Path
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import numpy as np
5
+ import torch
6
+ from model import DirectForecaster,loss_fn
7
+ from data import Sampler
8
+
9
+ def save(model,path,step,args,opt=None):
10
+ ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)}
11
+ if opt is not None:ck['opt']=opt.state_dict()
12
+ tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path)
13
+
14
+ def main():
15
+ ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True)
16
+ ap.add_argument('--source-weights-from',required=True);ap.add_argument('--steps',type=int,default=12000);ap.add_argument('--batch',type=int,default=128);ap.add_argument('--context',type=int,default=4096)
17
+ ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3)
18
+ ap.add_argument('--patch',type=int,default=32)
19
+ ap.add_argument('--lr',type=float,default=3e-4);ap.add_argument('--seed',type=int,default=17);ap.add_argument('--save-every',type=int,default=1000)
20
+ ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args()
21
+ torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed)
22
+ torch.backends.cuda.matmul.allow_tf32=True
23
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
24
+ model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda()
25
+ opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True)
26
+ # Exponential averaging is a training-only stabilization; inference remains fixed.
27
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()}
28
+ startstep=0
29
+ if a.resume:
30
+ ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step']
31
+ if 'opt' in ck:opt.load_state_dict(ck['opt'])
32
+ if a.initialize_from:
33
+ ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False)
34
+ missing,unexpected=model.load_state_dict(ck['model'],strict=False)
35
+ assert not unexpected and all(k.startswith('recency.') for k in missing)
36
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()}
37
+ sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from)
38
+ params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2))
39
+ print('parameters',params,flush=True)
40
+ rng=np.random.default_rng(a.seed+startstep)
41
+ def nextbatch():
42
+ c=int(rng.choice([512,1024,2048,a.context],p=[.1,.15,.35,.4]));h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5]))
43
+ return sampler.sample(a.batch,c,h)
44
+ pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[]
45
+ for step in range(startstep+1,a.steps+1):
46
+ arrays=future.result();future=pool.submit(nextbatch)
47
+ x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays]
48
+ lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps))))
49
+ for g in opt.param_groups:g['lr']=lr
50
+ opt.zero_grad(set_to_none=True)
51
+ with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p)
52
+ loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
53
+ if torch.isfinite(gn):
54
+ opt.step()
55
+ with torch.no_grad():
56
+ decay=min(.999,1-1/(step+1))
57
+ for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay)
58
+ losses.append(float(loss.detach()))
59
+ if step%50==0:
60
+ rec={'step':step,'loss':float(np.mean(losses)),'seconds':round(time.time()-t0,1),'lr':lr,'grad_norm':float(gn),'context':x.shape[-1],'horizon':y.shape[-1]}
61
+ print(json.dumps(rec),flush=True)
62
+ with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n')
63
+ losses=[]
64
+ stop=a.stop_file and Path(a.stop_file).exists()
65
+ if step%a.save_every==0 or step==a.steps or stop:
66
+ save(model,out/f'step{step:06d}.pt',step,a)
67
+ save(model,out/'last.pt',step,a,opt)
68
+ ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True}
69
+ path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path)
70
+ if stop:break
71
+ pool.shutdown()
72
+
73
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S027/provenance/partial_targets/model.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None,future_mask=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True,partial_target_lengths=True):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon,recency_features=recency_features,partial_target_lengths=partial_target_lengths)
51
+ self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None
52
+ if self.recency is not None:nn.init.zeros_(self.recency.weight)
53
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
54
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
55
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
56
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
57
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
58
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
59
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
60
+ with torch.no_grad():
61
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
62
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
63
+
64
+ @staticmethod
65
+ def standardize(ctx):
66
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
67
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
68
+ mu=x.sum(-1,keepdim=True)/count
69
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
70
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
71
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
72
+ return z,valid,mu,scale
73
+
74
+ @staticmethod
75
+ def features(z,valid,periods,h):
76
+ b,c=z.shape;dev=z.device
77
+ def avg(k):
78
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
79
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
80
+ last=z.gather(1,last_idx[:,None])[:,0]
81
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
82
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
83
+ t=torch.arange(h,device=dev)[None,:]
84
+ for j in range(2):
85
+ p=periods[:,j:j+1].clamp(min=1)
86
+ anchor=c-p+t%p
87
+ vals=[];masks=[]
88
+ for cycle in range(4):
89
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
90
+ ok=(idx>=0)&valid.gather(1,safe)
91
+ vals.append(z.gather(1,safe));masks.append(ok)
92
+ vals=torch.stack(vals);masks=torch.stack(masks)
93
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
94
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
95
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
96
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
97
+ k=min(128,max(4,c//4));recent=avg(k)
98
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
99
+ slope=((recent-older)/k).clamp(-.03,.03)
100
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
101
+ bases.append(trend)
102
+ return torch.stack(bases,-1)
103
+
104
+ def forward(self,ctx,periods,horizon,forecast_lengths=None):
105
+ p=self.patch;h=math.ceil(horizon/p)*p
106
+ ctx=ctx[:,-self.max_context:]
107
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
108
+ z,valid,mu,scale=self.standardize(ctx)
109
+ b,c=z.shape;nt=c//p
110
+ base=self.features(z,valid,periods,h)
111
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
112
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
113
+ future_mask=None
114
+ horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device)
115
+ if forecast_lengths is not None:
116
+ patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p)
117
+ future_mask=torch.arange(h//p,device=z.device)[None,:]<patch_count[:,None]
118
+ horizon_meta=(patch_count*p).clamp(min=32).float().log1p()[:,None]/8
119
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,horizon_meta),-1)
120
+ emb=self.metadata(meta)[:,None]
121
+ x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
122
+ for layer in self.encoder:x=layer(x,pmask)
123
+ q=self.query(base.reshape(b,h//p,p*9))+positional((torch.arange(h//p,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
124
+ if self.recency is not None:
125
+ pos=torch.arange(c,device=z.device)[None,:];extras=[]
126
+ for j in range(2):
127
+ period=periods[:,j:j+1]
128
+ recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period)
129
+ nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1)
130
+ mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool
131
+ sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt()
132
+ sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4)
133
+ active=(period>=2)&(npool>=3*period)
134
+ shift=torch.where(active,mr-mp,0.).expand(-1,h)
135
+ amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.)
136
+ extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude])
137
+ extra=torch.stack(extras,-1)
138
+ q=q+self.recency(extra.reshape(b,h//p,p*4))
139
+ for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask)
140
+ out=self.head(self.norm(q)).view(b,h,18).float()
141
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
142
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
143
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
144
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
145
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
146
+ return quant,mu,scale
147
+
148
+ @torch.no_grad()
149
+ def predict(self,ctx,periods,horizon):
150
+ q,mu,scale=self(ctx,periods,horizon)
151
+ q=q*scale[:,:,None]+mu[:,:,None]
152
+ # Positivity is a fixed context rule, as in released foundation forecasters.
153
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
154
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
155
+ return q.transpose(1,2)
156
+
157
+ def loss_fn(model,ctx,target,periods):
158
+ seen=torch.isfinite(target)
159
+ pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1
160
+ lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1)
161
+ q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths)
162
+ valid=torch.isfinite(target)
163
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
164
+ err=y[:,:,None]-q
165
+ levels=torch.arange(1,10,device=q.device)/10
166
+ # The evaluation gives equal importance to median MASE and average quantile loss.
167
+ pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs()
168
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
169
+ # A context-only seasonal scale makes highly predictable windows count more.
170
+ # It is used solely in the training loss; no inference adaptation is introduced.
171
+ with torch.no_grad():
172
+ z,seen,_,_=model.standardize(ctx)
173
+ n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:]
174
+ lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0)
175
+ pairs=(idx>=0)&seen&seen.gather(1,safe)
176
+ count=pairs.sum(-1)
177
+ errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1)
178
+ errscale=torch.where(count>=8,errscale,1.)
179
+ weight=(.25+errscale).reciprocal().clamp(.25,4.)
180
+ return (per*weight).sum()/weight.sum()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S028/provenance/member0/training/large_sign/model.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon)
51
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
52
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
53
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
54
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
55
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
56
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
57
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
58
+ with torch.no_grad():
59
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
60
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
61
+
62
+ @staticmethod
63
+ def standardize(ctx):
64
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
65
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
66
+ mu=x.sum(-1,keepdim=True)/count
67
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
68
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
69
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
70
+ return z,valid,mu,scale
71
+
72
+ @staticmethod
73
+ def features(z,valid,periods,h):
74
+ b,c=z.shape;dev=z.device
75
+ def avg(k):
76
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
77
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
78
+ last=z.gather(1,last_idx[:,None])[:,0]
79
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
80
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
81
+ t=torch.arange(h,device=dev)[None,:]
82
+ for j in range(2):
83
+ p=periods[:,j:j+1].clamp(min=1)
84
+ anchor=c-p+t%p
85
+ vals=[];masks=[]
86
+ for cycle in range(4):
87
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
88
+ ok=(idx>=0)&valid.gather(1,safe)
89
+ vals.append(z.gather(1,safe));masks.append(ok)
90
+ vals=torch.stack(vals);masks=torch.stack(masks)
91
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
92
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
93
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
94
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
95
+ k=min(128,max(4,c//4));recent=avg(k)
96
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
97
+ slope=((recent-older)/k).clamp(-.03,.03)
98
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
99
+ bases.append(trend)
100
+ return torch.stack(bases,-1)
101
+
102
+ def forward(self,ctx,periods,horizon):
103
+ p=self.patch;h=math.ceil(horizon/p)*p
104
+ ctx=ctx[:,-self.max_context:]
105
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
106
+ z,valid,mu,scale=self.standardize(ctx)
107
+ b,c=z.shape;nt=c//p
108
+ base=self.features(z,valid,periods,h)
109
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
110
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
111
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,torch.full((b,1),math.log1p(h)/8,device=z.device)),-1)
112
+ emb=self.metadata(meta)[:,None]
113
+ x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb
114
+ for layer in self.encoder:x=layer(x,pmask)
115
+ q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb
116
+ for layer in self.decoder:q=layer(q,pmask,x)
117
+ out=self.head(self.norm(q)).view(b,h,18).float()
118
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
119
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
120
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
121
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
122
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
123
+ return quant,mu,scale
124
+
125
+ @torch.no_grad()
126
+ def predict(self,ctx,periods,horizon):
127
+ q,mu,scale=self(ctx,periods,horizon)
128
+ q=q*scale[:,:,None]+mu[:,:,None]
129
+ # Positivity is a fixed context rule, as in released foundation forecasters.
130
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
131
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
132
+ return q.transpose(1,2)
133
+
134
+ def loss_fn(model,ctx,target,periods):
135
+ q,mu,scale=model(ctx,periods,target.shape[-1])
136
+ valid=torch.isfinite(target)
137
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
138
+ err=y[:,:,None]-q
139
+ levels=torch.arange(1,10,device=q.device)/10
140
+ # The evaluation gives equal importance to median MASE and average quantile loss.
141
+ pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs()
142
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
143
+ # A context-only seasonal scale makes highly predictable windows count more.
144
+ # It is used solely in the training loss; no inference adaptation is introduced.
145
+ with torch.no_grad():
146
+ z,seen,_,_=model.standardize(ctx)
147
+ n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:]
148
+ lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0)
149
+ pairs=(idx>=0)&seen&seen.gather(1,safe)
150
+ count=pairs.sum(-1)
151
+ errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1)
152
+ errscale=torch.where(count>=8,errscale,1.)
153
+ weight=(.25+errscale).reciprocal().clamp(.25,4.)
154
+ return (per*weight).sum()/weight.sum()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S028/provenance/member1/training/patch16/pack.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data."""
2
+ import json,time,hashlib,concurrent.futures,argparse
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pyarrow as pa
6
+
7
+ ROOT=Path('/workspace/data/gifteval_pretrain')
8
+
9
+ def pack_dir(job):
10
+ name,out,cap=job
11
+ rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little'))
12
+ files=sorted((ROOT/name).glob('data-*.arrow'))
13
+ rng.shuffle(files)
14
+ # Spread large-source samples across eight shards rather than taking one contiguous slice.
15
+ files=files[:min(8,len(files))]
16
+ meta=[]; total=0; offsets=[0]; t0=time.time()
17
+ with open(out/f'{name}.bin','wb') as dest:
18
+ for file in files:
19
+ quota=max(1,cap//len(files)); kept=0
20
+ with pa.memory_map(str(file),'r') as f:
21
+ table=pa.ipc.open_stream(f).read_all()
22
+ freq=table.column('freq')[0].as_py() if table.num_rows else ''
23
+ for target in table.column('target').chunks:
24
+ if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type):
25
+ target=target.values
26
+ off=target.offsets.to_numpy()
27
+ flat=target.values.to_numpy(zero_copy_only=False)
28
+ ids=np.arange(len(target));rng.shuffle(ids)
29
+ for i in ids:
30
+ x=flat[off[i]:off[i+1]]
31
+ if len(x)<16 or not np.isfinite(x).any():continue
32
+ # Cap very long series at a random contiguous year-sized segment.
33
+ if len(x)>131072:
34
+ start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072]
35
+ x=np.asarray(x,dtype=np.float32)
36
+ x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total)
37
+ meta.append({'dataset':name,'freq':freq,'length':len(x)})
38
+ if kept>=quota:break
39
+ if kept>=quota:break
40
+ np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64))
41
+ (out/f'{name}.json').write_text(json.dumps(meta))
42
+ return name,total,len(meta),round(time.time()-t0,1)
43
+
44
+ def main():
45
+ ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--cap',type=int,default=16000000);ap.add_argument('--workers',type=int,default=6);a=ap.parse_args()
46
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
47
+ names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.'))
48
+ lock=json.loads(Path('/workspace/data/sources.lock.json').read_text())
49
+ allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories']
50
+ assert set(names)<=set(allowed)
51
+ with concurrent.futures.ThreadPoolExecutor(a.workers) as pool:
52
+ for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True)
53
+ counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names}
54
+ (out/'meta.json').write_text(json.dumps({'dirs':[n for n in names if counts[n]],'counts':counts,'per_directory_point_cap':a.cap,'seed':'sha256(directory) little-endian first 4 bytes','min_length':16},indent=2))
55
+
56
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/direct_large/pack.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data."""
2
+ import json,time,hashlib,concurrent.futures,argparse
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pyarrow as pa
6
+
7
+ ROOT=Path('/workspace/data/gifteval_pretrain')
8
+
9
+ def pack_dir(job):
10
+ name,out,cap=job
11
+ rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little'))
12
+ files=sorted((ROOT/name).glob('data-*.arrow'))
13
+ rng.shuffle(files)
14
+ # Spread large-source samples across eight shards rather than taking one contiguous slice.
15
+ files=files[:min(8,len(files))]
16
+ meta=[]; total=0; offsets=[0]; t0=time.time()
17
+ with open(out/f'{name}.bin','wb') as dest:
18
+ for file in files:
19
+ quota=max(1,cap//len(files)); kept=0
20
+ with pa.memory_map(str(file),'r') as f:
21
+ table=pa.ipc.open_stream(f).read_all()
22
+ freq=table.column('freq')[0].as_py() if table.num_rows else ''
23
+ for target in table.column('target').chunks:
24
+ if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type):
25
+ target=target.values
26
+ off=target.offsets.to_numpy()
27
+ flat=target.values.to_numpy(zero_copy_only=False)
28
+ ids=np.arange(len(target));rng.shuffle(ids)
29
+ for i in ids:
30
+ x=flat[off[i]:off[i+1]]
31
+ if len(x)<16 or not np.isfinite(x).any():continue
32
+ # Cap very long series at a random contiguous year-sized segment.
33
+ if len(x)>131072:
34
+ start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072]
35
+ x=np.asarray(x,dtype=np.float32)
36
+ x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total)
37
+ meta.append({'dataset':name,'freq':freq,'length':len(x)})
38
+ if kept>=quota:break
39
+ if kept>=quota:break
40
+ np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64))
41
+ (out/f'{name}.json').write_text(json.dumps(meta))
42
+ return name,total,len(meta),round(time.time()-t0,1)
43
+
44
+ def main():
45
+ ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--cap',type=int,default=16000000);ap.add_argument('--workers',type=int,default=6);a=ap.parse_args()
46
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
47
+ names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.'))
48
+ lock=json.loads(Path('/workspace/data/sources.lock.json').read_text())
49
+ allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories']
50
+ assert set(names)<=set(allowed)
51
+ with concurrent.futures.ThreadPoolExecutor(a.workers) as pool:
52
+ for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True)
53
+ counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names}
54
+ (out/'meta.json').write_text(json.dumps({'dirs':[n for n in names if counts[n]],'counts':counts,'per_directory_point_cap':a.cap,'seed':'sha256(directory) little-endian first 4 bytes','min_length':16},indent=2))
55
+
56
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/large_sign/pack.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data."""
2
+ import json,time,hashlib,concurrent.futures,argparse
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pyarrow as pa
6
+
7
+ ROOT=Path('/workspace/data/gifteval_pretrain')
8
+
9
+ def pack_dir(job):
10
+ name,out,cap=job
11
+ rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little'))
12
+ files=sorted((ROOT/name).glob('data-*.arrow'))
13
+ rng.shuffle(files)
14
+ # Spread large-source samples across eight shards rather than taking one contiguous slice.
15
+ files=files[:min(8,len(files))]
16
+ meta=[]; total=0; offsets=[0]; t0=time.time()
17
+ with open(out/f'{name}.bin','wb') as dest:
18
+ for file in files:
19
+ quota=max(1,cap//len(files)); kept=0
20
+ with pa.memory_map(str(file),'r') as f:
21
+ table=pa.ipc.open_stream(f).read_all()
22
+ freq=table.column('freq')[0].as_py() if table.num_rows else ''
23
+ for target in table.column('target').chunks:
24
+ if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type):
25
+ target=target.values
26
+ off=target.offsets.to_numpy()
27
+ flat=target.values.to_numpy(zero_copy_only=False)
28
+ ids=np.arange(len(target));rng.shuffle(ids)
29
+ for i in ids:
30
+ x=flat[off[i]:off[i+1]]
31
+ if len(x)<16 or not np.isfinite(x).any():continue
32
+ # Cap very long series at a random contiguous year-sized segment.
33
+ if len(x)>131072:
34
+ start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072]
35
+ x=np.asarray(x,dtype=np.float32)
36
+ x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total)
37
+ meta.append({'dataset':name,'freq':freq,'length':len(x)})
38
+ if kept>=quota:break
39
+ if kept>=quota:break
40
+ np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64))
41
+ (out/f'{name}.json').write_text(json.dumps(meta))
42
+ return name,total,len(meta),round(time.time()-t0,1)
43
+
44
+ def main():
45
+ ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--cap',type=int,default=16000000);ap.add_argument('--workers',type=int,default=6);a=ap.parse_args()
46
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
47
+ names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.'))
48
+ lock=json.loads(Path('/workspace/data/sources.lock.json').read_text())
49
+ allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories']
50
+ assert set(names)<=set(allowed)
51
+ with concurrent.futures.ThreadPoolExecutor(a.workers) as pool:
52
+ for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True)
53
+ counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names}
54
+ (out/'meta.json').write_text(json.dumps({'dirs':[n for n in names if counts[n]],'counts':counts,'per_directory_point_cap':a.cap,'seed':'sha256(directory) little-endian first 4 bytes','min_length':16},indent=2))
55
+
56
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/long_memory_synth/model.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None,future_mask=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True,partial_target_lengths=True):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon,recency_features=recency_features,partial_target_lengths=partial_target_lengths)
51
+ self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None
52
+ if self.recency is not None:nn.init.zeros_(self.recency.weight)
53
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
54
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
55
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
56
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
57
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
58
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
59
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
60
+ with torch.no_grad():
61
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
62
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
63
+
64
+ @staticmethod
65
+ def standardize(ctx):
66
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
67
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
68
+ mu=x.sum(-1,keepdim=True)/count
69
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
70
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
71
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
72
+ return z,valid,mu,scale
73
+
74
+ @staticmethod
75
+ def features(z,valid,periods,h):
76
+ b,c=z.shape;dev=z.device
77
+ def avg(k):
78
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
79
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
80
+ last=z.gather(1,last_idx[:,None])[:,0]
81
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
82
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
83
+ t=torch.arange(h,device=dev)[None,:]
84
+ for j in range(2):
85
+ p=periods[:,j:j+1].clamp(min=1)
86
+ anchor=c-p+t%p
87
+ vals=[];masks=[]
88
+ for cycle in range(4):
89
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
90
+ ok=(idx>=0)&valid.gather(1,safe)
91
+ vals.append(z.gather(1,safe));masks.append(ok)
92
+ vals=torch.stack(vals);masks=torch.stack(masks)
93
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
94
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
95
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
96
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
97
+ k=min(128,max(4,c//4));recent=avg(k)
98
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
99
+ slope=((recent-older)/k).clamp(-.03,.03)
100
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
101
+ bases.append(trend)
102
+ return torch.stack(bases,-1)
103
+
104
+ def forward(self,ctx,periods,horizon,forecast_lengths=None):
105
+ p=self.patch;h=math.ceil(horizon/p)*p
106
+ ctx=ctx[:,-self.max_context:]
107
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
108
+ z,valid,mu,scale=self.standardize(ctx)
109
+ b,c=z.shape;nt=c//p
110
+ base=self.features(z,valid,periods,h)
111
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
112
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
113
+ future_mask=None
114
+ horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device)
115
+ if forecast_lengths is not None:
116
+ patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p)
117
+ future_mask=torch.arange(h//p,device=z.device)[None,:]<patch_count[:,None]
118
+ horizon_meta=(patch_count*p).clamp(min=32).float().log1p()[:,None]/8
119
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,horizon_meta),-1)
120
+ emb=self.metadata(meta)[:,None]
121
+ x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
122
+ for layer in self.encoder:x=layer(x,pmask)
123
+ q=self.query(base.reshape(b,h//p,p*9))+positional((torch.arange(h//p,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
124
+ if self.recency is not None:
125
+ pos=torch.arange(c,device=z.device)[None,:];extras=[]
126
+ for j in range(2):
127
+ period=periods[:,j:j+1]
128
+ recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period)
129
+ nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1)
130
+ mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool
131
+ sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt()
132
+ sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4)
133
+ active=(period>=2)&(npool>=3*period)
134
+ shift=torch.where(active,mr-mp,0.).expand(-1,h)
135
+ amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.)
136
+ extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude])
137
+ extra=torch.stack(extras,-1)
138
+ q=q+self.recency(extra.reshape(b,h//p,p*4))
139
+ for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask)
140
+ out=self.head(self.norm(q)).view(b,h,18).float()
141
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
142
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
143
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
144
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
145
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
146
+ return quant,mu,scale
147
+
148
+ @torch.no_grad()
149
+ def predict(self,ctx,periods,horizon):
150
+ q,mu,scale=self(ctx,periods,horizon)
151
+ q=q*scale[:,:,None]+mu[:,:,None]
152
+ # Positivity is a fixed context rule, as in released foundation forecasters.
153
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
154
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
155
+ return q.transpose(1,2)
156
+
157
+ def loss_fn(model,ctx,target,periods):
158
+ seen=torch.isfinite(target)
159
+ pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1
160
+ lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1)
161
+ q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths)
162
+ valid=torch.isfinite(target)
163
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
164
+ err=y[:,:,None]-q
165
+ levels=torch.arange(1,10,device=q.device)/10
166
+ # The evaluation gives equal importance to median MASE and average quantile loss.
167
+ pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs()
168
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
169
+ # A context-only seasonal scale makes highly predictable windows count more.
170
+ # It is used solely in the training loss; no inference adaptation is introduced.
171
+ with torch.no_grad():
172
+ z,seen,_,_=model.standardize(ctx)
173
+ n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:]
174
+ lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0)
175
+ pairs=(idx>=0)&seen&seen.gather(1,safe)
176
+ count=pairs.sum(-1)
177
+ errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1)
178
+ errscale=torch.where(count>=8,errscale,1.)
179
+ weight=(.25+errscale).reciprocal().clamp(.25,4.)
180
+ return (per*weight).sum()/weight.sum()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/partial_targets/train.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json,math,time,os,sys,shutil,hashlib
2
+ from pathlib import Path
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import numpy as np
5
+ import torch
6
+ from model import DirectForecaster,loss_fn
7
+ from data import Sampler
8
+
9
+ def save(model,path,step,args,opt=None):
10
+ ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)}
11
+ if opt is not None:ck['opt']=opt.state_dict()
12
+ tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path)
13
+
14
+ def main():
15
+ ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True)
16
+ ap.add_argument('--source-weights-from',required=True);ap.add_argument('--steps',type=int,default=12000);ap.add_argument('--batch',type=int,default=128);ap.add_argument('--context',type=int,default=4096)
17
+ ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3)
18
+ ap.add_argument('--patch',type=int,default=32)
19
+ ap.add_argument('--lr',type=float,default=3e-4);ap.add_argument('--seed',type=int,default=17);ap.add_argument('--save-every',type=int,default=1000)
20
+ ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args()
21
+ torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed)
22
+ torch.backends.cuda.matmul.allow_tf32=True
23
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
24
+ model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda()
25
+ opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True)
26
+ # Exponential averaging is a training-only stabilization; inference remains fixed.
27
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()}
28
+ startstep=0
29
+ if a.resume:
30
+ ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step']
31
+ if 'opt' in ck:opt.load_state_dict(ck['opt'])
32
+ if a.initialize_from:
33
+ ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False)
34
+ missing,unexpected=model.load_state_dict(ck['model'],strict=False)
35
+ assert not unexpected and all(k.startswith('recency.') for k in missing)
36
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()}
37
+ sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from)
38
+ params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2))
39
+ print('parameters',params,flush=True)
40
+ rng=np.random.default_rng(a.seed+startstep)
41
+ def nextbatch():
42
+ c=int(rng.choice([512,1024,2048,a.context],p=[.1,.15,.35,.4]));h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5]))
43
+ return sampler.sample(a.batch,c,h)
44
+ pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[]
45
+ for step in range(startstep+1,a.steps+1):
46
+ arrays=future.result();future=pool.submit(nextbatch)
47
+ x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays]
48
+ lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps))))
49
+ for g in opt.param_groups:g['lr']=lr
50
+ opt.zero_grad(set_to_none=True)
51
+ with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p)
52
+ loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
53
+ if torch.isfinite(gn):
54
+ opt.step()
55
+ with torch.no_grad():
56
+ decay=min(.999,1-1/(step+1))
57
+ for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay)
58
+ losses.append(float(loss.detach()))
59
+ if step%50==0:
60
+ rec={'step':step,'loss':float(np.mean(losses)),'seconds':round(time.time()-t0,1),'lr':lr,'grad_norm':float(gn),'context':x.shape[-1],'horizon':y.shape[-1]}
61
+ print(json.dumps(rec),flush=True)
62
+ with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n')
63
+ losses=[]
64
+ stop=a.stop_file and Path(a.stop_file).exists()
65
+ if step%a.save_every==0 or step==a.steps or stop:
66
+ save(model,out/f'step{step:06d}.pt',step,a)
67
+ save(model,out/'last.pt',step,a,opt)
68
+ ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True}
69
+ path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path)
70
+ if stop:break
71
+ pool.shutdown()
72
+
73
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S040/provenance/patch16/data.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class Sampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ w=min(len(values),20_000_000)**.25
19
+ if name.startswith(('era5_','cmip6_')):w*=.35
20
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
21
+ weights.append(w)
22
+ self.probs=np.array(weights)/sum(weights)
23
+
24
+ def synthetic(self,n,p):
25
+ r=self.rng;t=np.arange(n,dtype=np.float32)
26
+ # New generator: damped trends, random Fourier seasonality, AR noise,
27
+ # intermittent demand, changepoints, and randomly scaled observation noise.
28
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
29
+ x=np.full(n,level,np.float32)
30
+ if r.random()<.8:
31
+ for period in p:
32
+ if period<2:continue
33
+ for k in range(1,int(r.integers(2,5))):
34
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
35
+ if r.random()<.6:
36
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
37
+ x+=slope*tau*(1-np.exp(-t/tau))
38
+ noise=r.normal(0,sigma,n).astype(np.float32)
39
+ if r.random()<.5:
40
+ from scipy.signal import lfilter
41
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
42
+ x+=noise
43
+ if r.random()<.2:
44
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
45
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
46
+ if r.random()<.1:x=np.maximum(0,x)
47
+ return x.astype(np.float32)
48
+
49
+ def sample(self,batch,context=2048,horizon=1024):
50
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
51
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
52
+ for b,d in enumerate(ds):
53
+ if r.random()<self.synthetic_fraction:
54
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
55
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
56
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
57
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
58
+ # Random cutoffs retain short sources, with unavailable future steps masked.
59
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
60
+ nc=min(context,cut)
61
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
62
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
63
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
64
+ if r.random()<.12 and l>=4*(context+horizon):
65
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
66
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
67
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
68
+ else:periods[b]=self.periods[d][i]
69
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
70
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
71
+ sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1))
72
+ return ctx*sign,tgt*sign,periods
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/README.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Direct seasonal foundation forecaster
2
+
3
+ Run `bash infer.sh INPUT_DIR OUTPUT_DIR`. All runtime assets are included; package versions are pinned in requirements.txt. This 36,665,488-parameter model was trained from random initialization here. The complete checkpoint lineage and all training sources are in model_manifest.json. The trainer and generator code are archived in provenance/.
4
+
5
+ A patch encoder/decoder predicts nine monotone quantiles directly. Inference averages the original and sign-reversed forecasts, applies a fixed seasonal-confidence rule, and adds a decaying continuity correction on smooth histories. Every operation uses the supplied instance alone, with globally fixed parameters and no inference-time fitting. Per-instance normalization needs no external statistics.
6
+
7
+ EXPERIMENTS.md records hypotheses, negative results, compute, group metrics and checkpoint hashes. validation_report.json contains the most recent package evaluation. Validation and earlier-window diagnostic scores are not the held-out reward scale.
8
+
9
+ The seasonal template averages four cycles, then aligns its mean and noise-corrected amplitude to the latest cycle. The amplitude ratio is clipped to [0.5,2] and requires at least 75% observed points in the latest cycle. These are fixed formulas using only the supplied context.
10
+
11
+ Future queries receive additional learned projections of recent seasonal level and amplitude changes. These features are computed from the instance context and were trained jointly with the backbone on the declared pretraining corpus.
12
+
13
+ Future queries receive a 3,072-parameter projection of six fixed context statistics describing local and seasonal differences. These features were introduced in a frozen-backbone stage using the loss of forecasts averaged across both sign orientations.
14
+
15
+ The final continuation trained all model parameters. Its sign-loss mode is paired. Training settings and the complete earlier frozen-stage lineage are recorded in the manifest and provenance.
16
+
17
+ During training, rows with shorter available futures used their own horizon metadata and masked unused future tokens. Inference uses the full requested horizon and the ordinary decoder, without additional inputs.
18
+
19
+ For nonnegative histories with at least four exact zeros and at least 10% zeros among observed points, nonnegative forecast quantiles below 0.4 context standard deviations are set to zero. This fixed monotone transformation represents the observed mass at zero without fitting parameters.
20
+
21
+ The original trend summary uses a fixed 128-point averaging width, matching the formula used at every pretraining context length and avoiding dependence on batch padding for short histories.
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/infer.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export OMP_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=4
4
+ exec python3 "$(dirname "$(readlink -f "$0")")/predict.py" "$1" "$2"
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/confidence_query/data.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class Sampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ w=min(len(values),20_000_000)**.25
19
+ if name.startswith(('era5_','cmip6_')):w*=.35
20
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
21
+ weights.append(w)
22
+ self.probs=np.array(weights)/sum(weights)
23
+
24
+ def synthetic(self,n,p):
25
+ r=self.rng;t=np.arange(n,dtype=np.float32)
26
+ # New generator: damped trends, random Fourier seasonality, AR noise,
27
+ # intermittent demand, changepoints, and randomly scaled observation noise.
28
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
29
+ x=np.full(n,level,np.float32)
30
+ if r.random()<.8:
31
+ for period in p:
32
+ if period<2:continue
33
+ for k in range(1,int(r.integers(2,5))):
34
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
35
+ if r.random()<.6:
36
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
37
+ x+=slope*tau*(1-np.exp(-t/tau))
38
+ noise=r.normal(0,sigma,n).astype(np.float32)
39
+ if r.random()<.5:
40
+ from scipy.signal import lfilter
41
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
42
+ x+=noise
43
+ if r.random()<.2:
44
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
45
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
46
+ if r.random()<.1:x=np.maximum(0,x)
47
+ return x.astype(np.float32)
48
+
49
+ def sample(self,batch,context=2048,horizon=1024):
50
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
51
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
52
+ for b,d in enumerate(ds):
53
+ if r.random()<self.synthetic_fraction:
54
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
55
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
56
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
57
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
58
+ # Random cutoffs retain short sources, with unavailable future steps masked.
59
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
60
+ nc=min(context,cut)
61
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
62
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
63
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
64
+ if r.random()<.12 and l>=4*(context+horizon):
65
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
66
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
67
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
68
+ else:periods[b]=self.periods[d][i]
69
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
70
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
71
+ sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1))
72
+ return ctx*sign,tgt*sign,periods
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/confidence_query/model.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True,confidence_features=True):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon,recency_features=recency_features,confidence_features=confidence_features)
51
+ self.confidence=nn.Linear(6,d,bias=False)
52
+ nn.init.zeros_(self.confidence.weight)
53
+ self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None
54
+ if self.recency is not None:nn.init.zeros_(self.recency.weight)
55
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
56
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
57
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
58
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
59
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
60
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
61
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
62
+ with torch.no_grad():
63
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
64
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
65
+
66
+ @staticmethod
67
+ def standardize(ctx):
68
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
69
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
70
+ mu=x.sum(-1,keepdim=True)/count
71
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
72
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
73
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
74
+ return z,valid,mu,scale
75
+
76
+ @staticmethod
77
+ def features(z,valid,periods,h):
78
+ b,c=z.shape;dev=z.device
79
+ def avg(k):
80
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
81
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
82
+ last=z.gather(1,last_idx[:,None])[:,0]
83
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
84
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
85
+ t=torch.arange(h,device=dev)[None,:]
86
+ for j in range(2):
87
+ p=periods[:,j:j+1].clamp(min=1)
88
+ anchor=c-p+t%p
89
+ vals=[];masks=[]
90
+ for cycle in range(4):
91
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
92
+ ok=(idx>=0)&valid.gather(1,safe)
93
+ vals.append(z.gather(1,safe));masks.append(ok)
94
+ vals=torch.stack(vals);masks=torch.stack(masks)
95
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
96
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
97
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
98
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
99
+ k=128;recent=avg(k) # Match the training width, independently of padding.
100
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
101
+ slope=((recent-older)/k).clamp(-.03,.03)
102
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
103
+ bases.append(trend)
104
+ return torch.stack(bases,-1)
105
+
106
+ def forward(self,ctx,periods,horizon):
107
+ p=self.patch;h=math.ceil(horizon/p)*p
108
+ ctx=ctx[:,-self.max_context:]
109
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
110
+ z,valid,mu,scale=self.standardize(ctx)
111
+ b,c=z.shape;nt=c//p
112
+ base=self.features(z,valid,periods,h)
113
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
114
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
115
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,torch.full((b,1),math.log1p(max(32,h))/8,device=z.device)),-1)
116
+ emb=self.metadata(meta)[:,None]
117
+ x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
118
+ for layer in self.encoder:x=layer(x,pmask)
119
+ q=self.query(base.reshape(b,h//p,p*9))+positional((torch.arange(h//p,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
120
+ if self.recency is not None:
121
+ pos=torch.arange(c,device=z.device)[None,:];extras=[]
122
+ for j in range(2):
123
+ period=periods[:,j:j+1]
124
+ recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period)
125
+ nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1)
126
+ mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool
127
+ sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt()
128
+ sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4)
129
+ active=(period>=2)&(npool>=3*period)
130
+ shift=torch.where(active,mr-mp,0.).expand(-1,h)
131
+ amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.)
132
+ extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude])
133
+ extra=torch.stack(extras,-1)
134
+ q=q+self.recency(extra.reshape(b,h//p,p*4))
135
+ # Fixed normalized difference statistics expose local and seasonal repeatability.
136
+ pos=torch.arange(c,device=z.device)[None,:];stats=[]
137
+ for j in range(3):
138
+ lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j]
139
+ window=torch.full_like(lag,512) if j==0 else 8*lag
140
+ idx=pos-lag;safe=idx.clamp(min=0,max=c-1)
141
+ pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe)
142
+ count=pairs.sum(-1);difference=z-z.gather(1,safe)
143
+ absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1)
144
+ rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt()
145
+ absolute=torch.where(count>=8,absolute,1.)
146
+ rms=torch.where(count>=8,rms,math.sqrt(2.))
147
+ stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()])
148
+ q=q+self.confidence(torch.stack(stats,-1))[:,None]
149
+ for layer in self.decoder:q=layer(q,pmask,x)
150
+ out=self.head(self.norm(q)).view(b,h,18).float()
151
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
152
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
153
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
154
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
155
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
156
+ return quant,mu,scale
157
+
158
+ @torch.no_grad()
159
+ def predict(self,ctx,periods,horizon):
160
+ q,mu,scale=self(ctx,periods,horizon)
161
+ q=q*scale[:,:,None]+mu[:,:,None]
162
+ # Positivity is a fixed context rule, as in released foundation forecasters.
163
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
164
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
165
+ return q.transpose(1,2)
166
+
167
+ def loss_fn(model,ctx,target,periods):
168
+ n=ctx.shape[0]
169
+ q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1])
170
+ q=(q[:n]-q[n:].flip(-1))*.5
171
+ mu=mu[:n];scale=scale[:n]
172
+ valid=torch.isfinite(target)
173
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
174
+ err=y[:,:,None]-q
175
+ levels=torch.arange(1,10,device=q.device)/10
176
+ # The evaluation gives equal importance to median MASE and average quantile loss.
177
+ pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs()
178
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
179
+ # A context-only seasonal scale makes highly predictable windows count more.
180
+ # It is used solely in the training loss; no inference adaptation is introduced.
181
+ with torch.no_grad():
182
+ z,seen,_,_=model.standardize(ctx)
183
+ n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:]
184
+ lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0)
185
+ pairs=(idx>=0)&seen&seen.gather(1,safe)
186
+ count=pairs.sum(-1)
187
+ errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1)
188
+ errscale=torch.where(count>=8,errscale,1.)
189
+ weight=(.25+errscale).reciprocal().clamp(.25,4.)
190
+ return (per*weight).sum()/weight.sum()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/confidence_query/train.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train only confidence-query features on a frozen model, using paired-sign forecast loss."""
2
+ import argparse,json,math,time,os
3
+ from pathlib import Path
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ import numpy as np
6
+ import torch
7
+ from model import DirectForecaster,loss_fn
8
+ from data import Sampler
9
+
10
+ ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True)
11
+ ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000)
12
+ ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4)
13
+ ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args()
14
+ torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True
15
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
16
+ ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False)
17
+ config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda()
18
+ missing,unexpected=model.load_state_dict(ck['model'],strict=False)
19
+ assert not unexpected and all(k.startswith('confidence.') for k in missing)
20
+ for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.'))
21
+ params=[p for p in model.parameters() if p.requires_grad]
22
+ opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True)
23
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed)
24
+ (out/'config.json').write_text(json.dumps({**vars(a),'parameters':sum(p.numel() for p in model.parameters()),'trainable_parameters':sum(p.numel() for p in params)},indent=2))
25
+ rng=np.random.default_rng(a.seed)
26
+ def nextbatch():
27
+ c=int(rng.choice([512,1024,2048,4096],p=[.1,.15,.35,.4]));h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5]))
28
+ return sampler.sample(a.batch,c,h)
29
+ def save(step):
30
+ for prefix,weights in [('step',model.state_dict()),('ema',ema)]:
31
+ state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'}
32
+ path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path)
33
+ save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[]
34
+ for step in range(1,a.steps+1):
35
+ arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays]
36
+ lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps)))
37
+ for g in opt.param_groups:g['lr']=lr
38
+ opt.zero_grad(set_to_none=True)
39
+ with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p)
40
+ loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.)
41
+ if torch.isfinite(gn):
42
+ opt.step()
43
+ with torch.no_grad():
44
+ decay=min(.999,1-1/(step+1))
45
+ for k,v in model.state_dict().items():
46
+ if k.startswith('confidence.'):ema[k].lerp_(v,1-decay)
47
+ losses.append(float(loss.detach()))
48
+ if step%50==0:
49
+ rec={'step':step,'loss':float(np.mean(losses)),'seconds':round(time.time()-t0,1),'lr':lr,'grad_norm':float(gn),'context':x.shape[-1],'horizon':y.shape[-1]}
50
+ print(json.dumps(rec),flush=True)
51
+ with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n')
52
+ losses=[]
53
+ if step%a.save_every==0 or step==a.steps:save(step)
54
+ pool.shutdown()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/direct_large/data.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class Sampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ w=min(len(values),20_000_000)**.25
19
+ if name.startswith(('era5_','cmip6_')):w*=.35
20
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
21
+ weights.append(w)
22
+ self.probs=np.array(weights)/sum(weights)
23
+
24
+ def synthetic(self,n,p):
25
+ r=self.rng;t=np.arange(n,dtype=np.float32)
26
+ # New generator: damped trends, random Fourier seasonality, AR noise,
27
+ # intermittent demand, changepoints, and randomly scaled observation noise.
28
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
29
+ x=np.full(n,level,np.float32)
30
+ if r.random()<.8:
31
+ for period in p:
32
+ if period<2:continue
33
+ for k in range(1,int(r.integers(2,5))):
34
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
35
+ if r.random()<.6:
36
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
37
+ x+=slope*tau*(1-np.exp(-t/tau))
38
+ noise=r.normal(0,sigma,n).astype(np.float32)
39
+ if r.random()<.5:
40
+ from scipy.signal import lfilter
41
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
42
+ x+=noise
43
+ if r.random()<.2:
44
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
45
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
46
+ if r.random()<.1:x=np.maximum(0,x)
47
+ return x.astype(np.float32)
48
+
49
+ def sample(self,batch,context=2048,horizon=1024):
50
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
51
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
52
+ for b,d in enumerate(ds):
53
+ if r.random()<self.synthetic_fraction:
54
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
55
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
56
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
57
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
58
+ # Random cutoffs retain short sources, with unavailable future steps masked.
59
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
60
+ nc=min(context,cut)
61
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
62
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
63
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
64
+ if r.random()<.12 and l>=4*(context+horizon):
65
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
66
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
67
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
68
+ else:periods[b]=self.periods[d][i]
69
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
70
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
71
+ return ctx,tgt,periods
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/direct_large/model.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon)
51
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
52
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
53
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
54
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
55
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
56
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
57
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
58
+ with torch.no_grad():
59
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
60
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
61
+
62
+ @staticmethod
63
+ def standardize(ctx):
64
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
65
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
66
+ mu=x.sum(-1,keepdim=True)/count
67
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
68
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
69
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
70
+ return z,valid,mu,scale
71
+
72
+ @staticmethod
73
+ def features(z,valid,periods,h):
74
+ b,c=z.shape;dev=z.device
75
+ def avg(k):
76
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
77
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
78
+ last=z.gather(1,last_idx[:,None])[:,0]
79
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
80
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
81
+ t=torch.arange(h,device=dev)[None,:]
82
+ for j in range(2):
83
+ p=periods[:,j:j+1].clamp(min=1)
84
+ anchor=c-p+t%p
85
+ vals=[];masks=[]
86
+ for cycle in range(4):
87
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
88
+ ok=(idx>=0)&valid.gather(1,safe)
89
+ vals.append(z.gather(1,safe));masks.append(ok)
90
+ vals=torch.stack(vals);masks=torch.stack(masks)
91
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
92
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
93
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
94
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
95
+ k=min(128,max(4,c//4));recent=avg(k)
96
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
97
+ slope=((recent-older)/k).clamp(-.03,.03)
98
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
99
+ bases.append(trend)
100
+ return torch.stack(bases,-1)
101
+
102
+ def forward(self,ctx,periods,horizon):
103
+ p=self.patch;h=math.ceil(horizon/p)*p
104
+ ctx=ctx[:,-self.max_context:]
105
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
106
+ z,valid,mu,scale=self.standardize(ctx)
107
+ b,c=z.shape;nt=c//p
108
+ base=self.features(z,valid,periods,h)
109
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
110
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
111
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,torch.full((b,1),math.log1p(h)/8,device=z.device)),-1)
112
+ emb=self.metadata(meta)[:,None]
113
+ x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb
114
+ for layer in self.encoder:x=layer(x,pmask)
115
+ q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb
116
+ for layer in self.decoder:q=layer(q,pmask,x)
117
+ out=self.head(self.norm(q)).view(b,h,18).float()
118
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
119
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
120
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
121
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
122
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
123
+ return quant,mu,scale
124
+
125
+ @torch.no_grad()
126
+ def predict(self,ctx,periods,horizon):
127
+ q,mu,scale=self(ctx,periods,horizon)
128
+ q=q*scale[:,:,None]+mu[:,:,None]
129
+ # Positivity is a fixed context rule, as in released foundation forecasters.
130
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
131
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
132
+ return q.transpose(1,2)
133
+
134
+ def loss_fn(model,ctx,target,periods):
135
+ q,mu,scale=model(ctx,periods,target.shape[-1])
136
+ valid=torch.isfinite(target)
137
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
138
+ err=y[:,:,None]-q
139
+ levels=torch.arange(1,10,device=q.device)/10
140
+ pin=torch.maximum(levels*err,(levels-1)*err).mean(-1)
141
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
142
+ return per.mean()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/direct_large/pack.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data."""
2
+ import json,time,hashlib,concurrent.futures,argparse
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pyarrow as pa
6
+
7
+ ROOT=Path('/workspace/data/gifteval_pretrain')
8
+
9
+ def pack_dir(job):
10
+ name,out,cap=job
11
+ rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little'))
12
+ files=sorted((ROOT/name).glob('data-*.arrow'))
13
+ rng.shuffle(files)
14
+ # Spread large-source samples across eight shards rather than taking one contiguous slice.
15
+ files=files[:min(8,len(files))]
16
+ meta=[]; total=0; offsets=[0]; t0=time.time()
17
+ with open(out/f'{name}.bin','wb') as dest:
18
+ for file in files:
19
+ quota=max(1,cap//len(files)); kept=0
20
+ with pa.memory_map(str(file),'r') as f:
21
+ table=pa.ipc.open_stream(f).read_all()
22
+ freq=table.column('freq')[0].as_py() if table.num_rows else ''
23
+ for target in table.column('target').chunks:
24
+ if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type):
25
+ target=target.values
26
+ off=target.offsets.to_numpy()
27
+ flat=target.values.to_numpy(zero_copy_only=False)
28
+ ids=np.arange(len(target));rng.shuffle(ids)
29
+ for i in ids:
30
+ x=flat[off[i]:off[i+1]]
31
+ if len(x)<16 or not np.isfinite(x).any():continue
32
+ # Cap very long series at a random contiguous year-sized segment.
33
+ if len(x)>131072:
34
+ start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072]
35
+ x=np.asarray(x,dtype=np.float32)
36
+ x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total)
37
+ meta.append({'dataset':name,'freq':freq,'length':len(x)})
38
+ if kept>=quota:break
39
+ if kept>=quota:break
40
+ np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64))
41
+ (out/f'{name}.json').write_text(json.dumps(meta))
42
+ return name,total,len(meta),round(time.time()-t0,1)
43
+
44
+ def main():
45
+ ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--cap',type=int,default=16000000);ap.add_argument('--workers',type=int,default=6);a=ap.parse_args()
46
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
47
+ names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.'))
48
+ lock=json.loads(Path('/workspace/data/sources.lock.json').read_text())
49
+ allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories']
50
+ assert set(names)<=set(allowed)
51
+ with concurrent.futures.ThreadPoolExecutor(a.workers) as pool:
52
+ for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True)
53
+ counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names}
54
+ (out/'meta.json').write_text(json.dumps({'dirs':[n for n in names if counts[n]],'counts':counts,'per_directory_point_cap':a.cap,'seed':'sha256(directory) little-endian first 4 bytes','min_length':16},indent=2))
55
+
56
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/direct_large/train.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json,math,time,os,sys,shutil,hashlib
2
+ from pathlib import Path
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import numpy as np
5
+ import torch
6
+ from model import DirectForecaster,loss_fn
7
+ from data import Sampler
8
+
9
+ def save(model,path,step,args,opt=None):
10
+ ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)}
11
+ if opt is not None:ck['opt']=opt.state_dict()
12
+ tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path)
13
+
14
+ def main():
15
+ ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True)
16
+ ap.add_argument('--steps',type=int,default=12000);ap.add_argument('--batch',type=int,default=128);ap.add_argument('--context',type=int,default=4096)
17
+ ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3)
18
+ ap.add_argument('--lr',type=float,default=3e-4);ap.add_argument('--seed',type=int,default=17);ap.add_argument('--save-every',type=int,default=1000)
19
+ ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args()
20
+ torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed)
21
+ torch.backends.cuda.matmul.allow_tf32=True
22
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
23
+ model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda()
24
+ opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True)
25
+ # Exponential averaging is a training-only stabilization; inference remains fixed.
26
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()}
27
+ startstep=0
28
+ if a.resume:
29
+ ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step']
30
+ if 'opt' in ck:opt.load_state_dict(ck['opt'])
31
+ sampler=Sampler(a.packed,seed=a.seed+startstep)
32
+ params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2))
33
+ print('parameters',params,flush=True)
34
+ rng=np.random.default_rng(a.seed+startstep)
35
+ def nextbatch():
36
+ c=int(rng.choice([512,1024,2048,a.context],p=[.1,.15,.35,.4]));h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5]))
37
+ return sampler.sample(a.batch,c,h)
38
+ pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[]
39
+ for step in range(startstep+1,a.steps+1):
40
+ arrays=future.result();future=pool.submit(nextbatch)
41
+ x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays]
42
+ lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps))))
43
+ for g in opt.param_groups:g['lr']=lr
44
+ opt.zero_grad(set_to_none=True)
45
+ with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p)
46
+ loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
47
+ if torch.isfinite(gn):
48
+ opt.step()
49
+ with torch.no_grad():
50
+ decay=min(.999,1-1/(step+1))
51
+ for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay)
52
+ losses.append(float(loss.detach()))
53
+ if step%50==0:
54
+ rec={'step':step,'loss':float(np.mean(losses)),'seconds':round(time.time()-t0,1),'lr':lr,'grad_norm':float(gn),'context':x.shape[-1],'horizon':y.shape[-1]}
55
+ print(json.dumps(rec),flush=True)
56
+ with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n')
57
+ losses=[]
58
+ stop=a.stop_file and Path(a.stop_file).exists()
59
+ if step%a.save_every==0 or step==a.steps or stop:
60
+ save(model,out/f'step{step:06d}.pt',step,a)
61
+ save(model,out/'last.pt',step,a,opt)
62
+ ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True}
63
+ path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path)
64
+ if stop:break
65
+ pool.shutdown()
66
+
67
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/full_paired/data.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class BaseSampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values)
19
+ w=min(weight_points,20_000_000)**.25
20
+ if name.startswith(('era5_','cmip6_')):w*=.35
21
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
22
+ weights.append(w)
23
+ self.probs=np.array(weights)/sum(weights)
24
+
25
+ def synthetic(self,n,p):
26
+ r=self.rng;t=np.arange(n,dtype=np.float32)
27
+ # New generator: damped trends, random Fourier seasonality, AR noise,
28
+ # intermittent demand, changepoints, and randomly scaled observation noise.
29
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
30
+ x=np.full(n,level,np.float32)
31
+ if r.random()<.8:
32
+ for period in p:
33
+ if period<2:continue
34
+ for k in range(1,int(r.integers(2,5))):
35
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
36
+ if r.random()<.6:
37
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
38
+ x+=slope*tau*(1-np.exp(-t/tau))
39
+ noise=r.normal(0,sigma,n).astype(np.float32)
40
+ if r.random()<.5:
41
+ from scipy.signal import lfilter
42
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
43
+ x+=noise
44
+ if r.random()<.2:
45
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
46
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
47
+ if r.random()<.1:x=np.maximum(0,x)
48
+ return x.astype(np.float32)
49
+
50
+ def sample(self,batch,context=2048,horizon=1024):
51
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
52
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
53
+ for b,d in enumerate(ds):
54
+ if r.random()<self.synthetic_fraction:
55
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
56
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
57
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
58
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
59
+ # Random cutoffs retain short sources, with unavailable future steps masked.
60
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
61
+ nc=min(context,cut)
62
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
63
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
64
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
65
+ if r.random()<.12 and l>=4*(context+horizon):
66
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
67
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
68
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
69
+ else:periods[b]=self.periods[d][i]
70
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
71
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
72
+ sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1))
73
+ return ctx*sign,tgt*sign,periods
74
+
75
+
76
+ def truncate_targets(arrays,rng,patch=16):
77
+ """Random requested horizons; corpus windows and the original RNG remain unchanged."""
78
+ ctx,target,periods=arrays
79
+ h=target.shape[-1]
80
+ active=rng.random(len(target))<.5
81
+ end=rng.integers(max(1,h//4),h+1,size=len(target))
82
+ end=np.where(active,end,h)
83
+ end=np.minimum(h,((end+patch-1)//patch)*patch)
84
+ target=target.copy()
85
+ target[np.arange(h)[None,:]>=end[:,None]]=np.nan
86
+ return ctx,target,periods
87
+
88
+
89
+ class Sampler(BaseSampler):
90
+ def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None):
91
+ super().__init__(packed,seed,synthetic_fraction,source_weights_from)
92
+ self.horizon_rng=np.random.default_rng(seed+300003)
93
+ def sample(self,batch,context=2048,horizon=1024):
94
+ return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16)
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/full_paired/model.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None,future_mask=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True,confidence_features=True,partial_target_lengths=True):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon,recency_features=recency_features,confidence_features=confidence_features,partial_target_lengths=partial_target_lengths)
51
+ self.confidence=nn.Linear(6,d,bias=False)
52
+ nn.init.zeros_(self.confidence.weight)
53
+ self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None
54
+ if self.recency is not None:nn.init.zeros_(self.recency.weight)
55
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
56
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
57
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
58
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
59
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
60
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
61
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
62
+ with torch.no_grad():
63
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
64
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
65
+
66
+ @staticmethod
67
+ def standardize(ctx):
68
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
69
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
70
+ mu=x.sum(-1,keepdim=True)/count
71
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
72
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
73
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
74
+ return z,valid,mu,scale
75
+
76
+ @staticmethod
77
+ def features(z,valid,periods,h):
78
+ b,c=z.shape;dev=z.device
79
+ def avg(k):
80
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
81
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
82
+ last=z.gather(1,last_idx[:,None])[:,0]
83
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
84
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
85
+ t=torch.arange(h,device=dev)[None,:]
86
+ for j in range(2):
87
+ p=periods[:,j:j+1].clamp(min=1)
88
+ anchor=c-p+t%p
89
+ vals=[];masks=[]
90
+ for cycle in range(4):
91
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
92
+ ok=(idx>=0)&valid.gather(1,safe)
93
+ vals.append(z.gather(1,safe));masks.append(ok)
94
+ vals=torch.stack(vals);masks=torch.stack(masks)
95
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
96
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
97
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
98
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
99
+ k=128;recent=avg(k) # Match the training width, independently of padding.
100
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
101
+ slope=((recent-older)/k).clamp(-.03,.03)
102
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
103
+ bases.append(trend)
104
+ return torch.stack(bases,-1)
105
+
106
+ def forward(self,ctx,periods,horizon,forecast_lengths=None):
107
+ p=self.patch;h=math.ceil(horizon/p)*p
108
+ ctx=ctx[:,-self.max_context:]
109
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
110
+ z,valid,mu,scale=self.standardize(ctx)
111
+ b,c=z.shape;nt=c//p
112
+ base=self.features(z,valid,periods,h)
113
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
114
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
115
+ future_mask=None
116
+ horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device)
117
+ if forecast_lengths is not None:
118
+ patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p)
119
+ future_mask=torch.arange(h//p,device=z.device)[None,:]<patch_count[:,None]
120
+ horizon_meta=(patch_count*p).clamp(min=32).float().log1p()[:,None]/8
121
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,horizon_meta),-1)
122
+ emb=self.metadata(meta)[:,None]
123
+ x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
124
+ for layer in self.encoder:x=layer(x,pmask)
125
+ q=self.query(base.reshape(b,h//p,p*9))+positional((torch.arange(h//p,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
126
+ if self.recency is not None:
127
+ pos=torch.arange(c,device=z.device)[None,:];extras=[]
128
+ for j in range(2):
129
+ period=periods[:,j:j+1]
130
+ recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period)
131
+ nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1)
132
+ mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool
133
+ sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt()
134
+ sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4)
135
+ active=(period>=2)&(npool>=3*period)
136
+ shift=torch.where(active,mr-mp,0.).expand(-1,h)
137
+ amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.)
138
+ extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude])
139
+ extra=torch.stack(extras,-1)
140
+ q=q+self.recency(extra.reshape(b,h//p,p*4))
141
+ # Fixed normalized difference statistics expose local and seasonal repeatability.
142
+ pos=torch.arange(c,device=z.device)[None,:];stats=[]
143
+ for j in range(3):
144
+ lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j]
145
+ window=torch.full_like(lag,512) if j==0 else 8*lag
146
+ idx=pos-lag;safe=idx.clamp(min=0,max=c-1)
147
+ pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe)
148
+ count=pairs.sum(-1);difference=z-z.gather(1,safe)
149
+ absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1)
150
+ rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt()
151
+ absolute=torch.where(count>=8,absolute,1.)
152
+ rms=torch.where(count>=8,rms,math.sqrt(2.))
153
+ stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()])
154
+ q=q+self.confidence(torch.stack(stats,-1))[:,None]
155
+ for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask)
156
+ out=self.head(self.norm(q)).view(b,h,18).float()
157
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
158
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
159
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
160
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
161
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
162
+ return quant,mu,scale
163
+
164
+ @torch.no_grad()
165
+ def predict(self,ctx,periods,horizon):
166
+ q,mu,scale=self(ctx,periods,horizon)
167
+ q=q*scale[:,:,None]+mu[:,:,None]
168
+ # Positivity is a fixed context rule, as in released foundation forecasters.
169
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
170
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
171
+ return q.transpose(1,2)
172
+
173
+ def loss_fn(model,ctx,target,periods,paired=True):
174
+ n=ctx.shape[0]
175
+ seen=torch.isfinite(target)
176
+ pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1
177
+ lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1)
178
+ q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2))
179
+ if paired:
180
+ q=(q[:n]-q[n:].flip(-1))*.5
181
+ mu=mu[:n];scale=scale[:n]
182
+ else:
183
+ ctx=torch.cat((ctx,-ctx),0)
184
+ target=torch.cat((target,-target),0)
185
+ periods=periods.repeat(2,1)
186
+ valid=torch.isfinite(target)
187
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
188
+ err=y[:,:,None]-q
189
+ levels=torch.arange(1,10,device=q.device)/10
190
+ # The evaluation gives equal importance to median MASE and average quantile loss.
191
+ pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs()
192
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
193
+ # A context-only seasonal scale makes highly predictable windows count more.
194
+ # It is used solely in the training loss; no inference adaptation is introduced.
195
+ with torch.no_grad():
196
+ z,seen,_,_=model.standardize(ctx)
197
+ n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:]
198
+ lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0)
199
+ pairs=(idx>=0)&seen&seen.gather(1,safe)
200
+ count=pairs.sum(-1)
201
+ errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1)
202
+ errscale=torch.where(count>=8,errscale,1.)
203
+ weight=(.25+errscale).reciprocal().clamp(.25,4.)
204
+ return (per*weight).sum()/weight.sum()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/horizon_jitter/data.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class Sampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values)
19
+ w=min(weight_points,20_000_000)**.25
20
+ if name.startswith(('era5_','cmip6_')):w*=.35
21
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
22
+ weights.append(w)
23
+ self.probs=np.array(weights)/sum(weights)
24
+
25
+ def synthetic(self,n,p):
26
+ r=self.rng;t=np.arange(n,dtype=np.float32)
27
+ # New generator: damped trends, random Fourier seasonality, AR noise,
28
+ # intermittent demand, changepoints, and randomly scaled observation noise.
29
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
30
+ x=np.full(n,level,np.float32)
31
+ if r.random()<.8:
32
+ for period in p:
33
+ if period<2:continue
34
+ for k in range(1,int(r.integers(2,5))):
35
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
36
+ if r.random()<.6:
37
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
38
+ x+=slope*tau*(1-np.exp(-t/tau))
39
+ noise=r.normal(0,sigma,n).astype(np.float32)
40
+ if r.random()<.5:
41
+ from scipy.signal import lfilter
42
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
43
+ x+=noise
44
+ if r.random()<.2:
45
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
46
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
47
+ if r.random()<.1:x=np.maximum(0,x)
48
+ return x.astype(np.float32)
49
+
50
+ def sample(self,batch,context=2048,horizon=1024):
51
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
52
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
53
+ for b,d in enumerate(ds):
54
+ if r.random()<self.synthetic_fraction:
55
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
56
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
57
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
58
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
59
+ # Random cutoffs retain short sources, with unavailable future steps masked.
60
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
61
+ nc=min(context,cut)
62
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
63
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
64
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
65
+ if r.random()<.12 and l>=4*(context+horizon):
66
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
67
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
68
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
69
+ else:periods[b]=self.periods[d][i]
70
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
71
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
72
+ sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1))
73
+ return ctx*sign,tgt*sign,periods
74
+
75
+
76
+ def truncate_targets(arrays,rng,patch=16):
77
+ """Random requested horizons; corpus windows and the original RNG remain unchanged."""
78
+ ctx,target,periods=arrays
79
+ h=target.shape[-1]
80
+ active=rng.random(len(target))<.5
81
+ end=rng.integers(max(1,h//4),h+1,size=len(target))
82
+ end=np.where(active,end,h)
83
+ end=np.minimum(h,((end+patch-1)//patch)*patch)
84
+ target=target.copy()
85
+ target[np.arange(h)[None,:]>=end[:,None]]=np.nan
86
+ return ctx,target,periods
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/horizon_jitter/model.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features."""
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def periods_for_freq(freq):
8
+ import re
9
+ m=re.match(r'^(\d*)([A-Za-z]+)',str(freq));n=int(m[1] or 1) if m else 1;u=m[2] if m else 'D'
10
+ if u in ('s','S'):p=(3600/n,86400/n)
11
+ elif u in ('T','min'):p=(1440/n,10080/n)
12
+ elif u in ('H','h'):p=(24/n,168/n)
13
+ elif u=='D':p=(7/n,365/n)
14
+ elif u=='B':p=(5/n,260/n)
15
+ elif u=='W':p=(52/n,1)
16
+ elif u in ('M','MS','ME'):p=(12/n,1)
17
+ elif u in ('Q','QS','QE'):p=(4/n,1)
18
+ else:p=(1,1)
19
+ return [max(1,round(x)) for x in p]
20
+
21
+ def positional(pos,d):
22
+ freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d))
23
+ a=pos.float()[...,None]*freq
24
+ return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2)
25
+
26
+ class Attention(nn.Module):
27
+ def __init__(self,d,heads):
28
+ super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d)
29
+ def forward(self,x,context,mask=None):
30
+ b,t,d=x.shape;s=context.shape[1]
31
+ q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2)
32
+ k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0)
33
+ a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:])
34
+ return self.out(a.transpose(1,2).reshape(b,t,d))
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self,d,heads,cross=False):
38
+ super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads)
39
+ self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
40
+ self.cross=Attention(d,heads) if cross else None
41
+ if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d)
42
+ def forward(self,x,mask=None,context=None,future_mask=None):
43
+ y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask)
44
+ if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask)
45
+ return x+self.ff(self.norm2(x))
46
+
47
+ class DirectForecaster(nn.Module):
48
+ def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True,partial_target_lengths=True):
49
+ super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon
50
+ self.config=dict(d=d,heads=heads,enc_layers=enc_layers,dec_layers=dec_layers,patch=patch,max_context=max_context,max_horizon=max_horizon,recency_features=recency_features,partial_target_lengths=partial_target_lengths)
51
+ self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None
52
+ if self.recency is not None:nn.init.zeros_(self.recency.weight)
53
+ self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d))
54
+ self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d))
55
+ self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d))
56
+ self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers))
57
+ self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers))
58
+ self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18)
59
+ nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias)
60
+ with torch.no_grad():
61
+ bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22))
62
+ bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.])
63
+
64
+ @staticmethod
65
+ def standardize(ctx):
66
+ valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.)
67
+ count=valid.sum(-1,keepdim=True).clamp(min=1)
68
+ mu=x.sum(-1,keepdim=True)/count
69
+ var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count
70
+ scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4)
71
+ z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30)
72
+ return z,valid,mu,scale
73
+
74
+ @staticmethod
75
+ def features(z,valid,periods,h):
76
+ b,c=z.shape;dev=z.device
77
+ def avg(k):
78
+ return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1)
79
+ last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0)
80
+ last=z.gather(1,last_idx[:,None])[:,0]
81
+ small=avg(32);medium=avg(128);level=avg(min(1024,c))
82
+ bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)]
83
+ t=torch.arange(h,device=dev)[None,:]
84
+ for j in range(2):
85
+ p=periods[:,j:j+1].clamp(min=1)
86
+ anchor=c-p+t%p
87
+ vals=[];masks=[]
88
+ for cycle in range(4):
89
+ idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1)
90
+ ok=(idx>=0)&valid.gather(1,safe)
91
+ vals.append(z.gather(1,safe));masks.append(ok)
92
+ vals=torch.stack(vals);masks=torch.stack(masks)
93
+ avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1)
94
+ avgseason=torch.where(masks.any(0),avgseason,level[:,None])
95
+ bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason])
96
+ # A damped slope using two recent nonoverlapping means, a fixed transformation.
97
+ k=min(128,max(4,c//4));recent=avg(k)
98
+ older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1)
99
+ slope=((recent-older)/k).clamp(-.03,.03)
100
+ trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k)))
101
+ bases.append(trend)
102
+ return torch.stack(bases,-1)
103
+
104
+ def forward(self,ctx,periods,horizon,forecast_lengths=None):
105
+ p=self.patch;h=math.ceil(horizon/p)*p
106
+ ctx=ctx[:,-self.max_context:]
107
+ ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan'))
108
+ z,valid,mu,scale=self.standardize(ctx)
109
+ b,c=z.shape;nt=c//p
110
+ base=self.features(z,valid,periods,h)
111
+ x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1))
112
+ pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True
113
+ future_mask=None
114
+ horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device)
115
+ if forecast_lengths is not None:
116
+ patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p)
117
+ future_mask=torch.arange(h//p,device=z.device)[None,:]<patch_count[:,None]
118
+ horizon_meta=(patch_count*p).clamp(min=32).float().log1p()[:,None]/8
119
+ meta=torch.cat((periods.float().log1p()/8,valid.sum(-1,keepdim=True).float().log1p()/8,horizon_meta),-1)
120
+ emb=self.metadata(meta)[:,None]
121
+ x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
122
+ for layer in self.encoder:x=layer(x,pmask)
123
+ q=self.query(base.reshape(b,h//p,p*9))+positional((torch.arange(h//p,device=z.device)+.5)*p/32-.5,self.d)[None]+emb
124
+ if self.recency is not None:
125
+ pos=torch.arange(c,device=z.device)[None,:];extras=[]
126
+ for j in range(2):
127
+ period=periods[:,j:j+1]
128
+ recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period)
129
+ nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1)
130
+ mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool
131
+ sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt()
132
+ sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4)
133
+ active=(period>=2)&(npool>=3*period)
134
+ shift=torch.where(active,mr-mp,0.).expand(-1,h)
135
+ amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.)
136
+ extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude])
137
+ extra=torch.stack(extras,-1)
138
+ q=q+self.recency(extra.reshape(b,h//p,p*4))
139
+ for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask)
140
+ out=self.head(self.norm(q)).view(b,h,18).float()
141
+ median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9]
142
+ widths=F.softplus(out[:,:,10:]).clamp(max=20)
143
+ low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1)
144
+ high=median[:,:,None]+widths[:,:,4:].cumsum(-1)
145
+ quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon]
146
+ return quant,mu,scale
147
+
148
+ @torch.no_grad()
149
+ def predict(self,ctx,periods,horizon):
150
+ q,mu,scale=self(ctx,periods,horizon)
151
+ q=q*scale[:,:,None]+mu[:,:,None]
152
+ # Positivity is a fixed context rule, as in released foundation forecasters.
153
+ positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1)
154
+ q=torch.where(positive[:,None,None],q.clamp(min=0),q)
155
+ return q.transpose(1,2)
156
+
157
+ def loss_fn(model,ctx,target,periods):
158
+ seen=torch.isfinite(target)
159
+ pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1
160
+ lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1)
161
+ q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths)
162
+ valid=torch.isfinite(target)
163
+ y=torch.nan_to_num((target-mu)/scale).clamp(-30,30)
164
+ err=y[:,:,None]-q
165
+ levels=torch.arange(1,10,device=q.device)/10
166
+ # The evaluation gives equal importance to median MASE and average quantile loss.
167
+ pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs()
168
+ per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1)
169
+ # A context-only seasonal scale makes highly predictable windows count more.
170
+ # It is used solely in the training loss; no inference adaptation is introduced.
171
+ with torch.no_grad():
172
+ z,seen,_,_=model.standardize(ctx)
173
+ n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:]
174
+ lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0)
175
+ pairs=(idx>=0)&seen&seen.gather(1,safe)
176
+ count=pairs.sum(-1)
177
+ errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1)
178
+ errscale=torch.where(count>=8,errscale,1.)
179
+ weight=(.25+errscale).reciprocal().clamp(.25,4.)
180
+ return (per*weight).sum()/weight.sum()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/horizon_jitter/train.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json,math,time,os,sys,shutil,hashlib
2
+ from pathlib import Path
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import numpy as np
5
+ import torch
6
+ from model import DirectForecaster,loss_fn
7
+ from data import Sampler,truncate_targets
8
+
9
+ def save(model,path,step,args,opt=None):
10
+ ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)}
11
+ if opt is not None:ck['opt']=opt.state_dict()
12
+ tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path)
13
+
14
+ def main():
15
+ ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True)
16
+ ap.add_argument('--source-weights-from',required=True);ap.add_argument('--steps',type=int,default=12000);ap.add_argument('--batch',type=int,default=128);ap.add_argument('--context',type=int,default=4096)
17
+ ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3)
18
+ ap.add_argument('--patch',type=int,default=32)
19
+ ap.add_argument('--lr',type=float,default=3e-4);ap.add_argument('--seed',type=int,default=17);ap.add_argument('--save-every',type=int,default=1000)
20
+ ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args()
21
+ torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed)
22
+ torch.backends.cuda.matmul.allow_tf32=True
23
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
24
+ model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda()
25
+ opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True)
26
+ # Exponential averaging is a training-only stabilization; inference remains fixed.
27
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()}
28
+ startstep=0
29
+ if a.resume:
30
+ ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step']
31
+ if 'opt' in ck:opt.load_state_dict(ck['opt'])
32
+ if a.initialize_from:
33
+ ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False)
34
+ missing,unexpected=model.load_state_dict(ck['model'],strict=False)
35
+ assert not unexpected and all(k.startswith('recency.') for k in missing)
36
+ ema={k:v.detach().clone() for k,v in model.state_dict().items()}
37
+ sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from)
38
+ params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2))
39
+ print('parameters',params,flush=True)
40
+ rng=np.random.default_rng(a.seed+startstep)
41
+ horizon_rng=np.random.default_rng(a.seed+startstep+300003)
42
+ def nextbatch():
43
+ c=int(rng.choice([512,1024,2048,a.context],p=[.1,.15,.35,.4]));h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5]))
44
+ return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch)
45
+ pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[]
46
+ for step in range(startstep+1,a.steps+1):
47
+ arrays=future.result();future=pool.submit(nextbatch)
48
+ x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays]
49
+ lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps))))
50
+ for g in opt.param_groups:g['lr']=lr
51
+ opt.zero_grad(set_to_none=True)
52
+ with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p)
53
+ loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
54
+ if torch.isfinite(gn):
55
+ opt.step()
56
+ with torch.no_grad():
57
+ decay=min(.999,1-1/(step+1))
58
+ for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay)
59
+ losses.append(float(loss.detach()))
60
+ if step%50==0:
61
+ rec={'step':step,'loss':float(np.mean(losses)),'seconds':round(time.time()-t0,1),'lr':lr,'grad_norm':float(gn),'context':x.shape[-1],'horizon':y.shape[-1]}
62
+ print(json.dumps(rec),flush=True)
63
+ with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n')
64
+ losses=[]
65
+ stop=a.stop_file and Path(a.stop_file).exists()
66
+ if step%a.save_every==0 or step==a.steps or stop:
67
+ save(model,out/f'step{step:06d}.pt',step,a)
68
+ save(model,out/'last.pt',step,a,opt)
69
+ ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True}
70
+ path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path)
71
+ if stop:break
72
+ pool.shutdown()
73
+
74
+ if __name__=='__main__':main()
tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S041/provenance/large_corpus/data.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,re
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from model import periods_for_freq
5
+
6
+ class Sampler:
7
+ def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None):
8
+ self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction
9
+ self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs']
10
+ self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[]
11
+ for name in self.dirs:
12
+ records=json.loads((self.root/f'{name}.json').read_text())
13
+ values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r')
14
+ offsets=np.load(self.root/f'{name}.offsets.npy')
15
+ self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets))
16
+ self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64))
17
+ # Temperature 0.25 protects small, distinctive and low-frequency corpora.
18
+ weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values)
19
+ w=min(weight_points,20_000_000)**.25
20
+ if name.startswith(('era5_','cmip6_')):w*=.35
21
+ if name.startswith(('m1_','monash_m3_','tourism_')):w*=3
22
+ weights.append(w)
23
+ self.probs=np.array(weights)/sum(weights)
24
+
25
+ def synthetic(self,n,p):
26
+ r=self.rng;t=np.arange(n,dtype=np.float32)
27
+ # New generator: damped trends, random Fourier seasonality, AR noise,
28
+ # intermittent demand, changepoints, and randomly scaled observation noise.
29
+ level=r.normal(0,2);sigma=10**r.uniform(-2,.1)
30
+ x=np.full(n,level,np.float32)
31
+ if r.random()<.8:
32
+ for period in p:
33
+ if period<2:continue
34
+ for k in range(1,int(r.integers(2,5))):
35
+ x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi))
36
+ if r.random()<.6:
37
+ slope=r.normal(0,.006);tau=10**r.uniform(2,4)
38
+ x+=slope*tau*(1-np.exp(-t/tau))
39
+ noise=r.normal(0,sigma,n).astype(np.float32)
40
+ if r.random()<.5:
41
+ from scipy.signal import lfilter
42
+ phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise)
43
+ x+=noise
44
+ if r.random()<.2:
45
+ start=int(r.integers(n));x[start:]+=r.normal(0,1)
46
+ if r.random()<.15:x=np.maximum(0,x)*(r.random(n)<r.uniform(.05,.5))
47
+ if r.random()<.1:x=np.maximum(0,x)
48
+ return x.astype(np.float32)
49
+
50
+ def sample(self,batch,context=2048,horizon=1024):
51
+ r=self.rng;ctx=np.full((batch,context),np.nan,np.float32);tgt=np.full((batch,horizon),np.nan,np.float32);periods=np.ones((batch,2),np.int64)
52
+ ds=r.choice(len(self.dirs),batch,p=self.probs)
53
+ for b,d in enumerate(ds):
54
+ if r.random()<self.synthetic_fraction:
55
+ p=[[1,1],[4,1],[12,1],[7,365],[24,168],[48,336],[96,672],[144,1008],[288,2016],[360,8640]][int(r.integers(10))]
56
+ nctx=int(r.integers(8,context+1)) if r.random()<.3 else context
57
+ series=self.synthetic(nctx+horizon,p);ctx[b,-nctx:]=series[:nctx];tgt[b]=series[nctx:];periods[b]=p;continue
58
+ lengths=self.lengths[d];i=int(r.integers(len(lengths)));l=int(lengths[i]);off=self.offsets[d][i]
59
+ # Random cutoffs retain short sources, with unavailable future steps masked.
60
+ maxh=min(horizon,max(1,l//3));cut=int(r.integers(8,max(9,l-maxh+1)))
61
+ nc=min(context,cut)
62
+ if r.random()<.25:nc=int(r.integers(8,nc+1)) if nc>8 else nc
63
+ nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy()
64
+ # Random aggregation teaches the same dynamics at coarser sampling frequencies.
65
+ if r.random()<.12 and l>=4*(context+horizon):
66
+ factor=int(r.choice([2,4]));end=int(r.integers(factor*(context+horizon),l+1));raw=self.values[d][off+end-factor*(context+horizon):off+end]
67
+ win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon
68
+ periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64)
69
+ else:periods[b]=self.periods[d][i]
70
+ ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh]
71
+ if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan
72
+ sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1))
73
+ return ctx*sign,tgt*sign,periods